phpcakephpcakephp-2.0

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]" />

Solution

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