1

从这些问题来看:

Zend framework 2 循环遍历元素集合的元素

如何将参数传递给 Zend 表单集合实例以及如何在 ZF2 中设置自定义字段集标签?

我想没有自定义集合元素的好方法。

例如,有一个像这样的集合:

//path: MyModule\Form\MyFieldset

public function __construct($name = null) {

    parent::__construct('myFieldset');

    $this->add([
        'name'=>'test',
        'type' => Element\Collection::class,
        'options' => [
            'label' => 'MyCollection',
            'count' => 6,
            'should_create_template' => true,
            'target_element' => new Element\Text()
        ],
    ]);
}

然后为每个文本元素和/或自动编号的标签定义(此处为当前类)自定义属性,然后输出(只需调用 zend 助手 FormCollection,无需任何自定义视图助手):

<label>
   <span>text element n° 1</span>
   <input type="text" name="myFielset[test][0]" id='myId_0' alt='input 0' value="">
</label>

<label>
   <span>text element n° 2</span>
   <input type="text" name="myFielset[test][1]" id='myId_1' alt='input 1' value="">
</label>

[...]

我错了吗?

(我之所以这么问是因为我找到了一个很好的解决方案,并且可能有助于发布它)

4

3 回答 3

1

我找到的解决方案与 Richard Parnaby-King 提供的解决方案有一些共同之处:

target_element 必须引用一个字段集。

但不是设置克隆计数器,而是扩展Zend\Form\Fieldset method prepareElement

基本应用:

namespace Module\Form;

use Zend\Form\Fieldset;
use Zend\Form\FormInterface; //needed in order to call prepareElement method

class MyFieldset extends Fieldset {


    public function __construct($name = null) {
        parent::__construct($name);

        $this->add([
            'name' => 'question',
            'type' => 'text',
            'attributes' => [
                'alt' => 'input',
            ],
            'options' => [
                'label' => 'Text',
            ],
        ]);

    }//construct

    public function prepareElement(FormInterface $form){

        parent::prepareElement($form);

        $name = $this->getName(); 
        //Do stuff related to this fieldset

        foreach ($this->iterator as $elementOrFieldset) {

           $elementName=$elementOrFieldset->getName()
           //Do stuff related to this fieldset children
        }

    }//prepareElement

}

特征:

  1. 自动编号标签和/或属性
  2. 允许有条件地分配属性/标签
  3. 允许不同元素之间的交互(例如:将元素 A id 作为目标传递给元素 B)
  4. 使用模板


由于可以通过多种方式开发此解决方案,因此我准备了一个完整的演示,可以运行和探索

注意:这个演示不是最好的实现,而是导致结果的示例集合。:-)

此示例旨在使用前缀“Bob”在默认模块“Application”下运行,以避免与其他文件冲突(我想象有人可能已经有一个名为 TestController 的文件,但我猜没有人有一个名为 BobController 的文件)。

然后,如果您完全按照接下来的步骤进行操作,您应该能够毫无问题地运行和探索演示。

prepareElement方法在BobFieldset类中的实现可能看起来很庞大,但这只是注释、空格和示例的问题。根据您的需要,它可能非常小。

步骤1:

编辑文件:Application\config\module.config.php

//add bob route to router

'router' => [
        'routes' => [

            'bob' => [
                'type' => Literal::class,
                'options' => [
                    'route'    => '/bob',
                    'defaults' => [
                        'controller' => Controller\BobController::class,
                        'action'     => 'index',
                    ],
                ],
            ],

            [...]

//add BobController

 'controllers' => [
        'factories' => [
            [...]
            Controller\BobController::class => InvokableFactory::class,
        ],
    ],

第2步:

创建文件:Application\src\Controller\BobController.php

<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Application\Form\BobForm;

class BobController extends AbstractActionController
{
    public function __construct(){}

    public function indexAction()
    {

     $form = new BobForm('album');

     $request = $this->getRequest();


     if( $request->isPost()){

       $form->setInputFilter($form->getInputFilter());
       $form->setData($request->getPost());

        if (! $form->isValid()) {
            return ['form' => $form];
        }
     }
     return ['form' => $form];
    }
}

第 3 步:

创建文件:Application\src\Form\BobForm.php

 <?php

namespace Application\Form;

use Zend\Form\Element;
use Zend\Form\Form;

class BobForm extends Form
{
   private $inputFilter;
    public function __construct($name = null)
    {
        parent::__construct($name);

        $this->setLabel('formBaseFieldset');

        $this->add([
            'name' => 'select',
            'type' => 'select',
            'options' => [
                'label' => 'random element',
                'value_options' => [
                             0 => null,
                             1 => 'someThing',
                             2 => 'someThingElse',
                     ],
            ],
            'attributes' => [
            'value'  => 0,
            ],
        ]);

        $this->add([
            'name' => 'answer',
            'type' => Element\Collection::class,
            'options' => [
                'label'=>'bobFieldset',
                'count' =>3,
                'should_create_template' => true,
                'target_element' => new \Application\Form\BobFieldset ,
            ],
            'attributes' => [
            'id'=>'bob',
            ],
        ]);
        $this->add(array(
             'name' => 'addNewRow',
             'type' => 'button',
             'options' => array(
                 'label' => 'Add a new Row',
             ),
             'attributes' => [
             'onclick'=>'return add_category()',

             ]
         ));

}//construct

    public function getInputFilterSpecification() {
               return array(

            'select' => [
                'validators' => [
                    ['name' => 'NotEmpty'],
                ],  
            ],
        );
    }

}

第4步:

创建文件:Application\src\Form\BobFieldset.php

<?php

namespace Application\Form;

use Zend\Form\Fieldset;
use Zend\Form\FormInterface; //needed in order to call prepareElement method
use Zend\InputFilter\InputFilterProviderInterface;

class BobFieldset extends Fieldset  implements InputFilterProviderInterface 
{

   private $inputFilter;

    public function __construct($name = null) {

        parent::__construct($name);

        $this->setLabel('bobFieldset: Answer __num__');

        $this->add(array(
             'name' => 'text',
             'type' => 'text',
             'options' => array(
                 'label' => 'Text __num__',
             ),
             'attributes' => [
             'customAttribute'=>' -> ', //see below

             ]
         ));

        $this->add(array(
             'name' => 'optionsButton',
             'type' => 'button',
             'options' => array(
                 'label' => 'Options',
             ),
             'attributes' => [
             'data-dialog-target'=>'options', //sub fieldset name
             'class'=>'options',
             ]
         ));

        $this->add( new \Application\Form\BobSubFieldset('options'));
    }

   public function prepareElement(FormInterface $form)
    {

        /*--->here we're looping throug the collection target_element(instance of BobFieldset)<---*/

        //Leave untouched the default naming strategy
        parent::prepareElement($form);



        //output: (string) 'answer[$i]' -> BobFieldset's clone name attribute
        //Note: $i corresponds to the instance number
        $name = $this->getName();   //var_dump($name);

        //output: array(0=>'answer',1=>$i)
        $sections = $this->splitArrayString($name); //var_dump($sections);

        //output: (string) $i ->When the collection's option 'should_create_template' is setted to true, the last one will be: (string) '__index__'
        $key=end($sections);  //var_dump($key);

        //output (string) 'answer_$i' -> I guess this could be the easyest way to handle ids (easy to manipulate, see below)
        $string=implode('_',$sections); //var_dump($string);


        //Just because a label like 'answer number 0' is ugly ;-)
        $keyPlus=(is_numeric($key)) ? $key+1 : $key;  //var_dump($keyPlus);

        //Since we're using different placeholders:
        //Predefined __index__: used for names ($key)
        //__num__: used for labels ($keyplus)
        //Then we need this control to avoid replacements between placeholders(check below)
        $isTemplate=($keyPlus==$key) ? true : false;


        if(!$isTemplate){
          //get the label of the current element(BobFieldset clone) and replace the placeholder __num__ (defined above) with the current key (+1)
          $label = str_replace('__num__',($keyPlus),$this->getLabel());
          $this->setLabel($label); //var_dump($this->getLabel());
        }
        /*--->From here we're looping throug the target_element (BobFieldset) children<---*/
        foreach ($this->iterator as $elementOrFieldset) {

            //output: (string) 'answer[$i][elementName]'
            //answer[0][text]
            //answer[0][optionsButton]
            //answer[0][options]
            //answer[1][text]
            //...
            $elementName=$elementOrFieldset->getName();//var_dump($elementName);

            //Example: get specific element and OVERWRITE an autonumbered label
            $sections = $this->splitArrayString($elementName);
            $trueName=end($sections);
            if($trueName=='text' && !$isTemplate){
              $elementOrFieldset->setLabel('Input '.$keyPlus);
            }

           //Example2: get specific element via custom attribute
           //Note: when an attribute isn't listed into the Zend\Form\View\Helper\AbstractHelper's $validGlobalAttributes (array) it will be automatically removed on render
           //global attributes data-? will be rendered
           if($target=$elementOrFieldset->getAttribute('customAttribute')){
             $label=$elementOrFieldset->getLabel();
             $elementOrFieldset->setLabel($label.$target);
             }

           //Reference another element as target for a javascript function
           //button 'optionsButton' will have an attribute containing the id of the relative element 'options' (BobSubFieldset)
           //Alternatives:
           //1) work only with javascript & DOM 
           //2) set a javascript call directly: $elementOrFieldset->setAttribute('onclick','return doSomething();'); check BobForm 'addNewRow' button
           if($target=$elementOrFieldset->getAttribute('data-dialog-target')){
             $elementOrFieldset->setAttribute('data-dialog-target',$string.'_'.$target);
           }

           //set id for jqueryui dialog function. This id corresponds to the target setted above
           //The attribute data-transform will be used as jquery selector to create the dialogs
           if($elementOrFieldset->getAttribute('data-transform')=='dialog'){
             $id = str_replace(['[', ']'],['_', ''],$elementName);
             $elementOrFieldset->setAttribute('id',$id);

             //Set and autonumbering the dialog title
             if(!$isTemplate){
               $title = str_replace('__num__',($keyPlus),$elementOrFieldset->getAttribute('title'));
               $elementOrFieldset->setAttribute('title',$title);
             }
           }


        }//foreach

    }

    public function splitArrayString($string){

    return preg_split('/\h*[][]/', $string, -1, PREG_SPLIT_NO_EMPTY);
    }


    public function getInputFilterSpecification() {
               return array(

            'text' => [
                'validators' => [
                    ['name' => 'NotEmpty'],
                ],  
            ],
        );
    }
 }

第 5 步:

创建文件:Application\src\Form\BobSubFieldset.php

<?php

namespace Application\Form;

use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;

class BobSubFieldset extends Fieldset  implements 
InputFilterProviderInterface {

   private $inputFilter;

    public function __construct($name = null) {
         parent::__construct($name);

              $this->setLabel('bobSubFieldset');
              $this->setattribute('data-transform','dialog');
              $this->setattribute('title','Options for answer __num__');


         $this->add(array(
             'name' => 'first',
             'type' => 'text',
             'options' => array(
                 'label' => 'firstOption',
             ),
             'attributes' => [

             ]
         ));
         $this->add(array(
             'name' => 'second',
             'type' => 'text',
             'options' => array(
                 'label' => 'secondOption',
             ),
             'attributes' => [

             ]
         ));
                $this->add(array(
             'name' => 'third',
             'type' => 'text',
             'options' => array(
                 'label' => 'thirdOption',
             ),
             'attributes' => [

             ]
         ));

    }

    public function getInputFilterSpecification() {
        return array();
    }
}

第 6 步(最后):

创建文件:Application\view\application\bob\index.phtml

注意:这里我添加了我使用的所有外部 js/css,您的布局中可能已经有一些。

<?php

$script=
"$(document).ready(function(){

 $( '#bobContainer' ).on('click','button.options', function () {

    //Retrieve the target setted before...
    id=$(this).attr('data-dialog-target');
     $('#'+id).dialog('open');


    return false;
  });

 //We need a custo event in order to detect html changes when a new element is added dynamically
 $( '#bobContainer' ).on( 'loadContent', function() {

     //We need this because by default the dialogs are appended to the body (outside the form)
     $('fieldset[data-transform=dialog]').each(function (index) {

     $(this).dialog({
        autoOpen: false,
        appendTo:$(this).parent(),
        modal: true,
        height: 250,
        width: 450,
        buttons: {

        Ok: function() {
          $(this).dialog( 'close' );
        }
      },



    });
    });
  });


 $( '#bobContainer' ).trigger( 'loadContent');
}); //doc/ready

function add_category() {

var currentCount = $('#bob > fieldset').length;
var template = $('#bob > span').data('template');

template = template.replace(/__index__/g, currentCount);
template = template.replace(/__num__/g, (currentCount+1));

$('#bob').append(template).trigger( 'loadContent');

return false;
}
";
$this->headScript()
            ->appendFile("https://code.jquery.com/jquery-3.3.1.min.js",'text/javascript',array('integrity' => 'sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=','crossorigin'=>'anonymous'))
            ->appendFile("https://code.jquery.com/ui/1.12.1/jquery-ui.js")
            ->appendScript($script, $type = 'text/javascript', $attrs = array());
$this->headLink()
            ->appendStylesheet('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css')
            ->appendStylesheet('https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');


echo $this->headScript();
echo $this->headLink();

$title = 'Custom Collection Attributes';
$this->headTitle($title);

echo'<h1>'.$this->escapeHtml($title).'</h1>';
echo'<div class="container" id="bobContainer">';


$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form);

$form->add([
            'name' => 'submit',
            'type' => 'submit',
            'attributes' => [
                'value' => 'Go',
                'id'    => 'submitbutton',
                'class'=>'btn btn-success',
            ],
        ]);

$submit = $form->get('submit');

echo '<br>'.$this->formSubmit($submit);

echo $this->form()->closeTag();

echo'</div>';

输出:

截图1 截图2

截图3


编辑 我注意到一个小问题:当从模板创建元素时,旧元素的对话框变得无法访问。这与 jquery 对话框选项有关modal: true。可能有一个修复,但由于主要论点是关于 Zend ......只需删除该选项。

于 2018-03-07T00:35:41.313 回答
1

我刚刚意识到还有另一种更好且更灵活的解决方案:扩展集合元素(为什么我以前不考虑它?)。

这种方法的主要优点是不需要拆分元素的名称:“克隆号”( [0],[1],...) 可以直接访问。

特征:

  1. 自动编号标签和/或属性
  2. 允许有条件地分配属性/标签
  3. 允许不同元素之间的交互(有限,请参阅下面的问题)
  4. 使用模板(使用占位符 ->阅读更多),无需检查索引是否为数字(这是我的其他解决方案的问题)
  5. target_element 可以是一个简单的元素,不需要实现Zend/Form/Fieldset

问题:

  1. 集合 ID 可能有问题,因为 (2)

  2. 从扩展脚本中无法访问最终元素的名称(例如 fieldset[subfieldset][0][elementName]:),因为它将在以后分层构建。


这个怎么运作:

1. 扩展集合

//file: Application\src\Form\Element\ExtendedCollection.php
<?php

namespace Application\Form\Element;

use Zend\Form\Element\Collection;

class ExtendedCollection extends Collection
{
    protected $autonumbering_callback = false;
    protected $autonumbering_callback_options = [];  

    public function setOptions($options)
    {
        parent::setOptions($options);

        if (isset($options['autonumbering_callback'])) {
            $this->autonumbering_callback=(isset($options['autonumbering_callback'][0])) ? $options['autonumbering_callback'][0] : $options['autonumbering_callback'];
            $this->autonumbering_callback_options=(isset($options['autonumbering_callback'][1])) ? $options['autonumbering_callback'][1] : [];
        }

        return $this;
    }

    protected function addNewTargetElementInstance($key)
    {

        //Original instructions
        $this->shouldCreateChildrenOnPrepareElement = false;

        $elementOrFieldset = $this->createNewTargetElementInstance();
        $elementOrFieldset->setName($key);

        $this->add($elementOrFieldset);

        if (! $this->allowAdd && $this->count() > $this->count) {
            throw new Exception\DomainException(sprintf(
                'There are more elements than specified in the collection (%s). Either set the allow_add option ' .
                'to true, or re-submit the form.',
                get_class($this)
            ));
        }

        //Callback
        if ($this->autonumbering_callback && method_exists(...$this->autonumbering_callback) && is_callable($this->autonumbering_callback)){
          call_user_func_array($this->autonumbering_callback,[$elementOrFieldset,$key,$this->autonumbering_callback_options]);
        }

        return $elementOrFieldset;
    }

}

2. Target 元素(这里是一个字段集,但可以是一个简单的元素)

//file: Application\src\Form\BobFieldset.php
<?php

namespace Application\Form;

use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;

class BobFieldset extends Fieldset  implements InputFilterProviderInterface {

   private $inputFilter;

    public function __construct($name = null) {

        parent::__construct($name);

        $this->setLabel('Answer __num__');
        $this->setAttributes([
                             'title'=>'title no __num__',
                             'data-something'=>'custom attribute no __num__',
                             ]);


        $this->add(array(
             'name' => 'text',
             'type' => 'text',
             'options' => array(
                 'label' => 'Text',
             ),
         ));

         $this->add(array(
             'name' => 'text2',
             'type' => 'text',
             'options' => array(
                 'label' => 'Text',
             ),
         ));

         $this->add(array(
             'name' => 'text3',
             'type' => 'text',
             'options' => array(
                 'label' => 'Text',
             ),
         ));
    }

    public function getInputFilterSpecification() {
        return array(/*...*/);
    }

}//class

3. 表单(带有一些回调示例)

//file: Application\src\Form\BobForm.php
<?php

namespace Application\Form;

use Zend\Form\Form;
use Zend\Form\Fieldset; //needed for myCallback3
use Application\Form\Element\ExtendedCollection;

class BobForm extends Form
{
   private $inputFilter;
    public function __construct($name = null)
    {
        parent::__construct($name);


        $this->add([
            'name' => 'answer',
            'type' => ExtendedCollection::class,
            'options' => [
                'count' =>3,
                'should_create_template' => true,
                'target_element' => new \Application\Form\BobFieldset2 ,
                'autonumbering_callback'=>[
                                           [$this,'myCallback'],
                                           ['attributes'=>['title','data-something'],'whateverYouWant'=>'something',]
                                          ],
                ],
        ]);
    }

    public function myCallback($elementOrFieldset, $key, $params){

      foreach($params['attributes'] as $attr){
        $autoNumAttr=str_replace('__num__',($key),$elementOrFieldset->getAttribute($attr));
        $elementOrFieldset->setAttribute($attr,$autoNumAttr);
      }//foreach

      $label = str_replace('__num__',($key+1),$elementOrFieldset->getLabel());
      $elementOrFieldset->setLabel($label);
    }

    public function myCallback2($elementOrFieldset, $key, $params){

      $char='a';
      foreach(range(1,$key) as $i) {
        if($key>0){$char++;}
      }
      $elementOrFieldset->setLabel('Answer '.$char);
    }

    public function myCallback3($elementOrFieldset, $key, $params, $isChild=null){

      if(!$isChild){$elementOrFieldset->setLabel('Answer '.($key+1));}
      else{$elementOrFieldset->setLabel($key);}

      //don't forget: use Zend\Form\Fieldset;
      if($elementOrFieldset instanceof Fieldset && !$isChild){
        $char='a';
        foreach($elementOrFieldset as $item){
          $this->myCallback3($item,($key+1 .$char++.') '),null,1);
        }
      }
    }
}

输出

没有autonumbering_callback选项: 没有 autonumbering_callback 选项

使用myCallback使用 myCallback

使用myCallback2使用 myCallback2

使用myCallback3使用 myCallback3

于 2018-03-12T14:07:19.660 回答
0

target_element必须引用一个字段集。这可以是集合所在表单中的新实例,也可以是类名。

例如:

$fieldset = new Fieldset();
$fieldset->add([
    'name' => 'some_field_name',
    'type' => 'text',
]);
$this->add([
    'name'=>'test',
    'type' => Element\Collection::class,
    'options' => [
        'label' => 'MyCollection',
        'count' => 6,
        'should_create_template' => true,
        'target_element' => $fieldset
    ],
]);

或者

$this->add([
    'name'=>'test',
    'type' => Element\Collection::class,
    'options' => [
        'label' => 'MyCollection',
        'count' => 6,
        'should_create_template' => true,
        'target_element' => '\Namespace\Form\MyTextFieldset',
    ],
]);

在为每个输入自定义标签方面,我还没有找到一种方法来做到这一点。

不太确定集合如何工作的内部工作原理,但我怀疑它会根据target_element需要创建尽可能多的新实例。就只是向标签(或任意属性)添加一个数字而言,您可以使用以 开头的静态属性创建一个字段集类1,将其添加到您的标签并增加其值?

例如:

namespace Module\Form;
use Zend\Form\Fieldset;

class MyFieldset extends Fieldset {
    public static $instance_count = 1;

    public function __construct() {
        parent::__construct();

        $this->add([
            'name' => 'question',
            'type' => 'text',
            'attributes' => [
                'alt' => 'input' . MyFieldset::$instance_count,
            ],
            'options' => [
                'label' => 'Text element No ' . MyFieldset::$instance_count,
            ],
        ]);
        MyFieldset::$instance_count++;
    }
}
于 2018-03-06T11:52:10.760 回答