Student
Student

Reputation: 1863

How to add '[]' to form element name in Zend_Form?

I am creating form elements like this

    $elements = array();

    $element = $this->CreateElement('checkbox', 'field[0]' );
    $element->setLabel( 'MyField1' );
    $element->setAttrib( 'checked', true );
    $elements[] = $element;

    $element = $this->CreateElement('checkbox', 'field[1]' );    
    $element->setLabel( 'MyField2' );
    $element->setAttrib( 'checked', true );
    $elements[] = $element;

    $this->addElements( $elements );

But it is setting name='field0' and name='field1' instead of name='field[0]' and name='field[1]'

How can we add [] in elements names?

Thanks

Upvotes: 2

Views: 1063

Answers (5)

nickel715
nickel715

Reputation: 2803

This works for me

$file = $this->createElement('file', 'myImgUpload');
$file->setAttrib('name', 'myImgUpload[]');

Btw: in Zend_Form_Element::setName() the methode Zend_Form_Element::filterName() strip the brackets

Upvotes: 0

Kyal
Kyal

Reputation: 1

See http://zend-framework-community.634137.n4.nabble.com/Zend-Form-Element-set-name-allowBrackets-td679084.html

So, first off, names are not allowed to have brackets internally so that a variety of other features will work (overloading access, primarily).

That said, you can force brackets to appear in the output in a couple of different ways.

  • If you want brackets for allowing multiple values to be captured -- i.e., a name like 'foo[]' -- turn on the isArray property:

    $element->setIsArray(true); // or pass a true value to the
                                // "isArray" key during
                                // instantiation
    
  • If you want the value to be a key in another value, e.g., "bar[foo]", then you need to tell the element it belongs to another value:

    $element->setBelongsTo('bar'); // or pass the value to the
                                   // 'belongsTo' key during
                                   // instantiation
    
  • If you use sub forms, array notation happens by default; all elements "belongTo" the name of the sub form

Upvotes: 0

Batbekh Batmagnai
Batbekh Batmagnai

Reputation: 59

i read 2 kind of solutions one is setElementsBelongTo other one is setIsArray but the solutions are not comfortable for me why they block brackets i don't understand.why why why? I think one way is just edit filter function to allow brackets.

Upvotes: 2

Haim Evgi
Haim Evgi

Reputation: 125496

i think its not support in zend form only in :

Zend_Form_SubForm

like

$foo = new Zend_Form_SubForm();
$foo->setElementsBelongTo('foo')
    ->setElements(array(
        'bar' => 'text',
        'baz' => 'text'
    ));
echo $foo;

wich give you :

<input type="text" name="foo[bar]" id="foo.bar" value="" />
<input type="text" name="foo[baz]" id="foo.baz" value="" />

Upvotes: 1

Related Questions