Search code examples
cakephpconventions

CakePHP label convention


When using $this->Form->input('fieldname'), CakePHP creates a label element that, by convention, uses the fieldname. I know I can specify another string to use for the label as an argument to the input method, but is there any way I can specify the label name in the model, so I don't have to repeat the label name in multiple ctp files (e.g. so I only have to change it in one place)?


Solution

  • So I created this and made a quick test which worked, however, can't guarantee it's bug free:

    <?php
    App::uses('FormHelper', 'View/Helper');
    class MyFormHelper extends FormHelper {
    
        public function label($fieldName = null, $text = null, $options = array()) {
            if ($text === null) {
                $entity = $this->entity();
                $field = array_pop($entity);
                $model = $this->model();
                $object = $this->_models[$model];
                if (isset($object->labels[$field])) {
                    $text = $object->labels[$field];
                }
            }
            return parent::label($fieldName, $text, $options);
        }
    
    }
    

    Drop that in app/View/Helper/MyFormHelper.php

    Add it to the helper array and alias it if you want to.

    Add a public $labels array to the model with field => label-text structure. Hope it works.