Vegas CMF Forms

Decorating form elements

Vegas CMF forms in version 1.1 are using decorating system that allows you to easily change element view without making changes in PHP code. Each Vegas\Forms\Element has new method: renderDecorated().


Example configuration

namespace Foo\Forms;

use Vegas\Forms\Element\Datepicker;

class Bar extends \Vegas\Forms\Form
{
    public function initialize()
    {
        $date = new Datepicker('date');

        // DI is set automatically when form is initialized but you can pass DI on your own
        $date->getDecorator()->setDI($this->getDI());

        // set absolute or relative path to your template directory
        $date->getDecorator()->setTemplatePath($this->view->getPartialsDir().'myCustomDir'.DIRECTORY_SEPARATOR);

        // set template name (excluding extension)
        $date->getDecorator()->setTemplateName('myCustomTemplateName');

        $this->add($date);

        // ...
    }
}


This date picker will use /yourPartialDir/myCustomDir/myCustomTemplateName.[available_extension] view. Template for this element may look as follows:

{% do assets.addCss('assets/css/custom-datepicker.css') %}
{% do assets.addJs('assets/js/custom-datepicker.js') %}
<input type="text"{% for key, attribute in attributes %} {{ key }}="{{ attribute }}"{% endfor %} value="{{ value }}" custom-tag-or-something />


For this configuration calling {{ form.get('date').renderDecorated() }} will return code above filled with all attributes like name and id.
Calling {{ form.get('date').render() }} will return simple input field same as \Phalcon\Forms\Element\Text::render() method.


Creating decorated element

You may want to create your custom form element that will also use decorators. To obtain default decorator class and renderDecorated() method use Vegas\Forms\Decorator\DecoratedTrait. Notice that implementing Vegas\Forms\Decorator\DecoratedInterface allows form to automatically inject DI to your element.

namespace Vegas\Forms\Element;

use Vegas\Forms\Decorator;

class Colorpicker extends \Phalcon\Forms\Element\Text implements Decorator\DecoratedInterface
{
    use Decorator\DecoratedTrait;

    public function __construct($name, $attributes = null)
    {
        $templatePath = implode(DIRECTORY_SEPARATOR, [dirname(__FILE__), 'Colorpicker', 'views', '']);
        $this->setDecorator(new Decorator($templatePath));
        parent::__construct($name, $attributes);
    }
}

Creating undecorated element

To unify form rendering you can also use Vegas\Forms\Decorator\UnDecoratedTrait to obtain renderDecorated() method without creating decorators at all (default render() result will be returned).

namespace Vegas\Forms\Element;

use Vegas\Forms\Decorator\UnDecoratedTrait;

class Text extends \Phalcon\Forms\Element\Text
{
    use UnDecoratedTrait;
}


In this case both render() and renderDecorated() will print default input tag for Phalcon\Forms\Element\Text.