How to create an input field without a label

Published on and tagged with cakephp  helper  tip

If you use the form helper from CakePHP 1.2 to generate an input field, it automatically creates a label for the input field. So this snippet:

echo $form->input('Project/name');

will generate the following HTML code:

<div class="input">
    <label for="ProjectName">Name</label>
    <input name="data[Project][name]" type="text" value="" id="ProjectName" />
</div>

But sometimes you don’t want a label. How can you accomplish that? My first two attempts failed, the label “Name” was still shown:

// first attempt
echo $form->input('Project/name', array('label' => ''));
// second attempt
echo $form->input('Project/name', array('label' => null));

With the third attempt I was then successful, and the label disappeared:

echo $form->input('Project/name', array('label' => false));

In retrospect the solution is logical, but sometimes you don’t see the obvious solution ;-)

33 comments baked

  • theman

    I was wondering if you knew how to position a label for a checkbox? It always seems to appear to the right of a checkbox, can you make it appear to the left?

  • cakebaker

    @theman: Yes, that’s possible, CSS is your friend. Something like

    label {
    float: left;
    }
    

    or

    input[type=checkbox] {
    float: right;
    }
    

    should do the trick.

  • cdomigan

    Is it possible to set “label”=>false to be the default behaviour for all form elements?

    Chris

  • KesheR

    I had to do something similar to disable the “div” it added.

  • walkerhamilton

    Oh thank god.

    I was having some problems with that and tried the first two you did but it never occured to me to try the last one.

  • Derick

    @cdomigan: what i usually do with such things in 1.1.x.x is to create a helper which extends the HtmlHelper (or FormHelper in your case) then copy the function which you wish to be “different” from the original helper file to your newly created one. seems like a better way for me though it might not be the best way (i don’t know).

  • Miroslav Bazitov

    Hi Derick

    I have issue with submit method in the html helper – the output was “input” but I prefer “button”.

    I thought to make new helper witch extends HtmlHelper, but I wondered then if I need to use the newly created helper or the HtmlHelper.

    I want to modify the submit method of the HtmlHelper, but without touching anything in the /cake dir. I prefer to stick to HtmlHelper, because it’s load automaticaly.

    Thanks in advance
    Miro

  • Derick

    @miro: i guess it is sort of a preference thing.. like i’ve set labels on the checkboxes in my extended HtmlHelper etc. so I always use the extended version instead of the HtmlHelper.. this way you don’t need to edit the core files..

  • Sam

    Dear god thank you so much, i had tried loads of other options

    sometimes i think the name FormHelper is very misleading, it’s creating more work than the typing it saves!

  • cakebaker

    @Sam: I am glad to hear this article helped you :)

    Yeah, sometimes using the helper is more work than the traditional way and in some cases I even forgo to use the helper.

  • gad

    thx for this quick solution.

  • cakebaker

    @gad: Good to hear this article was helpful for you :)

  • Richard Brown

    Thank you! I was looking all over for this. It was driving me nuts. I wish the documentation for 1.2 was a bit more instructive.

  • cakebaker

    @Richard: I’m glad this article was helpful for you!

  • Neil

    Thanks you! this was helpful but is there also a way to change the lable text?

    for example I tried this with no success:
    echo $form->input(‘author’, array(‘type’ => ‘text’, ‘lable’ => ‘Name of the Author:’));

  • cakebaker

    @Neil: Yes, it is possible. Simply change “lable” to “label” in your example, and it should work ;-)

  • Gayatri

    Thank you!!!
    This solution may look simple but, it can get you stuck for quite some time…it took me a day until I found this blog!

    Thank you once again :)

  • cakebaker

    @Gayatri: I am glad this article helped you :)

  • Jon

    Thanks for this, your site here has been a huge use to me in the last week. I’m just learning and starting off on 1.2… the documentation is weak.
    they say $form->input has 2 arguments, the second being $options, but they don’t tell you what options you can use…

    do you know if theres a way to override cakes method of splitting up field names at the case? I.e. I have a set of field names DLCI[1-7]. When the $form->input helper does its thing, it makes the label D L C I1 and so on…

  • cakebaker

    @Jon: Thanks for your comment!

    I think you could write your own helper which extends the FormHelper, and then override the label() method. But it is a bit an ugly solution. It is probably easier if you provide an explicit value for the label with:

    $form->input('MyModel.DLCI1', array('label' => 'DLCI1'));
    

    Hope that helps!

  • Jon

    @cakebaker: thanks for the reply. I came to the same conclusion as the one you suggested… unfortunately.

    Is there a suggested naming conventions for fields that have acronyms (the system uses a lot of techish fields (IP, DLCI, TCP, etc) but I’d like to not have to override all the names. perhaps theres a built in alias function in cake?

    I’m trying to get away from building static views. I’d like to be able to build the form according to the db schema, possibly with a few alterations (order of the fields). On that note, do you have any ideas of a configuration model to have a bunch of user configuration tables to control things like :
    – drop downs (what fields to use them on, what options to allow, and the order of the options)
    – fields to include in reports, forms, tables, etc. (what fields to omit in forms, or reports, but still include in a different table)

    if this doesn’t make sense, it may be a result of me having to write it again since i didn’t include my name and email in the original post (p.s. you should have some sorta post back method).

    i built a web app that i’m now trying to migrate into the cake framework but a combo of me being a bit of a noob (only a year of self taught programming) and the spotty documentation is making it tougher than i first anticipated. any help you can offer would be swell.

  • cakebaker

    @Jon: I’m not aware of such an alias function. Maybe it is worth to open an enhancement ticket for Inflector::underscore() to make it more sophisticated. But I’m not sure whether this will get implemented, so I think it is probably easier to write a custom helper, which internally calls the FormHelper in the way shown in my previous comment.

    Regarding configuration model, I would probably create a model for each configuration table, and then have a special configurations controller. But at first I would ask myself whether this additional complexity is really necessary and worth the effort.

    What do you mean with “post back method”?

  • Jon

    @cakebaker: Thanks for your suggestions.

    re: post back – I wrote out a whole comment, about as long as the last one, but when I submitted, I forgot the mand. fields. I got a message saying to fill the mand. fields, but the message just stayed there (it was the only thing on the screen) and I wasn’t redirected back to my post. I clicked back button and my writing was gone and I had to re-write.

    Thanks again for your responses and your blog. It’s an excellent resource for someone like me who’s beginning what seems to be a long journey in php programming, and the cake framework.

  • cakebaker

    @Jon: Thanks for your explanation, now it is clear what you meant. I hope I can fix it.

    Anyway, good luck on your journey :)

  • Krishna

    Thanks for your suggestion. I would appreciate it if you could give a clue about this.
    I have been trying to validate form using cakephp. Basically in the model i have validation code like this:

    var $validate = array(
        	'username'=>array(
        		'rule'=>'alphaNumeric',
    			'required'=>true,
        		'message'=>'Please enter the username',
        	)
    	);

    and in the view i have this:
    <h2>Add User</h2>
    <?php echo $form->create('User', array('url' => '/users/add'));?>
    <?php echo $form->input('username', array('size' => '20','label'=>'User Name:'));?>
    <?php
    echo '<div><input type="submit" value="Submit" /> or '.$html->link('Cancel', array('action' => 'index')).'</div>';
    echo $form->end();
    ?>
    <code>
    <h2>Add User</h2>
    <?php echo $form->create('User', array('url' => '/users/add'));?>
    <?php echo $form->input('username', array('size' => '20','label'=>'User Name:'));?>
    <?php
    echo '<div><input type="submit" value="Submit" /> or '.$html->link('Cancel', array('action' => 'index')).'</div>';
    echo $form->end();
    ?>

    When I hit submit with empty usename i get the error message ‘Please enter the username’ but it is always black. I was trying to make it red, but could not succeed. I noticed the problem was with class=’required’ as seen in the view source:
    <form method="post" action="/AuthUsers/users/add">
    <fieldset style="display:none;">
    <input type="hidden" name="_method" value="POST" />
    </fieldset>
    <div class="input text required error">
    <label for="UserUsername">User Name:</label>
    <input name="data[User][username]" type="text" size="20" maxlength="20" value="" id="UserUsername" class="form-error" />
    <div class="error-message">Please enter the username</div>
    </div>
    <div>
    <input type="submit" value="Submit" /> or <a href="/AuthUsers/users">Cancel</a>
    </div>
    </form>

    Anny clue as to how i can have the error message displayed in red color but the label in black color?
    Krishna

  • cakebaker

    @Krishna: Hm, what did you try to make it red? Did you try it in the way shown below?

    .error-message {color: red;}
    
  • Axel

    easy, thank you!

  • cakebaker

    @Axel: You are welcome :)

  • faten

    my problem as Axel but i want to know if there any other way to display validate message from model in red without put the error message as Axel’s did

    User Name:

    Please enter the username

  • faten

    Sorry, i was pointing to Krishna problem

  • cakebaker

    @faten: I’m not sure I understand you correctly, but have a look at the error() method of the FormHelper. By using this helper method you can display the error message anywhere you want.

    I hope this answers your question. If not, please post some code, for example a snippet of the html you want to create.

  • Pedro Valentim

    I followed exactly the same steps except for the last and right option… thanks !

  • Pedro Valentim

    I followed exactly the same steps except for the last and right option… thanks !

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License