简体   繁体   中英

CakePHP does not auto-populate a field (that has no Model) after submission

The situation

I'm working on a large form which have been split into several tabs, both to group fields of a kind and make filling easier. The tabs are activated using JavaScript (jQuery) and the form is submitted whole (all tabs at once, even if there are blank fields).

I am trying to submit a hidden field along with the form to keep user's current tab. This way, when the form is submitted, data is saved and the user goes back to the very same tab it was before. This field is not attached to any Model, as it is just a helper .

The problem + what have I tried

The field is correctly populated by as the user switch tabs, and it is submitted along with the form. This is what I did:

<?php 
echo $this->Form->create('Briefing', array('enctype' => 'multipart/form-data'));

    // This is my aux field, which is populated via jQuery as user switch tabs
    echo $this->Form->hidden('tab-active', array('name' => 'tab-active', 'id' => 'tab-active')); 

    echo $this->Form->input('title');
    echo $this->Form->submit('Save', array('class' => 'btn btn-success'));

echo $this->Form->end(); 
?>

Let's suppose the user submitted the form when it was at "Tab #4". When I debug($this->data); at my BriefingsController , this is what I get:

/app/Controller/BriefingsController.php (line 133)
array(
    'tab-active' => 'tab-4',
    'Briefing' => array(
        'title' => 'My test title'
    )
)

So my Controller receives the form data for both tab-active and Briefing.title fields, but when the form is loaded after submission, only the Model field is populated with the submitted data, and tab-active comes with an empty value. CakePHP does not auto populate the value for my non-model-attached field .

Any thoughts on that? Is this a default CakePHP behavior or is there something I could do to make it work(auto populate)? I have no problem with the jQuery (already tested it in several ways), the real problem is into getting this field populated back after form submission . Any help is much appreciated.

CakePHP populates forms with the data of the form's model. So if you create a form for 'Briefing' creation, CakePHP will look at the $this->data['Briefing'] array, and populate inputs matching the fields that are present in this array. So as your hidden 'tab-active' field is present inside the 'Briefing' Form creation, CakePHP expects your 'Briefing' model to have a 'tab-active' attribute.

So my guess is that your $this->data array should be :

array(
    'Briefing' => array(
        'tab-active' => 'tab-4',
        'title' => 'My test title'
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM