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.

Related Posts