BadHorsie
BadHorsie

Reputation: 14544

CakePHP - Change the "name" attribute of a form input

I have a helper which generates a custom form input.

Helper (simplifed code)

public function customInput($field, array $options = array()) {

    $defaultOptions = array(
        'class' => 'custom-input',
        'label' => false
    );
    $options = array_merge($defaultOptions, $options);

    return $this->Form->input($field, $options);
}

Now how can I modify the name attribute of the input by prefixing it with another 'model'. For example, the input will by default have the following name attribute:

<input type="text" name="data[MyModel][field]" />

But I want it to be:

<input type="text" name="data[_custom][MyModel][field]" />

Mainly, what seems tricky is that I don't know how to get the model name that will be used by default. Also, I need something that works if the default model hierarchy is more complicated, like:

<input type="text" name="data[MyModel][AssociatedModel][field]" />

Would need to be modified to:

<input type="text" name="data[_custom][MyModel][AssociatedModel][field]" />

Upvotes: 0

Views: 5836

Answers (3)

Alvaro
Alvaro

Reputation: 41595

For the input helper, CakePHP uses $this->model() to get the name of the current model.

You can see it inside lib\Cake\view\FormHelper, or directly from the online API: http://api20.cakephp.org/view_source/form-helper#line-942

$modelKey = $this->model();

Maybe that helps.

Upvotes: 0

dogmatic69
dogmatic69

Reputation: 7575

You want name

echo $this->Form->input('whatever', array('name' => 'data[_custom][MyModel][field]'));

There is nothing like data[_custom][MyModel][AssociatedModel][field] in cakes form helper. Your options as far as automation go is:

  • field // normal, use current model
  • Model.field // used with not default model / relations
  • Model.$i.field // User hasMany Post would be Post.$i.field

Upvotes: 2

Ross
Ross

Reputation: 17967

well you can do: $this->Form->input('_custom.MyModel.field'); to create an input in the format you require.

It becomes a case of passing the appropriate model name and associated model with it.

I don't know how you could do this automatically as obviously each relation is different/may have multiple associations.

So using your helper: echo $this->YourHelper->CustomInput('_custom.MyModel.MyAssociation.field', $options) might do the trick.

Upvotes: 0

Related Questions