The solution I found has something in common with the one provided by Richard Parnaby-King:
target_element must reference a fieldset.
But instead that setting a clone counter, it extends the Zend\Form\Fieldset method prepareElement
Basic application:
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
}
Features:
- Autonumbering labels and/or attributes
- Allows conditional assignment of attributes/labels
- Allows interaction between different elements (ex: passing element A id to element B as target)
- Works with templates
Since this solution could be developed in many ways, I prepared a complete demonstration ready to run and explore.
Note: this demonstration isn't the best implementation but a collection of examples which leads to a result. :-)
This example is meant to run under the default module 'Application' using the prefix 'Bob' in order to avoid conflicts with other files (I imagined someone could already have a file named TestController but I guess nobody have a file called BobController).
Then if you follow the next steps exactly you should be able to run & explore the demonstration without any problem.
The implemantation of the prepareElement
method into the BobFieldset
class could appear massive but its' just a matter of comments, spaces and examples. It could be very small depending on your needs.
STEP 1:
EDIT file: 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,
],
],
STEP 2:
CREATE file: 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];
}
}
STEP 3:
CREATE file: 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'],
],
],
);
}
}
STEP 4:
CREATE file: 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'],
],
],
);
}
}
STEP 5:
CREATE file: 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();
}
}
STEP 6 (last):
CREATE file: Application\view\application\bob\index.phtml
Note: here I added all the external js/css I used, you may already have some in your layout.
<?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>';
OUTPUT:
EDIT
I noticed a little issue: when an element is created from template, the dialogs of the older elements became unaccessible. This is related to the jquery dialog option modal: true
. Probably there is a fix but since the main argument regards Zend...just remove that option.