Forcing cake to use “dashed” HTML DOM ID’s

Why bother?

I guess just to keep CSS purists happy, we should have our DOM id’s appear as “some-field-id” rather than CakePHP’s default “SomeFieldId”.
(Also, it’s just a matter of consistency and most certainly personal preference).
There is no defined rule for this, but in overwhelming CSS examples and tutorials it is quite common to see “dashed” names rather than camel cased.

Thanks to a tip from Mark Story, we can override the default behavior by creating an app_helper.php with the following method:

public function domId($options = null, $id = 'id') {
  $view =& ClassRegistry::getObject('view');
  if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
    return $options;
  } elseif (!is_array($options) && $options !== null) {
    return $this->domId();

  $entity = $view->entity();
  $model = array_shift($entity);
  $replacement = array($model .' '. implode('-', $entity));
  $dom = $model . join('', array_map(array('Inflector', 'camelize'), $entity));	
  $dom =  preg_replace('/(?<=[^A-Z])([A-Z])/', ' $1', $replacement);
  $dom = strtolower(implode('-', Inflector::slug($dom, '-')));
  if (is_array($options) && !array_key_exists($id, $options)) {
    $options[$id] = $dom;
  } elseif ($options === null) {
    return $dom;

  return $options;	

This overrides Helper::domId() and gives us nice “model-field-name” ID’s with dashes rather than “CamelCase”.
The actual change happens in lines 13 – 16 (if you care), the rest of the method remains the same as the core.

5 thoughts on “Forcing cake to use “dashed” HTML DOM ID’s

  1. Nice but you forgot to include return $options at the end of function. Btw i don’t think all html tag id generated via calling this function, at least form’s id remain CamelCase.

  2. @Jesh

    Thanks. Fixed.

    I am not sure what you mean by form’s id remain CamelCase… for any input it should work as described. For the form you can always pass ‘id’ manually.

  3. Thanks for the great tip, this has definitely bothered me!

    Jesh is correct, FormHelper::create() doesn’t call domId. I opened a ticket for this last night, after seeing your post here.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s