1

I creating a text box dynamically (based on user selection)using jquery ..is there any way to provide validation for that text box from zend form..?

1

1 Answer 1

2

Yes there is.

most credits go to jeremy kendall see http://www.jeremykendall.net/2009/01/19/dynamically-adding-elements-to-zend-form/

The way i solved it is by doing a jquery/ajax call to a action which adds get a form element something like:

$.ajax({
    type : "POST",
    url : "/<controller>/addfield/",
    success : function(newElements) {
        // Insert new element before the submit button
        $("#productsNew-submit-element").before(newElements);
    }
});

What this does is it call a action that generates a form element and returns the html which you can then add

public function addfieldAction()
{
    //use $ajaxContext = $this->_helper->getHelper('AjaxContext'); in the init to make it return html via ajax

    $element = new Zend_Form_Element_Text("extraElement_1");
    $element->setBelongsTo("yourForm");
    $element->setLabel('myElementName');

    /*
    set other stuff like decorators or so
    */

    //now create the html 
    $elements .= $element->__toString();

    $this->view->fields = $elements;
}

After that you will get a new element in your form via ajax

Now when you submit you have to do that again but then pre validation

  1. first check if your form has extraElements if so add them again
  2. fill the add element with the posted value
  3. validate
public function saveAction()
{
    function findFields($field) {
        // return field names that include 'extraElement_'
        if (strpos($field, 'extraElement_') !== false) {
            return $field;
        }
    }

    //set all stuff you need especially the form

    if($this->getRequest()->isPost()) {
        $postValues = $this->getRequest()->getPost();

        //step 1 
        $extraFields = array_filter(array_keys(current($postValues)), 'findFields');

        //add the element before validation
        if(count($extraFields) !== 0) {
            foreach(extraFields as $extraField) {
                $this->addFields($postValues[$extraField]); <-- step 2 add the field(s)
            }
        }

        //step 3 validate
        if($this->_form->isValid($postValues)) {
            //do post validation stuff
        } else {
            //show errors
        }
    }       
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.