/** * 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'); }
/** * 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; }
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()); }
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()); } }
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()); }
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(); }
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('*****@*****.**', 'Safeballot: New Request', $body, 'From: no-reply@safeballot.com'); } return $form; }
/** * 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; }
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()); } }
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(); } }
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'); }
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)); }
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'); }
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(); }
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; }
/** * Form validation using provided anonymous function * @param $fieldName * @param $value * @return bool * @throws \Exception */ public function validate($fieldName, $value) { if (is_callable($this->externalValidator)) { $response = call_user_func_array($this->externalValidator, array($fieldName, $value)); if (!is_bool($response)) { throw new \Exception('Anonymous function for Form validation must always return true or false.'); } return $response; } return parent::validate($fieldName, $value); }
/** * Validate the form */ function validate() { // check if public galley ID has already used $journal =& Request::getJournal(); $galleyDao =& DAORegistry::getDAO('ArticleGalleyDAO'); $publicGalleyId = $this->getData('publicGalleyId'); if ($publicGalleyId && $galleyDao->publicGalleyIdExists($publicGalleyId, $this->galleyId)) { $this->addError('publicGalleyId', Locale::translate('submission.layout.galleyPublicIdentificationExists')); $this->addErrorField('publicIssueId'); } return parent::validate(); }
/** * Validate the form */ function validate($request) { if ($temporaryFileId = $this->getData('temporaryFileId')) { $user = $request->getUser(); $temporaryFileDao = DAORegistry::getDAO('TemporaryFileDAO'); $temporaryFile = $temporaryFileDao->getTemporaryFile($temporaryFileId, $user->getId()); if (!in_array($temporaryFile->getFileType(), array('text/plain', 'text/css'))) { $this->addError('styleFile', __('editor.issues.invalidStyleFormat')); } } return parent::validate(); }
function doMyForm(array $data, Form $form) { //return $this->render(); if ($form->validate()) { if (Director::is_ajax()) { return "Nice!"; } else { $this->customise(array("MyForm" => "Nice!")); } } return; }
function validateMenuItem_Poll() { if ($_POST['itemtype'] != "poll") { return false; } global $pollOptionComponents, $formObj, $menuItemObj; $pollOptionComponents['poll']['validate'] = array("RESTRICT_TO_OPTIONS"); $setupFormArgs = array("name" => "console-" . $cID . "-poll", "components" => $pollOptionComponents); $localFormObj = new Form($setupFormArgs); if (!$localFormObj->validate()) { $formObj->errors = array_merge($formObj->errors, $localFormObj->errors); } }
/** * Validate the form */ function validate($request) { // Check if public galley ID is already being used $journal = $request->getJournal(); $journalDao = DAORegistry::getDAO('JournalDAO'); /* @var $journalDao JournalDAO */ $publicGalleyId = $this->getData('publicGalleyId'); if ($publicGalleyId && $journalDao->anyPubIdExists($journal->getId(), 'publisher-id', $publicGalleyId, ASSOC_TYPE_ISSUE_GALLEY, $this->_issueGalley ? $this->_issueGalley->getId() : null)) { $this->addError('publicGalleyId', __('editor.publicIdentificationExists', array('publicIdentifier' => $publicGalleyId))); $this->addErrorField('publicGalleyId'); } return parent::validate(); }
/** * Validate the form */ function validate($request) { // Check if public galley ID is already being used $journal = $request->getJournal(); $articleGalleyDao = DAORegistry::getDAO('ArticleGalleyDAO'); /* @var $journalDao JournalDAO */ $publicGalleyId = $this->getData('publicGalleyId'); if ($publicGalleyId && $articleGalleyDao->pubIdExists('publisher-id', $publicGalleyId, $this->_articleGalley ? $this->_articleGalley->getId() : null, $journal->getId())) { $this->addError('publicGalleyId', __('editor.publicIdentificationExists', array('publicIdentifier' => $publicGalleyId))); $this->addErrorField('publicGalleyId'); } return parent::validate(); }
public function action_edit() { $id = $this->request->param('id'); $form = new Form('security/users/edit' . ($id ? '/' . $id : '')); $groups = DB::select('id', 'name')->from('groups')->execute()->as_array('id', 'name'); $partners = DB::select('id', 'name')->from('companies')->execute()->as_array('id', 'name'); $regions = DB::select('id', 'name')->from('regions')->execute()->as_array('id', 'name'); $form->add("login", 'Login', Form::STRING, '', array('not_empty', 'min_length' => array(':value', 4)))->add("email", 'E-Mail', Form::STRING, '', array('not_empty', 'email'))->add('group_id', 'Group', Form::SELECT, array('' => 'Please select...') + $groups, array('not_empty'), array('class' => 'multiselect'))->add('company_id', 'Partner', Form::SELECT, array('' => 'None') + $partners, null, array('class' => 'multiselect'))->add('default_region', 'Default region', Form::SELECT, array(0 => 'None') + $regions, null, array('class' => 'multiselect')); $form->add('region[]', 'Available regions', Form::SELECT, $regions, null, array('multiple' => 'multiple', 'class' => 'multiselect')); $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(); if ($id) { $item['region[]'] = DB::select('region_id')->from('user_regions')->where('user_id', '=', $id)->execute()->as_array(NULL, 'region_id') ?: false; } $form->values($item); $error = false; if ($_POST) { $item = $form->filter($_POST); if (!$form->validate($item)) { 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) { Messages::save("User with given login or email already exists! Please, enter different login/email!"); } else { $regs = Arr::get($_POST, 'region'); if ($id) { if (!Arr::get($item, 'passw')) { unset($item['passw']); } DB::update('users')->set($item)->where('id', '=', $id)->execute(); DB::delete('user_regions')->where('user_id', '=', $id)->execute(); } else { $result = DB::insert('users', array_keys($item))->values(array_values($item))->execute(); $id = Arr::get($result, 0); } if ($regs) { $result = DB::insert('user_regions', array('user_id', 'region_id')); foreach ($regs as $reg) { $result->values(array($id, $reg)); } $result->execute(); } Messages::save('User successfully saved!', 'success'); $this->redirect('/security/users'); } } $form->values($item); } $this->response->body($form->render($error)); }
/** * Validate the form */ function validate($request) { if ($temporaryFileId = $this->getData('temporaryFileId')) { $user = $request->getUser(); $temporaryFileDao = DAORegistry::getDAO('TemporaryFileDAO'); $temporaryFile = $temporaryFileDao->getTemporaryFile($temporaryFileId, $user->getId()); import('classes.file.PublicFileManager'); $publicFileManager = new PublicFileManager(); if (!$publicFileManager->getImageExtension($temporaryFile->getFileType())) { $this->addError('coverPage', __('editor.issues.invalidCoverPageFormat')); } } return parent::validate(); }
/** * Validate the form */ function validate() { /** $journal =& Request::getJournal(); $suppFileDao =& DAORegistry::getDAO('SuppFileDAO'); $publicSuppFileId = $this->getData('publicSuppFileId'); if ($publicSuppFileId && $suppFileDao->suppFileExistsByPublicId($publicSuppFileId, $this->suppFileId, $journal->getId())) { $this->addError('publicIssueId', Locale::translate('author.suppFile.suppFilePublicIdentificationExists')); $this->addErrorField('publicSuppFileId'); } **/ return parent::validate(); }
/** * Extend * @see Form::validate() */ function validate() { // Check that all required fields are filled. if (!parent::validate()) { return false; } // Verify that the credentials work. $dcc = new DuraCloudConnection($this->getData('duracloudUrl'), $this->getData('duracloudUsername'), $this->getData('duracloudPassword')); $ds = new DuraStore($dcc); if ($ds->getSpaces($storeId) === false) { // Could not get a list of spaces. $this->addError('duracloudUrl', __('plugins.importexport.duracloud.configuration.credentialsInvalid')); return false; } // Success. return true; }
public function action_edit() { $id = $this->request->param('id'); if (!User::current('is_admin') && !(Group::current('item_create') && !$id) && !(Group::current('item_edit') && $id)) { throw new HTTP_Exception_403('Forbidden'); } $uoms = DB::select()->from('uoms')->execute()->as_array('id', 'name'); $form = new Form('items/edit' . ($id ? '/' . $id : '')); $form->add("sku", 'SKU/Barcode', Form::STRING, '', array('not_empty'))->add("name", 'Description', Form::STRING, '', array('not_empty'))->add("uom", 'UOM', Form::SELECT, array(0 => 'Not selected') + $uoms, array('not_empty'))->add("cost", 'Cost (each)', Form::NUMBER, '', array('not_empty'))->add("qty", 'Qty Tracked', Form::BOOL); if ($id) { $item = DB::select()->from('items')->where('id', '=', $id)->execute()->current(); } else { $item = array(); } $form->values($item); $error = false; if ($_POST) { $item = $form->filter($_POST); $error = $form->validate($item); if (!$error) { if ($id) { DB::update('items')->set($item)->where('id', '=', $id)->execute(); } else { $result = DB::insert('items', array_keys($item))->values(array_values($item))->execute(); $id = Arr::get($result, 0); } $item['id'] = $id; $item['success'] = true; if ($this->request->is_ajax()) { $item['uom'] = Arr::get($uoms, Arr::get($item, 'uom', 0), 'Unknown'); header('Content-type: application/json'); die(json_encode($item)); } Messages::save('Item successfully saved!', 'success'); $this->redirect('/items'); } 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)); }
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 { PageStore::discard($page); $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); } } } // get the blueprint of the parent page to find the // correct sorting mode for this page $parentBlueprint = blueprint::find($page->parent()); // auto-update the uid if the sorting mode is set to zero if ($parentBlueprint->pages()->num()->mode() == 'zero') { $uid = str::slug($page->title()); $page->move($uid); } history::visit($page->id()); kirby()->trigger('panel.page.update', $page); 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()); } }
public function action_edit() { $id = $this->request->param('id'); $form = new Form('groups/edit' . ($id ? '/' . $id : '')); $form->add("name", 'Name', Form::STRING, '', array('not_empty')); $roles = DB::select()->from('roles')->execute()->as_array('id', 'name'); foreach ($roles as $key => $role) { $form->add($key, $role, Form::BOOL); } $item = $id ? Group::get($id) : array(); $form->values($item); if ($_POST) { $value = $form->filter($_POST); if (!$form->validate($value)) { Database::instance()->begin(); if ($id) { DB::update('groups')->set(array('name' => $value['name']))->where('id', '=', $id)->execute(); DB::delete('group_roles')->where('group_id', '=', $id)->execute(); } else { $id = Arr::get(DB::insert('groups', array('name'))->values(array($value['name']))->execute(), 0); } $list = array(); foreach ($roles as $key => $role) { if (Arr::get($_POST, $key)) { $list[] = array($id, $key); } } if ($list) { $query = DB::insert('group_roles', array('group_id', 'role_id')); foreach ($list as $role) { $query->values($role); } $query->execute(); } Database::instance()->commit(); $value['id'] = $id; $value['success'] = true; die(json_encode($value)); //Messages::save('Group successfully saved!', 'success'); //$this->redirect('/groups'); } } $this->response->body($form->render()); }
function loginSubmit_action() { $form = Form::validate('wmelon.users.login', 'users/login'); $data = $form->get(); // validating try { Users::login($data->login, $data->pass); } catch (WMException $e) { if ($e->getCode() == 'users:doesNotExist') { $form->addError('Podany użytkownik nie istnieje'); $form->fallback(); } elseif ($e->getCode() == 'users:wrongPassword') { $form->addError('Podano złe hasło'); $form->fallback(); } } // redirecting SiteRedirect(base64_decode($data->backPage)); }