Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cake PHP 2 custom Form->Label

I'm using the Form helper to generate a label:

$this->Form->label('Contact.name', 'Name');

Which generates the following:

<label for="ContactName">Name</label>

Is it possible to generate the following using the helper:

<label for="ContactName"><span class="mandatory">*</span> Name</label>

Whilst I can manually write the html for the above it becomes a little more difficult when I am using the input method where a label is automatically generated.

For example:

$this->Form->input('Contact.forename',array('div' =>false,
                   'label' => array(
                   text'=> 'First Name',class =>'myclass'),
                   'class' => 'input','size' => '25' ,'tabindex' => '1'));

Is this possible in cake or do I have to manually inject the html using javascript when the page loads? Which I would think is rather ugly.

like image 435
Bear Avatar asked Aug 01 '12 00:08

Bear


2 Answers

If you are using model validation for the mandatory fields then cakephp automatically applies '*' on the Label else you can use the helper as follows-

echo $this->Form->label('name', '<span class="mandatory">*</span> Name');

If you don't want the labels to generate automatically you can use "label => false" while using the helper.

echo $this->Form->input('Contact.forename',array('label' =>false));
like image 71
Sitansu Avatar answered Nov 28 '22 18:11

Sitansu


Not sure CakePHP supports that (and it would get a bit messy anyway). The simplest solution I can think of is to assign a "mandatory" class to the label via the form helper:

$this->Form->label('User.name', 'Your username', array('class'=>'mandatory'));

Which produces something like:

<label class="mandatory" for="ContactName">Name</label>

Then the rest is done purely in CSS:

label.mandatory:after {
    content: ' *';
    color: red;
    display: inline;
}

Avoids having any additional HTML.

like image 27
Ben Avatar answered Nov 28 '22 19:11

Ben