/**
  * Main method
  * @param string The form object
  * @param string Name of the element
  * @return string HTML block showing message
  */
 public function showFormElementMessages(Zend_Form $form, $element)
 {
     if ($form->getMessages($element)) {
         echo '<ul class="help-inline alert-error form-error-msg" rel="' . $element . '">';
         foreach ($form->getMessages($element) as $error) {
             echo '<li class="icon-exclamation-sign">' . $error . '</li>';
         }
         echo '</ul>';
     }
 }
Beispiel #2
0
 /**
  * Get Validation Messages
  *
  * @param string $name
  * @param bool   $suppressArrayNotation
  * @return array
  */
 public function getMessages($name = null, $suppressArrayNotation = false)
 {
     $messages = parent::getMessages($name, $suppressArrayNotation);
     if (empty($messages)) {
         $messages = array_merge($messages, $this->getErrorMessages());
     }
     return $messages;
 }
Beispiel #3
0
 public function getActiveTab(\Zend_Form $form)
 {
     $errors = $form->getMessages();
     if (!empty($errors)) {
         return preg_replace("/[^\\w]/", "", array_shift(array_keys($errors)));
     }
     return null;
 }
Beispiel #4
0
 public function testShouldAllowPushingErrorsOntoErrorStackWithErrorMessages()
 {
     $this->assertFalse($this->form->isErrors());
     $this->form->setErrors(array('Error 1', 'Error 2'))->addError('Error 3')->addErrors(array('Error 4', 'Error 5'));
     $this->assertTrue($this->form->isErrors());
     $messages = $this->form->getMessages();
     $this->assertEquals(5, count($messages));
     foreach (range(1, 5) as $id) {
         $message = 'Error ' . $id;
         $this->assertContains($message, $messages);
     }
 }
Beispiel #5
0
 public function getMessages($name = null, $suppressArrayNotation = false)
 {
     $e = parent::getMessages($name, $suppressArrayNotation);
     if ($e) {
         foreach ($e as &$el) {
             if ($el) {
                 foreach ($el as $k => &$el_1) {
                     $el_1 = $this->translateError($k, $el_1);
                 }
             }
         }
     }
     return $e;
 }
Beispiel #6
0
 public static function getAdaptedMessagesArray(Zend_Form $zendFormObj)
 {
     $messagesArray = $zendFormObj->getMessages();
     $adaptedMessagesObj = Model_Library_Messages_Message::createInstance(Model_Library_Messages_States_Error::createInstance());
     if (!empty($messagesArray)) {
         foreach ($messagesArray as $field => $messages) {
             if (!empty($messages)) {
                 foreach ($messages as $type => $message) {
                     $adaptedMessagesObj->addMessage($field . ': ' . $message);
                 }
             }
         }
     }
     return $adaptedMessagesObj;
 }
Beispiel #7
0
 /**
  * @group ZF-9540
  */
 public function testSubFormTranslatorPreferredOverDefaultTranslator()
 {
     $defaultTranslations = array('isEmpty' => 'Default message');
     $subformTranslations = array('isEmpty' => 'SubForm message');
     $defaultTranslate = new Translator('ArrayAdapter', $defaultTranslations);
     $subformTranslate = new Translator('ArrayAdapter', $subformTranslations);
     Registry::set('Zend_Translator', $defaultTranslate);
     $this->form->addSubForm(new SubForm(), 'subform');
     $this->form->subform->setTranslator($subformTranslate);
     $this->form->subform->addElement('text', 'foo', array('required' => true));
     $this->assertFalse($this->form->isValid(array('subform' => array('foo' => ''))));
     $messages = $this->form->getMessages();
     $this->assertEquals('SubForm message', $messages['subform']['foo']['isEmpty']);
     $this->assertFalse($this->form->isValidPartial(array('subform' => array('foo' => ''))));
     $messages = $this->form->getMessages();
     $this->assertEquals('SubForm message', $messages['subform']['foo']['isEmpty']);
 }
Beispiel #8
0
 /**
  * @group ZF-9364
  */
 public function testElementTranslatorPreferredOverDefaultTranslator()
 {
     $defaultTranslations = array('isEmpty' => 'Default message');
     $formTranslations = array('isEmpty' => 'Form message');
     $elementTranslations = array('isEmpty' => 'Element message');
     $defaultTranslate = new Zend_Translate('array', $defaultTranslations);
     $formTranslate = new Zend_Translate('array', $formTranslations);
     $elementTranslate = new Zend_Translate('array', $elementTranslations);
     Zend_Registry::set('Zend_Translate', $defaultTranslate);
     $this->form->setTranslator($formTranslate);
     $this->form->addElement('text', 'foo', array('required' => true, 'translator' => $elementTranslate));
     $this->form->addElement('text', 'bar', array('required' => true));
     $this->assertFalse($this->form->isValid(array('foo' => '', 'bar' => '')));
     $messages = $this->form->getMessages();
     $this->assertEquals(2, count($messages));
     $this->assertEquals('Element message', $messages['foo']['isEmpty']);
     $this->assertEquals('Form message', $messages['bar']['isEmpty']);
     $this->assertFalse($this->form->isValidPartial(array('foo' => '', 'bar' => '')));
     $messages = $this->form->getMessages();
     $this->assertEquals(2, count($messages));
     $this->assertEquals('Element message', $messages['foo']['isEmpty']);
     $this->assertEquals('Form message', $messages['bar']['isEmpty']);
 }
Beispiel #9
0
    public function testCanValidatePartialNestedFormsWithElementsBelongingToArrays()
    {
        $form = new Zend_Form();
        $form->setElementsBelongTo('foobar');

        $form->addElement('text', 'firstName')
             ->getElement('firstName')
             ->setRequired(false);

        $form->addElement('text', 'lastName')
             ->getElement('lastName')
             ->setRequired(true);

        $subForm = new Zend_Form_SubForm();
        $subForm->setElementsBelongTo('foobar[baz]');
        $subForm->addElement('text', 'email')
                ->getElement('email')
                ->setRequired(true)
                ->addValidator('NotEmpty');

        $subSubForm = new Zend_Form_SubForm();
        $subSubForm->setElementsBelongTo('foobar[baz][bat]');
        $subSubForm->addElement('checkbox', 'home')
                   ->getElement('home')
                   ->setRequired(true)
                   ->addValidator('NotEmpty');

        $subForm->addSubForm($subSubForm, 'subSub');

        $form->addSubForm($subForm, 'sub')
             ->addElement('submit', 'save', array('value' => 'submit'));


        $data = array('foobar' => array(
            'lastName'  => 'Cow',
        ));
        $this->assertTrue($form->isValidPartial($data));
        $this->assertEquals('Cow', $form->lastName->getValue());
        $firstName = $form->firstName->getValue();
        $email     = $form->sub->email->getValue();
        $home      = $form->sub->subSub->home->getValue();
        $this->assertTrue(empty($firstName));
        $this->assertTrue(empty($email));
        $this->assertTrue(empty($home));

        $form->sub->subSub->home->addValidator('StringLength', false, array(4, 6));
        $data['foobar']['baz'] = array('bat' => array('home' => 'ab'));

        $this->assertFalse($form->isValidPartial($data), var_export($form->sub->subSub->home, 1));
        $this->assertEquals('1', $form->sub->subSub->home->getValue());
        $messages = $form->getMessages();
        $this->assertFalse(empty($messages));
        $this->assertTrue(isset($messages['foobar']['baz']['bat']['home']), var_export($messages, 1));
        $this->assertTrue(isset($messages['foobar']['baz']['bat']['home']['stringLengthTooShort']));
    }
Beispiel #10
0
 public function getMessages($name = null, $suppressArrayNotation = true)
 {
     return parent::getMessages($name, $suppressArrayNotation);
 }
 /**
  * Helper function for common work executed in each form step
  * Checks user is "allowed" on this step, redirecting if not
  * Returns result of form validation
  *
  * @param Zend_Form $pageForm form definition for this step
  * @param int $stepNum current step number
  *
  * @return array two elements: the modified Zend_Form and a boolean indicating validation success
  * @todo Needs a massive cleanup as it's way too slow for the ajax calls!
  */
 private function _formStepCommonValidate($pageForm, $stepNum)
 {
     $this->view->errorCount = 0;
     $this->view->stepNum = $stepNum;
     $this->view->stepMax = $this->_stepMax;
     $request = $this->getRequest();
     $pageSession = new Zend_Session_Namespace('online_claims');
     if ($pageForm->isValid($request->getPost())) {
         // Page is valid so set the session step to true
         $pageSession->completed[$stepNum] = true;
         return true;
     } else {
         $pageSession->completed[$stepNum] = false;
         // Mark page as invalid, so user must complete it to progress
         // Output errors to progress section in layout,
         //   and list out IDs that JS can use to highlight error fields
         $errorsJs = "var errorList = " . Zend_Json::encode($pageForm->getMessages()) . ";\n";
         $this->view->headScript()->appendScript($errorsJs, $type = 'text/javascript');
         $errorMessages = $pageForm->getMessages();
         $this->view->errorCount = count($errorMessages);
         $this->view->sidebar = $this->view->partial('partials/rent-guarantee-claim-sidebar.phtml', array('errorsHtml' => $this->view->partial('partials/rent-guarantee-claim-error-list.phtml', array('errors' => $errorMessages)), 'stepNum' => $stepNum, 'stepMax' => $this->_stepMax));
         return false;
     }
 }
 /**
  * The Ajax Post method where above method post request is submited to save
  * a patient and his tests
  */
 public function postorderAction()
 {
     $session = new Zend_Session_Namespace('userObj');
     $userObj = $session->__get('userObj');
     // This page only visible to operator
     if ($userObj['user_type'] == 'operator') {
         $data = $this->getRequest()->getPost();
         $forms = Zend_Registry::get('forms');
         $form = new Zend_Form($forms->orders->adduser);
         if ($form->isValid($data)) {
             $patient = new Application_Model_Patient();
             if ($patient->check_mrn($data)) {
                 $result = $patient->save($data);
                 $erro_data['id'] = $result['id'];
                 $erro_data['order_id'] = $result['order_id'];
                 $erro_data['messages'] = ' Successfully saved';
             } else {
                 $erro_data['messages'] = ' MRN already exists';
             }
         } else {
             $erro_data['id'] = $this->_request->getParam('id', 0);
             $erro_data['order_id'] = $this->_request->getParam('order_id', 0);
             $erro_data['messages'] = '';
             $messages = $form->getMessages();
             foreach ($messages as $row) {
                 $erro_data['messages'] .= (is_array($row) ? current($row) : $row) . ' ';
             }
         }
     } else {
         $erro_data['messages'] = 'You don\'t have permission to this page';
     }
     header('Content-type: application/json');
     echo json_encode($erro_data);
     die;
 }
Beispiel #13
0
 public function testCanGetMessagesOfNestedFormsWithMultiLevelElementsBelongingToArrays()
 {
     $this->_checkZf2794();
     $form = new Zend_Form();
     $form->setElementsBelongTo('foo[bar]');
     $form->addElement('text', 'firstName')->getElement('firstName')->setRequired(false);
     $form->addElement('text', 'lastName')->getElement('lastName')->setRequired(true);
     $subForm = new Zend_Form_SubForm();
     $subForm->setElementsBelongTo('baz');
     $subForm->addElement('text', 'email')->getElement('email')->setRequired(true)->addValidator('NotEmpty');
     $subSubForm = new Zend_Form_SubForm();
     $subSubForm->setElementsBelongTo('bat[quux]');
     $subSubForm->addElement('checkbox', 'home')->getElement('home')->setRequired(true)->addValidator('InArray', false, array(array('1')));
     $subForm->addSubForm($subSubForm, 'subSub');
     $form->addSubForm($subForm, 'sub')->addElement('submit', 'save', array('value' => 'submit'));
     $data = array('foo' => array('bar' => array('lastName' => 'Cow')));
     $form->sub->subSub->home->addValidator('StringLength', false, array(4, 6));
     $data['foo']['bar']['baz'] = array('bat' => array('quux' => array('home' => 'ab')));
     $form->isValidPartial($data);
     $messages = $form->getMessages();
     $this->assertFalse(empty($messages));
     $this->assertTrue(isset($messages['foo']['bar']['baz']['bat']['quux']['home']), var_export($messages, 1));
     $this->assertTrue(isset($messages['foo']['bar']['baz']['bat']['quux']['home']['notInArray']), var_export($messages, 1));
 }
Beispiel #14
0
$form->setMethod("post");
$form->setAttrib("enctype", Zend_Form::ENCTYPE_MULTIPART);
// file element, upload is optional, but if file is uploaded run multiple validators
$file1 = $form->createElement("file", "file1");
$file1->setRequired(false)->setLabel("File:")->addValidator('Count', true, 2)->addValidator('Size', true, "100KB")->addValidator('Extension', true, 'jpg')->addValidator('MimeType', true, array('image/jpeg'))->addValidator('ImageSize', true, array(0, 0, 340, 480));
// add another file element with same validators
$file2 = clone $file1;
$file2->setName("file2");
$submit = $form->createElement("submit", "submit");
$submit->setLabel("GO!");
$form->addElements(array($file1, $file2, $submit));
// check the form
if ($request->isPost()) {
    $formData = $request->getPost();
    if ($form->isValid($formData)) {
        echo "FORM VALID";
    } else {
        print_r($form->getMessages());
    }
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<?php 
echo $form->render(new Zend_View());
?>
</body>
</html>
Beispiel #15
0
 /**
  * Recurse through a form object, rendering errors
  * 
  * @param  Zend_Form $form 
  * @param  Zend_View_Interface $view 
  * @return string
  */
 protected function _recurseForm(Zend_Form $form, Zend_View_Interface $view)
 {
     $content = '';
     $errors = $form->getMessages();
     if ($form instanceof Zend_Form_SubForm) {
         $name = $form->getName();
         if (1 == count($errors) && array_key_exists($name, $errors)) {
             $errors = $errors[$name];
         }
     }
     if (empty($errors)) {
         return $content;
     }
     foreach ($errors as $name => $list) {
         $element = $form->{$name};
         if ($element instanceof Zend_Form_Element) {
             $element->setView($view);
             $content .= $this->getMarkupListItemStart() . $this->renderLabel($element, $view) . $view->formErrors($list, $this->getOptions()) . $this->getMarkupListItemEnd();
         } elseif (!$this->ignoreSubForms() && $element instanceof Zend_Form) {
             $content .= $this->getMarkupListStart() . $this->_recurseForm($element, $view) . $this->getMarkupListEnd();
         }
     }
     return $content;
 }
Beispiel #16
0
 /**
  * @group ZF-11831
  */
 public function testElementsOfSubFormReceiveCorrectDefaultTranslator()
 {
     // Global default translator
     $trDefault = new Zend_Translate(array('adapter' => 'array', 'content' => array(Zend_Validate_NotEmpty::IS_EMPTY => 'Default'), 'locale' => 'en'));
     Zend_Registry::set('Zend_Translate', $trDefault);
     // Translator to use for elements
     $trElement = new Zend_Translate(array('adapter' => 'array', 'content' => array(Zend_Validate_NotEmpty::IS_EMPTY => 'Element'), 'locale' => 'en'));
     Zend_Validate_Abstract::setDefaultTranslator($trElement);
     // Change the form's translator
     $form = new Zend_Form();
     $form->addElement(new Zend_Form_Element_Text('foo', array('required' => true, 'validators' => array('NotEmpty'))));
     // Create a subform with it's own validator
     $sf1 = new Zend_Form_SubForm();
     $sf1->addElement(new Zend_Form_Element_Text('foosub', array('required' => true, 'validators' => array('NotEmpty'))));
     $form->addSubForm($sf1, 'Test1');
     $form->isValid(array());
     $messages = $form->getMessages();
     $this->assertEquals('Element', @$messages['foo'][Zend_Validate_NotEmpty::IS_EMPTY], 'Form element received wrong validator');
     $this->assertEquals('Element', @$messages['Test1']['foosub'][Zend_Validate_NotEmpty::IS_EMPTY], 'SubForm element received wrong validator');
 }
 /**
  * Based on the product that has been modified
  * Pull the correct for, test for validity and save
  * or return the appropriate errors
  */
 public function processAction()
 {
     if (!$this->_request->isXmlHttpRequest() || !$this->_request->isPost() || !$this->_request->getParam('product_category_name')) {
         $this->_redirect('/admin/products/');
     }
     $return = array();
     //Identify the correct Product Form
     $productGateway = new Products_Model_ProductGateway();
     switch ($this->_request->getParam('product_category_name')) {
         case "Annuity":
             $form = $productGateway->getForm('ModifyAnnuityProduct');
             $validForm = $form->isValid($this->_request->getParams());
             break;
         case "Disability":
             $form = $productGateway->getForm('ModifyDisabilityProduct');
             $validForm = $form->isValid($this->_request->getParams());
             break;
         case "Health":
             $form = $productGateway->getForm('ModifyHealthProduct');
             $validForm = $form->isValid($this->_request->getParams());
             break;
         case "Life":
             $form = $productGateway->getForm('ModifyLifeProduct');
             $validForm = $form->isValid($this->_request->getParams());
             break;
         default:
             $form = new Zend_Form();
             $form->addErrorMessage('Unable to indentify a Valid Form');
             $validForm = false;
     }
     // Check the form for validity
     if (!$validForm) {
         $return['formErrors'] = $form->getMessages();
         $return['formResult'] = FALSE;
     } else {
         $form->removeElement('product_company_name');
         $form->removeElement('product_category_name');
         $product = $productGateway->create($form->getValues());
         $product->save();
         $productId = $this->_request->getParam('product_id');
         $flashMessenger = $this->_helper->getHelper('FlashMessenger');
         $flashMessenger->setNamespace('notifications')->addMessage($this->_request->getParam('product_name') . ' Product Updated');
         if ($this->_request->getParam('close') == 1) {
             $return['redirect']['location'] = '/admin/products/';
         } else {
             $return['redirect']['location'] = '/admin/products/modify/' . $productId;
         }
     }
     $this->_helper->json->sendJson($return);
 }
 /**
  * Validate the data against the target form
  *
  * @param array $row
  * @param scalar $key
  * @return mixed Row array or false when errors occurred
  */
 public function validateRowValues(array $row, $key)
 {
     if (!$this->targetForm instanceof \Zend_Form) {
         return $row;
     }
     // Clean up lingering values
     $this->targetForm->clearErrorMessages()->populate(array());
     if (!$this->targetForm->isValid($row)) {
         $messages = $this->targetForm->getMessages(null, true);
         $this->_addErrors($messages, $key, $row);
     }
     // \MUtil_Echo::track($row);
     // Notice: this changes all dates back to string
     $row = array_intersect_key($this->targetForm->getValues(), $row) + $row;
     // Restore the dates as date objects
     foreach ($this->_dateElementNames as $name) {
         $element = $this->targetForm->getElement($name);
         if ($element instanceof \MUtil_JQuery_Form_Element_DatePicker) {
             $row[$name] = $element->getDateValue();
         }
     }
     // \MUtil_Echo::track($row);
     return $row;
 }