Hacking the CakePHP FormHelper Adding Required Indicators
May 14 2008
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- div.required label:after {
- content: ' *';
- color: #990000;
- display:inline;
- }
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- /**
- * Required field String
- *
- */
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- $divClass = "optional";
- if ($required) {
- $divClass = "required";
- $str .= FORMS_REQUIRED_STRING;
- }
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.
Search
Categories
Recent Posts
- Code Completion for CakePHP in Eclipse
- CakePHP RC3 released and CakePHP 1.1 new release
- Book Review: CakePHP Application Development
- Providing Contextual Form Help with Mootools
- Creating gracefully degrading javascript and enabling progressive enhancement
- Server up and down time
- Acl Menu Component
- Github hooked up
- Auth and Acl - Automatically updating user Aros
- CakePHP Easter eggs
Comments
grigri 3 days, 7 hours ago
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:
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:grigri 3 days, 7 hours ago
Heh, the textile didn’t like the code much. Put it here for you:
http://pastebin.com/f22db06ad
mark story 2 days, 20 hours ago
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
thisin css expresssions . Good to know you can do far more advanced hacking.Have Something to say?