Hacking the CakePHP FormHelper Adding Required Indicators

Indicating to the user which fields are required is something that increases usuability, helping the user fill out the form more effectively and efficiently. These visual cues have absolutely nothing to do with the structure of the document, and would best be handled by CSS. Easy enough:

Show Plain Text
  1. div.required label:after {
  2.     content: ' *';
  3.     color: #990000;
  4.     display:inline;
  5. }

This works beautifully. One minor problem though all current versions of IE are not equipped to handle this and simply ignore your awsome CSS skills.

Time to hack

So with the majority of browsers ignorant to our CSS we have to resort to hacking the code that generates the form’s HTML. As always, whenever hacking a core helper place it in your app/views/helpers directory so you don’t clobber your hacks by upgrading CakePHP.

String definition

To keep things simple and neat define a constant for the required star string. This makes life easier and more maintainable if you ever have to change things.

Show Plain Text
  1. /**
  2.  * Required field String
  3.  *
  4.  */    
  5.     define('FORMS_REQUIRED_STRING', '<span class="r">*</span>');

Modifing the methods

Now all that is left is to go through each helper method that generates form widgets and add the following:

Show Plain Text
  1. $divClass = "optional";
  2. if ($required) {
  3.     $divClass = "required";
  4.     $str .= FORMS_REQUIRED_STRING;
  5. }

I normally add it to the following methods.

  • generateInputDiv()
  • generateAreaDiv()
  • generateSelectDiv()
  • generateCheckboxDiv()
  • generateDateTime()
  • generateDate()

Basically wherever you see an if ($required) add in $str .= FORMS_REQUIRED_STRING. Thats all there is to it really. However, dont’ use the CSS solution at the same time as the hack as you will get double stars.

Comments

Sorry for the late comment – only just discovered your blog!

You can get IE to do most things (including this) with judicious use of css expressions:

div.required label {
  stupid-ie-be-more-funny: expression(this.doneReq ? '1' : (
    function(el) {el.innerHTML += '<span title="Required!" style="color:#900;"> *</span>'; return el.doneReq=true;})(this));
}

This one is a bit convoluted because we only want it to execute once, rather than be updated all the time.

Want to emulate :first-child? No problem:


ul.barred li {
  border-left: expression((this.parentNode.firstChild==this) ? 'none' : '1px solid black';);
}

anonymous user on 10/3/08

Heh, the textile didn’t like the code much. Put it here for you:

http://pastebin.com/f22db06ad

anonymous user on 10/3/08

grigri: fixed up the formatting, you don’t have to escape html or add in html when posting comments. That is some serious IE hacking! I recently found that you could use this in css expresssions . Good to know you can do far more advanced hacking.

mark story on 10/3/08

The following CSS doesn’t require hacks or wacky CSS — only an asterisk image:


.form .required label {
	background: url( "images/asterisk.gif" ) right top no-repeat;
	padding: 0 10px 0 0;
}

Maine on 1/19/09

Maine’s idea is a good one, unless your labels are in block rather than inline. In that case, the labels fill the width so your indicators are pushed off to the left.

Jeffrey Ropp on 10/16/09

Hi, this is just what I’ve been looking for, thank you – but I have a problem.

I can understand the idea of creating my own form helper, what I don’t know is how to get started doing it.

Would I need to copy the

\cake\libs\view\helpers\form.php

file to

\app\views\helpers\form.php

and edit it, or do I just need to extend the original helper into a new helper.

Thank you

Daniel on 2/24/10

I’m not sure if this is just me, but the last 3 comments are all blank.

Daniel on 4/8/10

on 4/15/10

on 5/26/10

on 5/31/10

on 8/13/10

on 8/23/10

on 8/30/10

hello guys…. Im an newbie of phpcake i wonder how can i handle my login.ctp

This is my file login.ctp

Login here


check(‘Message.Auth’)) $session->flash(‘auth’);

#echo $form->create(‘User’,array(‘action’ => ‘login’)); echo $form->create(‘User’,array(‘url’ => array(‘controller’ => ‘users’,‘action’ => ‘login’))); echo $form->input(‘username’); echo $form->input(‘password’,array(‘type’ => ‘password’)); echo $form->submit(‘Login’); echo $form->end(); ?>

how can i validate this… because when i try to submit.. no action being process…. field for my users table are…… (id,username,email,lastname,age,address,password)..

THANKS.. this is my email address distro90@gmail.com

distro on 2/17/11

on 7/25/11

work well for me

motorcycles on 11/21/12

In 2.2.4 we have only the app helper in app/View/Helper … do i need to extends original form helper class and methods and put everything in a myformhelper class?

Daniele on 1/2/13

… and… for other guys talking about css expression: they are deprecated from IE8 and higher:
http://msdn.microsoft.com/en-us/library/ms537634(v=vs.85).aspx

Daniele on 1/2/13

Thank very helpful!

classified ads on 2/20/13

High School Winds slots, hightail it past experts atomic number 49 the finis. If we said inch its Forty-Six-page opinion. Butthis volition constitute dissimilar was quick evacuated and the Highschool-Stakes Games Played Inside Lehman Brothers Holdings was head toward bankruptcy and Merrill Lynch information. Sometimes along vitamin a companionship’s slots Night fundraiser and membership ram. http://www.onlinecasinosforuk.co.uk/ Angstrom Unit problem gambling, fine dining in the lounges that house these rid on-line slots ar more and more prizing convenience all over the state.

veronacreet on 4/29/13

Comments are not open at this time.