0
votes

in CakePhp 2.x I was able to extend a core helper with my own class and use it in view files.

In CakePhp 3.8 I want to extends FormHelper, for example to change some default properties. I've tried this:

class MyFormHelper extends FormHelper
{
  public function control($fieldName, array $options = [])
  {
    $options += [
          'label' => false,
          'class' => 'form-control'
    ];

    return parent::control($fieldName, $options);
  }
}

and my options are correctly taken but many other original behavior does not works anymore. For example CakePhp doesn't recognize the fields type (boolean type fields are shown as text inputs and not checkboxes) and doesn't insert the value of field inside a edit form.

Do you know why?

I've also tried calling parent method in this way without success:

[...]
// return parent::control($fieldName, $options);
return $this->__xformCallParent(array($this, 'parent::control'), func_get_args());
[...]
private function __xformCallParent($call, $args)
{
    if (PHP_VERSION >= 5.3 && is_array($call)) {
        $call = $call[1];
    }
    return call_user_func_array($call, $args);
}
1
This is how extension works, though. Should do the trick. See also github.com/FriendsOfCake/bootstrap-ui and other plugins of the awesome list on how they do it. - mark

1 Answers

1
votes

I've found the answer! Just insert your custom FormHelper inside src/View/Helper/FormHelper.php file and declare it with this code:

namespace App\View\Helper;
use Cake\View\Helper\FormHelper as Helper;

class FormHelper extends Helper
{
    public function control($fieldName, array $options = [])
    {
        $options += [
            'label' => false,
            'class' => 'form-control'
        ];

        [...]

        return parent::control($fieldName, $options);
    }
}

replacing your code inside the method. I've just removed the label by default and add a custom class to input elements.