Values of input fields in the same array

Published on and tagged with cakephp  programming  tip

Today, Petr Vytlacil asked me how to create input fields with the html helper so that the values are in the same array, i.e. how to create something like:

<input name="data[Price][price][]" value= "" />
<input name="data[Price][price][]" value= "" />

The obvious approach with

$html->inputTag('Price/price[]');

does not work, as it creates a wrong name:

<input  name="data[Price][price[]]" value="" />

If we look at this output, we can see, how CakePHP works: it splits “Price/size[]” on the “/” character and adds square brackets. That leads us to the following workaround:

$html->inputTag('Price/price][');

Sure, it is a little bit counterintuitive, but it does the job ;-)

6 comments baked

  • Petr Vytlačil

    Hi Daniel I want one more say thanks for your advice. It would be best write tutorial how generate inputs with the aid of AJAX. For examples any item can has many price after capacity. So this generate dozens of times inputs for setting price and capacity.

    Ciao and tomorrow I wish your national hockey team luck. Because our magic player with No. 68 will have shooting day .-). So I hope.
    Petr Vytlačil – Czech Republic

  • luke barker

    how about for a checkbox ?

    this works for the name, but it breaks on the id ! In that:

    echo $html->checkbox(‘Category/Category][‘, NULL, array(‘value’=>$catid));

    Gives us:

  • luke barker

    LESS THAN SIGN
    input type=”checkbox” name=”data[Category][Category][]” id=”tag_Category][” value=”1″
    GREATER THAN SIGN

    sorry cant work out how to do a html tag!

  • CakePHP初実践メモ その2 – CakePHPの作法関連 | skmtdisk

    […] "同じ配列フォーム変数に値を入れる方法" フォーラム – CakePHP Users in Japan Values of input fields in the same array – cakebaker カテゴリー: 未分類   パーマリンク ← CakePHP1.3初実践メモ […]

  • Rohan

    i’ve been trying this for a while now but could not find anything useful..
    I wanted to add fields at user’s request so i add them using a simple javascript function.
    it generates something like

    <input .... name ="User[hobbies][] ">
    

    But when i submit such data all i get is white screen of death..
    Can you tell me why such happens?

  • cakebaker

    @Rohan: My guess is that this happens because of the Security component, and your request gets black-holed as you modified the form.

    You can either disable the CSRF protection by setting the $validatePost property of the Security component to false, or you can disable it for certain form fields by using the $disabledFields property. See also the documentation of the Security component: http://book.cakephp.org/view/1296/Security-Component.

    Hope this helps!

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License