/** * editformAction * @author Thomas Schedler <*****@*****.**> * @version 1.0 */ public function editformAction() { $this->core->logger->debug('users->controllers->ResourceController->editformAction()'); try { $arrGroups = $this->getModelUsers()->getResourceGroups($this->getRequest()->getParam('id')); if (count($arrGroups) > 0) { $this->arrGroups = array(); foreach ($arrGroups as $objGroup) { $this->arrGroups[] = $objGroup->idGroups; } } $this->initForm(); $this->objForm->setAction('/zoolu/users/resource/edit'); $this->objResource = $this->getModelUsers()->getResourceTable()->find($this->getRequest()->getParam('id'))->current(); foreach ($this->objForm->getElements() as $objElement) { $name = $objElement->getName(); if (isset($this->objResource->{$name})) { $objElement->setValue($this->objResource->{$name}); } } $this->view->form = $this->objForm; $this->view->formTitle = $this->core->translate->_('Edit_Resource'); $this->renderScript('form.phtml'); } catch (Exception $exc) { $this->core->logger->err($exc); } }
public function saveFormData(Zend_Form $form) { $item = $this->_model; $item->setOptions($form->getValues()); if ($this->_request->getParam('contentMarkdown')) { $context_html = Michelf\MarkdownExtra::defaultTransform($this->_request->getParam('contentMarkdown')); $item->setContentHtml($context_html); } $fullPath = $this->_request->getParam('path'); if ($this->_request->getParam('parentId') != 0) { $parentCategory = $this->_modelMapper->find($this->_request->getParam('parentId'), new Pipeline_Model_PipelineCategories()); if ($parentCategory) { $fullPath = $parentCategory->getFullPath(); } } $item->setFullPath($fullPath); $this->setMetaData($item); $this->getModelMapper()->save($item); if ($item->getId() && $item->getId() != '') { $id = $item->getId(); } else { $id = $this->getModelMapper()->getDbTable()->getAdapter()->lastInsertId(); } $item = $this->getModelMapper()->find($id, $this->getModel()); foreach ($form->getElements() as $key => $element) { if ($element instanceof Zend_Form_Element_File && $element->isUploaded()) { $item = $this->saveUploadFile($element, $item); } } return $item; }
/** * Sets each element with a class based on its type * * @param Zend_Form $form */ public static function setFormElementTypeClasses(Zend_Form $form) { foreach ($form->getElements() as $element) { $type = strtolower(array_pop(explode('_', $element->getType()))); $class = isset($element->class) ? $element->class . ' ' : ''; $class .= 'element-type-' . $type; $element->class = $class; } }
/** * Adds unique IDs to all elements in the given form. * * @param Zend_Form $form */ public function enhance(Zend_Form $form) { foreach ($form->getSubForms() as $subForm) { /* @var $subForm Zend_Form */ $this->enhance($subForm); } foreach ($form->getElements() as $element) { /* @var $element Zend_Form_Element */ $this->updateId($element); } }
/** * @group ZF-3217 */ public function testFormShouldOverloadToRenderDecorators() { $this->setupElements(); $this->form->setView($this->getView()); $html = $this->form->renderFormElements(); foreach ($this->form->getElements() as $element) { $this->assertContains('id="' . $element->getFullyQualifiedName() . '"', $html, 'Received: ' . $html); } $this->assertNotContains('<dl', $html); $this->assertNotContains('<form', $html); $html = $this->form->renderForm('this is the content'); $this->assertContains('<form', $html); $this->assertContains('</form>', $html); $this->assertContains('this is the content', $html); }
/** * Serialize form elements * @param Zend_Form $form Zend form, which value to serialize * @param DOMElement $domElement parent element where to create the "values" element */ private function serializeValues($form, DOMElement $domElement) { $values = $domElement->ownerDocument->createElement("values"); $domElement->appendChild($values); foreach ($form->getElements() as $name => $element) { $node = $domElement->ownerDocument->createElement("element"); $node->setAttribute("name", $element->getFullyQualifiedName()); if ($element->getAttrib("disabled")) { $node->setAttribute("disabled", "disabled"); } $node->appendChild($domElement->ownerDocument->createElement('value', htmlspecialchars($element->getValue(), ENT_NOQUOTES))); $this->serializeErrors($element->getErrors(), $node); $values->appendChild($node); } }
/** * editformAction * @author Thomas Schedler <*****@*****.**> * @version 1.0 */ public function editformAction() { $this->core->logger->debug('users->controllers->GroupController->editformAction()'); try { /** * get permissions */ $arrPermissions = $this->getModelUsers()->getGroupPermissions($this->getRequest()->getParam('id')); if (count($arrPermissions) > 0) { $this->arrPermissions = array(); foreach ($arrPermissions as $objPermission) { if (!array_key_exists('lang_' . $objPermission->idLanguages, $this->arrPermissions)) { $this->arrPermissions['lang_' . $objPermission->idLanguages] = array('language' => $objPermission->idLanguages, 'permissions' => array($objPermission->idPermissions)); } else { $this->arrPermissions['lang_' . $objPermission->idLanguages]['permissions'][] = $objPermission->idPermissions; } } } else { $this->arrPermissions = array(array('language' => '', 'permissions' => '')); } /** * get groupType */ $arrGroupTypes = $this->getModelUsers()->getGroupGroupTypes($this->getRequest()->getParam('id')); if (count($arrGroupTypes) > 0) { $this->arrGroupTypes = array(); foreach ($arrGroupTypes as $objGroupType) { $this->arrGroupTypes[] = $objGroupType->idGroupTypes; } } else { $this->arrGroupTypes = array(); } $this->initForm(); $this->objForm->setAction('/zoolu/users/group/edit'); $this->objGroup = $this->getModelUsers()->getGroupTable()->find($this->getRequest()->getParam('id'))->current(); foreach ($this->objForm->getElements() as $objElement) { $name = $objElement->getName(); if (isset($this->objGroup->{$name})) { $objElement->setValue($this->objGroup->{$name}); } } $this->view->form = $this->objForm; $this->view->formTitle = $this->core->translate->_('Edit_Group'); $this->renderScript('form.phtml'); } catch (Exception $exc) { $this->core->logger->err($exc); } }
public function formBootstrap(Zend_Form $form, $submitLabel = 'Valider') { $html = $form->renderForm(false); foreach ($form->getElements() as $element) { $element->getDecorator('label')->setOption('tag', null); // TODO retirer la class error du ul $html .= $element->getMessages() ? '<div class="form-group has-error">' : '<div class="form-group">'; $html .= $element->renderLabel(); $html .= $element->setAttrib('class', 'form-control')->renderViewHelper(); if ($element->getMessages()) { $html .= '<div class="help-block">'; $html .= $element->renderErrors(); $html .= '</div>'; } $html .= '</div>'; } $html .= '<button type="submit" class="btn btn-primary">' . $submitLabel . '</button>'; $html .= '</form>'; return $html; }
public static function build($formConfig) { $decorators = array(); if ($formConfig->useInternalError) { $decorators[] = new Saf_Form_Zend_Helper_Error(array('class' => 'formErrors', 'id' => $newFormId . 'Errors', 'placement' => 'append', 'escape' => false)); } $newForm = new Zend_Form(); $newForm->setConfig($formConfig); $newForm->removeDecorator('HtmlTag'); $newFormId = $newForm->getId(); $formDecorator = $newForm->getDecorator('Form'); $elementDecorator = $newForm->getDecorator('FormElements'); $decorators[] = $elementDecorator; $decorators[] = $formDecorator; $newForm->setDecorators($decorators); foreach ($newForm->getElements() as $element) { self::fixElement($element); } return $newForm; }
protected function _buildTable(Zend_Form $form) { # generate table header if ($this->_tableHeadersBuilt !== true) { if ($form instanceof Zend_Form_SubForm) { foreach ($form->getElements() as $eName => $e) { if (isset($this->_tableHeaders[$eName])) { throw new Exception(sprintf('Invalid sub-form (table row configuration) "%s" for table layout - table header already set for this column "%s"', $form->getName(), $eName)); } $this->_tableHeaders[$eName] = $e->getLabel(); } foreach ($form->getSubForms() as $formName => $subForm) { $this->_buildTable($subForm); } return false; } # get headers from first sub-form $subform = $form->getSubForms(); $subform = current($subform); $this->_buildTable($subform); $this->_tableHeadersBuilt = true; } if ($form instanceof Zend_Form_SubForm) { foreach ($form->getElements() as $eName => $e) { if ($this->getOption('doNotSetDecorators') !== true) { $e->setDecorators(array('ViewHelper')); } if (isset($this->_tableCell[$eName])) { throw new Exception(sprintf('Invalid sub-form (table row configuration) "%s" for table layout - table cell "%s" already set for row %d', $form->getName(), $eName, $this->_rowIndex)); } $this->_tableCell[$eName] = $e; } foreach ($form->getSubForms() as $formName => $subForm) { $this->_buildTable($subForm); } return; } # $form is not instance of Zend_Form_SubForm $result = array(); foreach ($form->getSubForms() as $formName => $subForm) { $this->_tableCell = array(); $this->_rowIndex++; $this->_buildTable($subForm); if (empty($this->_tableCell)) { # no data generated from current subform continue; } $result[$this->_rowIndex] = $this->_tableCell; } if (empty($result)) { return ''; } $tableRows = array(); foreach ($result as $rowIndex => $row) { $elements = array(); foreach ($this->_tableHeaders as $eName => $label) { if (!isset($row[$eName])) { throw new Exception(sprintf('Invalid form "%s" for table layout - missing table cell "%s" for row %d', $form->getName(), $eName, $rowIndex)); } # display messages in the same table cell as the input field $elements[] = implode('<br />', array_merge($row[$eName]->getMessages(), array($row[$eName]->render()))); } $tableRows[] = '<tr><td>' . implode('</td><td>', $elements) . '</td></tr>' . "\n"; } return '<table><tr><th>' . implode('</th><th>', $this->_tableHeaders) . '</th></tr>' . "\n" . implode('', $tableRows) . '</table>'; }
/** * Get action form * * @return Zend_Form */ private function getActionForm() { $translator = \Zend_Registry::get('container')->getService('translator'); $form = new Zend_Form(); $form->addElements(array(new Zend_Form_Element_Hash('csrf', array('decorators' => array('ViewHelper'))), new Zend_Form_Element_Hidden('name', array('decorators' => array('ViewHelper'))), new Zend_Form_Element_Select('multiaction', array('multioptions' => array('' => $translator->trans('Actions'), 'move' => $translator->trans('Move'), 'delete' => $translator->trans('Delete')), 'decorators' => array('ViewHelper'))), new Zend_Form_Element_Hidden('action', array('required' => true, 'validators' => array(array('inArray', true, array(array('copy', 'move', 'rename', 'delete', 'create-file', 'create-folder')))), 'decorators' => array('ViewHelper'))), new Zend_Form_Element_MultiCheckbox('file'))); foreach ($form->getElements() as $elem) { $elem->removeDecorator('DtDdWrapper')->removeDecorator('Label'); } return $form; }
/** * @param unknown_type $formName * @param unknown_type $options * @throws Exception * @return Zend_Form */ public function getForm($formName, $options = null, $useTemplate = false) { if (is_null(self::$_forms)) { if (is_file(APPLICATION_PATH . '/configs/forms.ini')) { $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/forms.ini'); } else { $config = new Zend_Config(include_once APPLICATION_PATH . '/configs/forms.php'); } $config = $config->toArray(); self::$_forms = $config; } if (!array_key_exists($formName, $config)) { throw new Exception("Form not exist"); } if ($useTemplate) { //$form = new Zend_Form_Template($config[$formName]); //$form->setTemplate($formName, $options); $form = new Zend_Form($config[$formName]); $elements = $form->getElements(); foreach ($elements as &$element) { $element->removeDecorator('Label'); $element->removeDecorator('HtmlTag'); $element->removeDecorator('DtDdWrapper'); $element->removeDecorator('Description'); $element->removeDecorator('Errors'); $element->addDecorator(array('data' => 'Errors'), array('tag' => 'p', 'class' => 'description')); } $filter = new Zend_Filter_Word_CamelCaseToDash(); $formName = $filter->filter($formName); $options['viewScript'] = 'forms/' . $formName . '.phtml'; $form->setDecorators(array(array('viewScript', $options))); } else { $form = new Zend_Form($config[$formName]); /* $form->addElementPrefixPath('Zend_Decorator', 'Zend/Decorator/', 'decorator'); $form->setDecorators(array('Default'));*/ //Zend_Debug::dump($form->getDecorator('Errors')); /*$elements = $form->getElements(); foreach ($elements as &$element) { $element->setDecorators( array( 'ViewHelper', 'Errors', array(array('data' => 'HtmlTag'), array('tag' => 'div', 'class' => 'element')), 'Label', array(array('row' => 'HtmlTag'), array('tag' => 'li')) ) ); //Zend_Debug::dump($element->getDecorator('Errors')); };*/ /* $form->setElementDecorators(array( 'ViewHelper', array('Errors', array('class' => 'help-inline control-error')), array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'controls')), array(array('label' => 'Label'), array('class' => 'control-label')), array(array('data' => 'HtmlTag'), array('tag' => 'div', 'class' => 'control-group')), )); */ // $form->addElement("text", "naem", $opt); /* $form->setDecorators(array( 'FormElements', array('Form', array('class' => 'form-horizontal')) ));*/ //Zend_Debug::dump($form); // вынести декораторы } $formAction = $form->getAction(); $routes = $this->getRouterNames(); $actionParams = array(); if (is_array($options) && array_key_exists('actionParams', $options)) { $actionParams = $options['actionParams']; } if (in_array($formAction, $routes)) { if (array_key_exists("actionParams", $config[$formName]) && is_array($config[$formName]['actionParams'])) { $actionParams = $config[$formName]['actionParams']; } $form->setAction($this->_url($actionParams, $formAction)); } //Zend_Debug::dump($form); return $form; }
/** * Return an array of form elements. * * @param Zend_Form $form * @return array */ public function getFormAsArray(Zend_Form $form) { $array = array(); $array['action'] = $form->getAction(); $array['method'] = $form->getMethod(); foreach ($form->getElements() as $element) { $element->removeDecorator('HtmlTag'); $element->removeDecorator('Label'); $element->removeDecorator('DtDdWrapper'); $array[$element->getName()] = $element; } return $array; }
/** * Set a form populated with elements for filtering and validation of * the input elements * * @param \Zend_Form $form * @return \MUtil_Model_ModelTranslatorAbstract (continuation pattern) */ public function setTargetForm(\Zend_Form $form) { $this->targetForm = $form; $this->_dateElementNames = array(); $this->_checkForm($form->getElements()); return $this; }
/** * Checks if the provided form already contains a CSRF element. * * @param Zend_Form $form * @return boolean */ protected function hasCsrf(Zend_Form $form) { foreach ($form->getElements() as $element) { /* @var $element Zend_Form_Element */ if ($element instanceof Zend_Form_Element_Hash) { // Form already contains a CSRF token. return true; } } return false; }
/** * Iterate over elements and hand over to */ protected function setupElementsUnique() { foreach ($this->form->getElements() as $elmKey => $elm) { $this->setupSingleElement($elm); } }
/** * Receive an error message in the form of an array * * ex. array( * Error form! Invalid data in the form introduced. * Email : '111' Invalid e-mail address. Enter it in the format 'name@domain' * Protection from spam : Introduced invalid characters * ) * @param Zend_Form $form * * @return array */ public function getFormMessages(Zend_Form $form) { $errorMessages = array(); //--------------------------- $elements = $form->getElements(); foreach ($elements as $element) { $label = $element->getLabel(); //getLabel(); $label = trim($label); $label = trim($label, ':'); $name = $element->getName(); if ($name == 'captcha') { $label = 'Сaptcha - защита от спама '; } if ($element->getErrors()) { //Добавим первую строку предупреждения if (count($errorMessages) == 0) { $errorMessages[] = '<em>' . Zend_Registry::get('Zend_Translate')->_('Ошибка формы! Неверно введены данные в форму.') . '</em>'; } //Добавим сообщения об ошибках $errors = $element->getErrors(); foreach ($errors as $error) { $messages = $element->getMessages(); $errorMessages[] = '<em>' . $label . ': ' . '</em>' . $messages[$error] . ';'; } } } if (count($errorMessages) == 0) { $errorMessages = NULL; } return $errorMessages; }
/** * Set the form decorators by the given string format or by the default div style * * @param object $objForm Zend_Form pointer-reference * @param string $constFormat Project_Plugin_FormDecoratorDefinition constants * @return NULL */ public static function setFormDecorator(Zend_Form $form, $format = self::BOOTSTRAP, $submit_str = 'submit', $cancel_str = 'cancel') { /** * - disable default decorators * - set form & displaygroup decorators */ $form->setDisableLoadDefaultDecorators(true); $form->setDisplayGroupDecorators(self::$_DisplayGroupDecorator[$format]); $form->setDecorators(self::$_FormDecorator[$format]); // set needed prefix path for bootstrap decorators if ($format == self::BOOTSTRAP) { $form->addElementPrefixPath('EasyBib_Form_Decorator', 'EasyBib/Form/Decorator', Zend_Form::DECORATOR); } // set form element decorators $form->setElementDecorators(self::$_ElementDecorator[$format]); // set submit button decorators if ($form->getElement($submit_str)) { $form->getElement($submit_str)->setDecorators(self::$_SubmitDecorator[$format]); if ($format == self::BOOTSTRAP) { $attribs = $form->getElement($submit_str)->getAttrib('class'); if (empty($attribs)) { $attribs = array('btn', 'primary'); } else { if (is_string($attribs)) { $attribs = array($attribs); } $attribs = array_unique(array_merge(array('btn'), $attribs)); } $form->getElement($submit_str)->setAttrib('class', $attribs)->setAttrib('type', 'submit'); if ($form->getElement($cancel_str)) { $form->getElement($submit_str)->getDecorator('HtmlTag')->setOption('openOnly', true); } } } // set cancel button decorators if ($form->getElement($cancel_str)) { $form->getElement($cancel_str)->setDecorators(self::$_ResetDecorator[$format]); if ($format == self::BOOTSTRAP) { $attribs = $form->getElement($cancel_str)->getAttrib('class'); if (empty($attribs)) { $attribs = array('btn'); } else { if (is_string($attribs)) { $attribs = array($attribs); } $attribs = array_unique(array_merge(array('btn'), $attribs)); } $form->getElement($cancel_str)->setAttrib('class', $attribs)->setAttrib('type', 'reset'); if ($form->getElement($submit_str)) { $form->getElement($cancel_str)->getDecorator('HtmlTag')->setOption('closeOnly', true); } } } // set hidden input decorators foreach ($form->getElements() as $e) { if ($e->getType() == 'Zend_Form_Element_Hidden') { $e->setDecorators(self::$_HiddenDecorator[$format]); } } }
/** * Generates the Javascript markup needed for jQuery Validate * using the parameters of the Zend_Form object * @param Zend_Form $form The Zend Form to use * @param array $otherOptions A array with additional options if needed * @return string */ public function formJQueryValidate(Zend_Form $form, array $otherOptions = array()) { $id = $form->getAttrib('id'); if (!$id) { $id = uniqid('zfForm'); } $fields = array(); $messages = array(); foreach ($form->getElements() as $elemName => $element) { $options = array(); $elemMessages = array(); if ($element->getIgnore() == true) { continue; } if ($element->isRequired()) { $options['required'] = true; $elemMessages['required'] = 'Este elemento es necesario'; } $validators = $element->getValidators(); foreach ($validators as $validator) { $validatorMessages = $validator->getMessageTemplates(); switch (true) { case $validator instanceof Zend_Validate_NotEmpty: $options['required'] = true; $elemMessages['required'] = $this->toJQueryValidateFormat($validatorMessages['isEmpty']); break; case $validator instanceof Zend_Validate_EmailAddress: $options['email'] = true; $elemMessages['email'] = $this->toJQueryValidateFormat($validatorMessages['emailAddressInvalidFormat']); break; case $validator instanceof Zend_Validate_StringLength: $min = $validator->getMin(); $max = $validator->getMax(); if ($min) { $options['minlength'] = $min; $elemMessages['minlength'] = $this->toJQueryValidateFormat($validatorMessages['stringLengthTooShort']); } if ($max) { $options['maxlength'] = $max; $elemMessages['maxlength'] = $this->toJQueryValidateFormat($validatorMessages['stringLengthTooLong']); } break; case $validator instanceof Zend_Validate_Identical: $token = $validator->getToken(); if ($token) { $options['equalTo'] = '#' . $token; $elemMessages['equalTo'] = $this->toJQueryValidateFormat($validatorMessages['notSame']); } break; case $validator instanceof Zend_Validate_Date: $options['mxdate'] = true; $elemMessages['equalTo'] = $this->toJQueryValidateFormat($validatorMessages['dateInvalidDate']); break; } } $fields[$elemName] = $options; $messages[$elemName] = $elemMessages; } $validateOptions = json_encode(array_merge($otherOptions, array('rules' => $fields, 'messages' => $messages))); $js = "\$('#{$id}').validate({$validateOptions});"; return $js; }
/** * Organizes the fieds according its position define in the order attribute. * <br /> This is usefull besause of the loop done for the render. * It's not the default Zend_Form mechanism and we have to set this order. * * @param Zend_Form $form The form or subform to render. * * @return array */ private function _reorderElements(Zend_Form $form) { $elementsArray = array(); foreach ($form->getElements() as $key => $element) { $test = $element instanceof Zend_Form_Element_Hidden; if (!$element instanceof Zend_Form_Element_Hidden && !$element instanceof Zend_Form_Element_Button && !$element instanceof Zend_Form_Element_Submit) { $value = $element->getValue(); if (empty($value)) { $value = ' '; } $index = $element->getOrder(); $elementsArray[$index]['label'] = $element->getLabel(); $elementsArray[$index]['value'] = $value; } } ksort($elementsArray); return $elementsArray; }
/** * Helper function for creating automatically calculated widths. * * @staticvar \Zend_Form $last_form Prevent recalculation. This function is called for every label * @staticvar string $last_factor Last result * @param \Zend_Form $form The form to calculate the widest label for * @param float $factor The factor to multiple the number of characters with for to get the number of em's * @return string E.g.: '10em' */ public static function calculateAutoWidthFormLayout(\Zend_Form $form, $factor = 1) { static $last_form; static $last_factor; // No need to repeat the calculations for every element, // which would otherwise happen. if ($form === $last_form) { return $last_factor; } $maxwidth = 0; foreach ($form->getElements() as $element) { if ($decorator = $element->getDecorator('Label')) { $decorator->setElement($element); $len = strlen(strip_tags($decorator->getLabel())); if ($len > $maxwidth) { $maxwidth = $len; } } } $last_form = $form; if ($maxwidth) { $last_factor = intval($factor * $maxwidth) . 'em'; } else { // We need to return some usable value. $last_factor = 'auto'; } return $last_factor; }