Add a subform to a form with ajax on submit

佐手、 提交于 2019-12-05 07:42:58

Add a prefix of the subform to the subform elements. I used the prefix "child" to represent the subforms. Each subform will be created as child1, child2 and so on.

public function clonerecursivegroupAction()
{
       //.. Other code

        $subform = new Zend_Form_SubForm();
    $subform->setIsArray(true);
    $subform->setName("child$id");
    $Element1 = $subform->createElement('text', "newfield$id");
    $Element1->setLabel("newfield$id")
             ->setRequired(true);
    $subform->addElement($Element1);

    $Element1 = $subform->createElement('text', "nextfield$id");
    $Element1->setLabel("nextfield$id")
             ->setRequired(true);

    $subform->addElement($Element1);

    $this->view->field = $subform; 
 // Rest of your statements

}

Then, in the preValidation function, filter the subforms using the subform prefix, instead of the field name:

   public function preValidation(array $data) {
         // array_filter callback
        function findForms($field) {
         // return field names that include 'child'
          if (strpos($field, 'child') !== false) {
               return $field;
           }
         }

      $subForms = array_filter(array_keys($data), 'findForms'); //filter the subform elements

      $children = array();
      foreach ($subForms as $subform) {

          if (is_array($data[$subform])) { 
        $children[$subform] = $data[$subform];
      }

       }

       //Iterate the children
       foreach ($children as $key => $fields) { //$key = subformname, $field=array containing fiend names and values

       // strip the id number off of the field name and use it to set new order
       $order = ltrim($key, 'child') + 2;
       $this->addNewForm($key, $fields, $order);
     }

}

Add New Form function creates each of the sub forms and attaches to the main form:

     public function addNewForm($form, $elements, $order) {

            $subform = new Zend_Form_SubForm();
    $subform->setIsArray(true);
    foreach ($elements as $key => $el) {
          $Element1 = $subform->createElement('text', $key);
              $Element1->setLabel($form.$key)
             ->setValue($el)
                 ->setRequired(true);
                   $subform->addElement($Element1);
    }
        $this->addSubForm($subform, $form, $order);

    }

[EDIT] Using setIsArray for a subform creates each element of the subform as an array element. It simplifies the preValidate function. Edited the code to utilize this feature.

See the complete code in pastebin

Here is another solution using belongsTo, providing array notation to the sub form elements : http://www.stephenrhoades.com/?p=364

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!