我找到的解决方案与 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
}
特征:
- 自动编号标签和/或属性
- 允许有条件地分配属性/标签
- 允许不同元素之间的交互(例如:将元素 A id 作为目标传递给元素 B)
- 使用模板
由于可以通过多种方式开发此解决方案,因此我准备了一个完整的演示,可以运行和探索。
注意:这个演示不是最好的实现,而是导致结果的示例集合。:-)
此示例旨在使用前缀“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>';
输出:
编辑
我注意到一个小问题:当从模板创建元素时,旧元素的对话框变得无法访问。这与 jquery 对话框选项有关modal: true
。可能有一个修复,但由于主要论点是关于 Zend ......只需删除该选项。