I am using cakephp 1.3, and want to set form inputs as "required" explicitly instead of relying on model validation. A form input example:
<div class="input text required">
<label for="ClaimClaimantFirstName">First Name</label>
<input name="data[ClaimClaimant][first_name]" type="text" id="ClaimClaimantFirstName" />
</div>
I also want to maintain the FormHelper naming instead of using custom form helper names. Example:
$this->Form->input(...)
The solution I came up with is
implement MyFormHelper, extending from FormHelper and overriding the input method. Specifically, around line 804 of the FormHelper, replacing
if ( isset($this->fieldset[$modelKey]) && in_array($fieldKey, $this->fieldset[$modelKey]['validates']) ) { $divOptions = $this->addClass($divOptions, 'required'); }with
if (isset($options['required'])) { if ($options['required'] === true) { $divOptions = $this->addClass($divOptions, 'required'); } elseif ($options['required'] === false) { // do not add class 'required' } } elseif ( isset($this->fieldset[$modelKey]) && in_array($fieldKey, $this->fieldset[$modelKey]['validates']) ) { $divOptions = $this->addClass($divOptions, 'required'); }This ensures the presence of
$options['required']takes precedence before we rely on the model validation.use Joe Beeson's analogue plugin, to alias MyForm to Form:
public $helpers = array( 'Analogue.Analogue' => array( array( 'helper' => 'MyForm', 'rename' => 'Form' ) ) )then, specifying the form input as required looks like:
$this->Form->Input( 'SomeModel.SomeField', array('required' => true) )
Is there some other better approach than this, or potential issues with this solution?
$this->Form->input('foo', array('div'=>array('class'=>'required')));but really why go to this trouble when it's in cake out of the box? What are you trying to achieve. - Ross