zen of coding

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) {
    unset($options[$id]);
    return $options;
  } elseif (!is_array($options) && $options !== null) {
    $this->setEntity($options);
    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.

  • Jesh

    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.

  • @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.

  • 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.

  • @Scott Reeves

    Cool. Glad it helped… and thanks for submitting a ticket.

  • Thanks for the ticket as well :) Nice work on showing how to extend and replace some core behaviour.

%d bloggers like this: