本文整理汇总了PHP中Form::validate方法的典型用法代码示例。如果您正苦于以下问题:PHP Form::validate方法的具体用法?PHP Form::validate怎么用?PHP Form::validate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Form
的用法示例。
在下文中一共展示了Form::validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testUploadMissingRequiredFile
/**
* Test different scenarii for a failed upload : an error occured, no files where provided
*/
public function testUploadMissingRequiredFile()
{
$form = new Form(new Controller(), 'Form', new FieldSet($fileField = new FileField('cv', 'Upload your CV')), new FieldSet(), new RequiredFields('cv'));
// All fields are filled but for some reason an error occured when uploading the file => fails
$fileFieldValue = array('name' => 'aCV.txt', 'type' => 'application/octet-stream', 'tmp_name' => '/private/var/tmp/phpzTQbqP', 'error' => 1, 'size' => 3471);
$fileField->setValue($fileFieldValue);
$this->assertFalse($form->validate(), 'An error occured when uploading a file, but the validator returned true');
// We pass an empty set of parameters for the uploaded file => fails
$fileFieldValue = array();
$fileField->setValue($fileFieldValue);
$this->assertFalse($form->validate(), 'An empty array was passed as parameter for an uploaded file, but the validator returned true');
// We pass an null value for the uploaded file => fails
$fileFieldValue = null;
$fileField->setValue($fileFieldValue);
$this->assertFalse($form->validate(), 'A null value was passed as parameter for an uploaded file, but the validator returned true');
}
示例2: action
/**
* The action that displays the entry insert form .
*
* @param PDO $pdo The PDO object.
* @return Opt_View
*/
function action($pdo, $config)
{
$view = new Opt_View('add.tpl');
$view->title = 'Add new entry';
$form = new Form($view);
$form->setAction('index.php?action=add');
$form->addField('author', 'required,min_len=3,max_len=30', 'The length must be between 3 and 30 characters.');
$form->addField('email', 'required,email,min_len=3,max_len=100', 'The value must be a valid mail with maximum 100 characters long.');
$form->addField('website', 'url,min_len=3,max_len=100', 'The value must be a valid URL with maximum 100 characters long.');
$form->addField('body', 'required,min_len=3', 'The body must be at least 3 characters long.');
if ($form->validate()) {
$values = $form->getValues();
$stmt = $pdo->prepare('INSERT INTO `entries` (`author`, `email`, `date`, `website`, `body`)
VALUES(:author, :email, :date, :website, :body)');
$stmt->bindValue(':author', $values['author'], PDO::PARAM_STR);
$stmt->bindValue(':email', $values['email'], PDO::PARAM_STR);
$stmt->bindValue(':date', time(), PDO::PARAM_INT);
$stmt->bindValue(':website', $values['website'], PDO::PARAM_STR);
$stmt->bindValue(':body', $values['body'], PDO::PARAM_STR);
$stmt->execute();
$view->setTemplate('message.tpl');
$view->message = 'The entry has been successfully added!';
$view->redirect = 'index.php?action=list';
} else {
// The form is an object, so we need to inform OPT about it.
$view->form = $form;
$view->setFormat('form', 'Objective');
}
return $view;
}
示例3: action_edit
public function action_edit()
{
$type = $this->request->param('id');
$id = Arr::get($_GET, 'id');
$uoms = DB::select('id', 'name')->from('uoms')->execute()->as_array('id', 'name');
$form = new Form('items/edit/' . $type . '?id=' . ($id ?: ''));
$form->add('code', 'Code', Form::STRING, '', array('not_empty'))->add('name', 'Name', Form::STRING, '', array('not_empty'));
if ($type == 'item') {
$table = 'items';
$form->add('descr', 'Description', Form::TEXT);
} else {
$table = 'bom_items';
}
$form->add('uom', 'UOM', Form::SELECT, array(0 => 'Not selected') + $uoms);
$item = DB::select()->from($table)->where('id', '=', $id)->execute()->current();
$form->values($item);
if ($_POST) {
$value = $form->filter($_POST);
if (!$form->validate($value)) {
if ($id) {
DB::update($table)->set($value)->where('id', '=', $id)->execute();
} else {
$id = Arr::get(DB::insert($table, array_keys($value))->values(array_values($value))->execute(), 0, 0);
}
$value['id'] = $id;
$value['success'] = true;
$value['uom'] = Arr::get($uoms, $value['uom'], 'Unknown');
if (isset($value['descr'])) {
$value['descr'] = nl2br($value['descr']);
}
die(json_encode($value));
}
}
$this->response->body($form->render());
}
示例4: update
public function update($id)
{
$filename = get('filename');
$page = $this->page($id);
if (!$page) {
return response::error(l('files.error.missing.page'));
}
$file = $page->file($filename);
if (!$file) {
return response::error(l('files.error.missing.file'));
}
$blueprint = blueprint::find($page);
$fields = $blueprint->files()->fields($page);
// trigger the validation
$form = new Form($fields->toArray());
$form->validate();
// fetch the form data
$data = filedata::createByInput($file, $form->serialize());
// stop at invalid fields
if (!$form->isValid()) {
return response::error(l('files.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name')));
}
try {
$file->update($data, app::$language);
return response::success('success', array('data' => $data));
} catch (Exception $e) {
return response::error($e->getMessage());
}
}
示例5: action_edit
public function action_edit()
{
$id = $this->request->param('id');
$form = new Form('security/groups/edit' . ($id ? '/' . $id : ''));
$form->add("name", 'Name', Form::STRING, '', array('not_empty'))->add('is_admin', 'Administrative group', Form::BOOL)->add('show_all_jobs', 'Show all jobs (unchecked - show only assigned jobs)', Form::BOOL)->add('allow_assign', 'Allow assigning jobs', Form::BOOL)->add('allow_reports', 'Allow tracking changes', Form::BOOL)->add('allow_submissions', 'Allow tracking submissions', Form::BOOL)->add('allow_finance', 'Financial reports', Form::BOOL)->add('allow_forms', 'Forms submission', Form::BOOL)->add('allow_custom_forms', 'Custom forms submission', Form::BOOL)->add('edit_custom_forms', 'Edit custom forms reports', Form::BOOL)->add('time_machine', 'Time Machine', Form::BOOL);
$form->add('columns', 'Show columns in job search', Form::INFO);
foreach (Columns::$fixed as $key => $value) {
$form->add($key, $value, Form::BOOL);
}
$item = $id ? Group::get($id) : array();
if ($item) {
$columns = explode(',', $item['columns']);
foreach ($columns as $column) {
$item[$column] = 1;
}
unset($item['columns']);
}
$form->values($item);
if ($_POST) {
$value = $form->filter($_POST);
if ($value['is_admin']) {
$value['show_all_jobs'] = 1;
$value['allow_assign'] = 1;
$value['allow_reports'] = 1;
$value['allow_submissions'] = 1;
$value['allow_finance'] = 1;
$value['allow_forms'] = 0;
$value['allow_custom_forms'] = 1;
$value['edit_custom_forms'] = 1;
$value['time_machine'] = 1;
$value['columns'] = implode(',', array_keys(Columns::$fixed));
} else {
$columns = array();
foreach (Columns::$fixed as $key => $name) {
if (Arr::get($value, $key)) {
$columns[] = $key;
}
}
$value['columns'] = implode(',', $columns);
}
$value = array_diff_key($value, Columns::$fixed);
if (!$form->validate($value)) {
if ($id) {
DB::update('groups')->set($value)->where('id', '=', $id)->execute();
} else {
$origin = Arr::get($_POST, 'permissions');
unset($_POST['permissions']);
$id = Arr::get(DB::insert('groups', array_keys($value))->values(array_values($value))->execute(), 0);
DB::query(Database::INSERT, DB::expr("INSERT INTO `group_columns` (`group_id`, `column_id`, `permissions`) \n (SELECT :id, `column_id`, `permissions` FROM `group_columns` WHERE `group_id` = :origin)")->param(':id', $id)->param(':origin', $origin)->compile())->execute();
}
Messages::save('Group successfully saved!', 'success');
$this->redirect('/security/groups');
}
}
if (!$id) {
$groups = DB::select('id', 'name')->from('groups')->execute()->as_array('id', 'name');
$form->add('permissions', 'Copy permissions from group', Form::SELECT, $groups);
}
$this->response->body($form->render());
}
示例6: getAdminInterface
public function getAdminInterface()
{
$st = "select ecomm_product.id as product_id, ecomm_product.name as product_name,\n\t\t\t\tecomm_product.supplier as supplier_id, ecomm_supplier.name as supplier_name, ecomm_product.price as product_price\n\t\t\t\tfrom ecomm_product left join ecomm_supplier on ecomm_product.supplier = ecomm_supplier.id\n\t\t\t\torder by ecomm_supplier.name,ecomm_product.name";
$products = Database::singleton()->query_fetch_all($st);
$formPath = "/admin/EComm§ion=Plugins&page=ChangeProductPrice";
$form = new Form('change_product_prices', 'post', $formPath);
if ($form->validate() && isset($_REQUEST['submit'])) {
foreach ($products as $product) {
$ECommProduct = new Product($product['product_id']);
$ECommProduct->setPrice($_REQUEST['product_' . $product['product_id']]);
$ECommProduct->save();
}
return "Your products' prices have been changed successfully<br/><a href='{$formPath}'>Go back</a>";
}
$oldSupplier = 0;
$currentSupplier = 0;
$defaultValue = array();
foreach ($products as $product) {
$currentSupplier = $product['supplier_id'];
if ($oldSupplier != $currentSupplier) {
$form->addElement('html', '<br/><br/><hr/><h3>Supplier: ' . $product['supplier_name'] . '</h3>');
}
$form->addElement('text', 'product_' . $product['product_id'], $product['product_name']);
$defaultValue['product_' . $product['product_id']] = $product['product_price'];
$oldSupplier = $product['supplier_id'];
}
$form->addElement('submit', 'submit', 'Submit');
$form->setDefaults($defaultValue);
return $form->display();
}
示例7: getRegisterForm
public function getRegisterForm($target = '/Vote/register')
{
$form = new Form('group_register', 'POST', $target, '', array('class' => 'admin'));
$form->addElement('text', 'first_name', 'First Name');
$form->addElement('text', 'last_name', 'Last Name');
$form->addElement('text', 'company', 'Company/Group');
$form->addElement('text', 'email', 'E-mail');
$form->addElement('text', 'phone', 'Work Phone');
$form->addElement('text', 'cell_phone', 'Cell Phone');
$form->addElement('submit', 'register_submit', 'Submit');
$form->addRule('first_name', 'Please enter your first name', 'required');
$form->addRule('last_name', 'Please enter your last name', 'required');
$form->addRule('company', 'Please enter your company/group', 'required');
$form->addRule('email', 'Please enter your e-mail address', 'required');
$form->addRule('email', 'Please enter a valid email address', 'email');
$form->addRule('phone', 'Please enter your phone number', 'required');
if ($form->validate() && $form->isSubmitted() && isset($_REQUEST['register_submit'])) {
$body = "New registration request: \n\n";
$body .= "Name: " . $form->exportValue('last_name') . ', ' . $form->exportValue('first_name');
$body .= "\nCompany/Group: " . $form->exportValue('company');
$body .= "\nE-mail address: " . $form->exportValue('email');
$body .= "\nPhone number(s): Work - " . $form->exportValue('phone') . ', Cell - ' . $form->exportValue('cell_phone');
$body .= "\n\nRequest sent on " . date("w F jS \\a\\t g:ia");
mail('register@safeballot.com', 'Safeballot: New Request', $body, 'From: no-reply@safeballot.com');
}
return $form;
}
示例8: isValid
/**
* If this field is linked to a form and validate is defined,
* this will return true/false otherwise null
* @return null|bool
*/
public function isValid()
{
if (!is_null($this->form)) {
return $this->form->validate($this->getName(true), $this->getValue());
}
return null;
}
示例9: update
public function update($id = '')
{
$page = $this->page($id);
if (!$page) {
return response::error(l('pages.error.missing'));
}
$blueprint = blueprint::find($page);
$fields = $blueprint->fields($page);
$oldTitle = (string) $page->title();
// trigger the validation
$form = new Form($fields->toArray());
$form->validate();
// fetch the data for the form
$data = pagedata::createByInput($page, $form->serialize());
// stop at invalid fields
if (!$form->isValid()) {
return response::error(l('pages.show.error.form'), 400, array('fields' => $form->fields()->filterBy('error', true)->pluck('name')));
}
try {
$page->update($data);
// make sure that the sorting number is correct
if ($page->isVisible()) {
$num = api::createPageNum($page);
if ($num !== $page->num()) {
if ($num > 0) {
$page->sort($num);
}
}
}
history::visit($page->id());
return response::success('success', array('file' => $page->content()->root(), 'data' => $data, 'uid' => $page->uid(), 'uri' => $page->id()));
} catch (Exception $e) {
return response::error($e->getMessage());
}
}
示例10: init
public function init()
{
parent::init();
$id = __CLASS__ . $this->params['content']->id;
$this->params['profileVar'] = $this->urlParam('view');
$blank = true;
if (Yii::app()->request->getParam($this->params['profileVar']) !== null) {
$profile = User::model()->findByPk(intval(Yii::app()->request->getParam($this->params['profileVar'])));
if ($profile) {
$this->params['details'] = Yii::app()->controller->widget('zii.widgets.CDetailView', array('data' => $profile, 'attributes' => $this->makeFields($this->params['content']->displayed_fields, $profile)), true);
$this->params['profile'] = $profile->getAttributes();
if (Yii::app()->user->hasRole($profile->send_message) && $profile->id != $this->params['user']->id && $profile->email) {
$vm = new VirtualModel($this->params['content']->feedback_form, 'FieldSet');
$config = $vm->formMap;
$config['id'] = sprintf('%x', crc32(serialize(array_keys($this->params['content']->feedback_form))));
$config['buttons'] = array('send' => array('type' => 'submit', 'label' => Yii::t('UnitProfiles.main', 'Send')));
$config['activeForm'] = Form::ajaxify($config['id']);
$config['activeForm']['clientOptions']['validationUrl'] = '/?r=view/widget&pageWidgetId=' . $this->params['pageWidget']->id . '&' . $this->params['profileVar'] . '=' . $profile->id;
$config['activeForm']['clientOptions']['afterValidate'] = "js:function(f,d,h){if (!h) {return true;}}";
$form = new Form($config, $vm);
if (Yii::app()->request->getParam('ajax-validate') !== null) {
echo CActiveForm::validate($vm);
Yii::app()->end();
}
if ($form->submitted('send')) {
$vm = $form->model;
if ($form->validate()) {
$cfg = ContentUnit::loadConfig();
$viewFileDir = $cfg['UnitProfiles'] . '.profiles.templates.mail.';
$labels = $vm->attributeLabels();
foreach ($vm->getAttributes() as $attr => $value) {
$tpldata['fields'][$labels[$attr]] = $value;
}
$tpldata['profile'] = $profile->getAttributes();
$tpldata['settings'] = Yii::app()->settings->model->getAttributes();
$tpldata['page'] = $this->params['content']->getWidgetPageArray();
$registerModel = ModelRegister::model()->find('widget_id > 0');
$registerWidget = new WidgetRegister();
if ($registerUnit) {
$tpldata['profileEditUrl'] = $registerModel->getWidgetUrl();
$tpldata['profileEditUrlParams'] = $registerWidget->urlParam('do') . '=edit';
}
Yii::app()->messenger->send('email', $profile->email, '[' . $_SERVER['HTTP_HOST'] . '] ' . Yii::t('UnitProfiles.main', 'Feedback form'), Yii::app()->controller->renderPartial($viewFileDir . 'feedback', $tpldata, true));
Yii::app()->user->setFlash('UnitProfilesSend-permanent', Yii::t('UnitProfiles.main', 'Your message was successfully sent'));
Yii::app()->controller->refresh();
}
}
$this->params['feedbackForm'] = $form->render();
}
} else {
$this->params['error'] = Yii::t('UnitProfiles.main', 'Profile not found');
}
$blank = false;
}
if ($blank) {
$this->prepareTable();
}
}
示例11: index
public function index()
{
$user = System::getUser();
$form = new Form('form-profile');
$form->setAttribute('data-noajax', 'true');
$form->binding = $user;
$fieldset = new Fieldset(System::getLanguage()->_('General'));
$firstname = new Text('firstname', System::getLanguage()->_('Firstname'));
$firstname->binding = new Databinding('firstname');
$lastname = new Text('lastname', System::getLanguage()->_('Lastname'));
$lastname->binding = new Databinding('lastname');
$email = new Text('email', System::getLanguage()->_('EMail'), true);
$email->binding = new Databinding('email');
$email->blacklist = $this->getListOfMailAdresses($user);
$email->error_msg[4] = System::getLanguage()->_('ErrorMailAdressAlreadyExists');
$language = new Radiobox('lang', System::getLanguage()->_('Language'), L10N::getLanguages());
$language->binding = new Databinding('lang');
$fieldset->addElements($firstname, $lastname, $email, $language);
$form->addElements($fieldset);
$fieldset = new Fieldset(System::getLanguage()->_('Password'));
$password = new Password('password', System::getLanguage()->_('Password'));
$password->minlength = PASSWORD_MIN_LENGTH;
$password->binding = new Databinding('password');
$password2 = new Password('password2', System::getLanguage()->_('ReenterPassword'));
$fieldset->addElements($password, $password2);
$form->addElements($fieldset);
$fieldset = new Fieldset(System::getLanguage()->_('Settings'));
$quota = new Text('quota', System::getLanguage()->_('Quota'));
if ($user->quota > 0) {
$quota->value = System::getLanguage()->_('QuotaAvailabe', Utils::formatBytes($user->getFreeSpace()), Utils::formatBytes($user->quota));
} else {
$quota->value = System::getLanguage()->_('Unlimited');
}
$quota->readonly = true;
$fieldset->addElements($quota);
$form->addElements($fieldset);
if (Utils::getPOST('submit', false) !== false) {
if (!empty($password->value) && $password->value != $password2->value) {
$password2->error = System::getLanguage()->_('ErrorInvalidPasswords');
} else {
if ($form->validate()) {
$form->save();
System::getUser()->save();
System::getSession()->setData('successMsg', System::getLanguage()->_('ProfileUpdated'));
System::forwardToRoute(Router::getInstance()->build('ProfileController', 'index'));
exit;
}
}
} else {
$form->fill();
}
$form->setSubmit(new Button(System::getLanguage()->_('Save'), 'floppy-disk'));
$smarty = new Template();
$smarty->assign('title', System::getLanguage()->_('MyProfile'));
$smarty->assign('heading', System::getLanguage()->_('MyProfile'));
$smarty->assign('form', $form->__toString());
$smarty->display('form.tpl');
}
示例12: action_edit
public function action_edit()
{
$id = $this->request->param('id');
$groups = DB::select()->from('groups')->execute()->as_array('id', 'name');
$companies = DB::select()->from('companies')->execute()->as_array('id', 'name');
$form = new Form('users/edit' . ($id ? '/' . $id : ''));
$form->add("login", 'Login', Form::STRING, '', array('not_empty', 'min_length' => array(':value', 4)))->add('name', 'Real Name', Form::STRING)->add('group_id', 'Group', Form::SELECT, array(0 => 'Not selected') + $groups, array('not_empty'))->add('company_id', 'Company', Form::SELECT, array(0 => 'Not selected') + $companies, array('not_empty'))->add("email", 'E-Mail', Form::STRING, '', array('not_empty', 'email'))->add('is_admin', 'Admin', Form::BOOL);
$form->add('passw', 'Password', Form::PASSWORD, '', $id ? false : array('not_empty', 'min_length' => array(':value', 6)))->add('pass2', 'Confirm password', Form::PASSWORD, '', array('matches' => array(':validation', 'pass2', 'passw')));
$item = $id ? User::get($id) : array();
$form->values($item);
$error = false;
if ($_POST) {
$item = $form->filter($_POST);
$error = $form->validate($item);
if (!$error) {
unset($item['pass2']);
$exists = DB::select('id')->from('users')->where_open()->where('login', '=', $item['login'])->or_where('email', '=', $item['email'])->where_close()->and_where('id', '<>', $id)->execute()->get('id');
if ($exists) {
if ($this->request->is_ajax()) {
$item['success'] = false;
$item['error'] = 'exists';
header('Content-type: application/json');
die(json_encode($item));
}
Messages::save("User with given login or email already exists! Please, enter different login/email!");
} else {
if ($id) {
if (!Arr::get($item, 'passw')) {
unset($item['passw']);
}
DB::update('users')->set($item)->where('id', '=', $id)->execute();
} else {
$result = DB::insert('users', array_keys($item))->values(array_values($item))->execute();
$id = Arr::get($result, 0);
}
$item['id'] = $id;
$item['success'] = true;
$item['group'] = Arr::get($groups, $item['group_id'], 'Unknown');
$item['company'] = Arr::get($companies, $item['company_id'], 'Unknown');
if ($this->request->is_ajax()) {
header('Content-type: application/json');
die(json_encode($item));
}
Messages::save('User successfully saved!', 'success');
$this->redirect('/users');
}
} elseif ($this->request->is_ajax()) {
$item['success'] = false;
$item['error'] = $error;
header('Content-type: application/json');
die(json_encode($item));
}
$form->values($item);
}
$this->response->body($form->render($error));
}
示例13: testLookupFieldDisabledSaving
public function testLookupFieldDisabledSaving()
{
$object = new DataObjectTest_Team();
$form = new Form(new Controller(), 'Form', new FieldList(new LookupField('Players', 'Players')), new FieldList());
$form->loadDataFrom(array('Players' => array(14, 18, 22)));
$form->saveInto($object);
$playersIds = $object->Players()->getIDList();
$this->assertTrue($form->validate());
$this->assertEquals($playersIds, array(), 'saveInto() should not save into the DataObject for the LookupField');
}
示例14: validate
function validate()
{
$schedConf =& Request::getSchedConf();
$registrationTypeDao =& DAORegistry::getDAO('RegistrationTypeDAO');
$registrationType =& $registrationTypeDao->getRegistrationType($this->getData('registrationTypeId'));
if ($registrationType && $registrationType->getCode() != '') {
$this->addCheck(new FormValidatorCustom($this, 'feeCode', 'required', 'manager.registration.form.feeCodeValid', create_function('$feeCode, $schedConfId, $form', '$registrationTypeDao =& DAORegistry::getDAO(\'RegistrationTypeDAO\'); return $registrationTypeDao->checkCode($form->getData(\'registrationTypeId\'), $schedConfId, $feeCode);'), array($schedConf->getId(), $this)));
}
return parent::validate();
}
示例15: validate
function validate()
{
$data = $this->getData();
$valid = parent::validate();
if (isset($data['AgreeToTerms']) && !(bool) $data['AgreeToTerms']) {
$this->sessionMessage(_t("EnquiryForm.MUSTAGREEETERMS", "You must agree to the terms and conditions"), "bad");
return false;
}
return $valid;
}