Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend_Form array notation with no indices

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?

like image 877
mingos Avatar asked May 18 '11 08:05

mingos


3 Answers

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).

like image 162
Tomáš Fejfar Avatar answered Oct 23 '22 05:10

Tomáš Fejfar


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.

like image 25
Monir Uddin Avatar answered Oct 23 '22 03:10

Monir Uddin


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';
like image 33
akond Avatar answered Oct 23 '22 03:10

akond