I would like to create a form that allows the user to input any number of values, each in a separate text field using an array notation. The example expected HTML output is:
<dd id="dupa-element">
<input type="text" name="dupa[]" value="">
<input type="text" name="dupa[]" value="">
</dd>
However, I can't seem to find a way to introduce multiple input elements within a single element, using array notation without indices.
Currently, I do this:
$elt1 = new Zend_Form_Element_Text('1');
$elt1->setOptions(array('belongsTo' => 'dupa'));
$elt2 = new Zend_Form_Element_Textarea('2');
$elt2->setOptions(array('belongsTo' => 'dupa'));
While this works, Zend_Form treats these as independent elements (which can have different sets of validators and filters - that's sort of cool) and the resulting HTML is something along these lines:
<dd id="dupa-1-element">
<input type="text" name="dupa[1]" id="dupa-1" value="">
</dd>
<dd id="dupa-2-element">
<input type="text" name="dupa[2]" id="dupa-2" value="">
</dd>
Is there a (preferably simple) way to achieve the indexless array notation I'm after?
I would follow MWOP's tutorial on creating composite elements. More work, but it's less Trial&Error then akond's solution. Basic idea for me would be extending the Zend_Form_Element_Multi
(what you want is how Zend_Form_Element_Multiselect/MultiCheckbox works).
I managed to do this by having a "container subform", and then adding subforms to that "container" e.g.:
$container = new Zend_Form_SubForm();
$subform1 = new Zend_Form_SubForm();
$container->addSubForm($subform1, '1');
$subform2 = new Zend_Form_SubForm();
$subform2->addSubForm($subform1, '2');
$mainForm = new Zend_Form();
$mainForm->addSubform($container,'mysubforms');
Hope that helps.
You need a custom view helper for that.
class Zend_View_Helper_FormMySelect extends Zend_View_Helper_Abstract
{
function formMySelect ($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n")
{
$result = array ();
foreach ($options as $option)
{
$result [] = sprintf ('<input type="text" name="%s[]" value="">', $name);
}
return join ($listsep, $result);
}
}
Than have in your form something like that:
$form = new Zend_Form();
$form->addElement ('select', 'test', array (
'label' => 'Test',
'multioptions' => array (
'test 1',
'test 2',
'test 3',
),
));
$form->test->helper = 'formMySelect';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With