Search code examples
phpzend-framework2

Zend Framework 2 Form creation via Factory. How to remove elements from fieldset depending on role?


I am creating a form using factories and specified form structure by configuring Fieldsets.

However, user with the role "admin" may edit form with all fields of an Entity and regular user "client" edit just few fields. That is why I have to delete elements from fieldsets in controller.

    $this->form->getBaseFieldset()->remove('name');
    $this->form->getBaseFieldset()->remove('title');
    $this->form->getBaseFieldset()->remove('message');`

Is it possible to specify in Fieldset or Form configuration for what role element must be added or deleted?

class ZoneDefaultElement extends Fieldset implements InputFilterProviderInterface
{

    public function __construct($name, $entity)
    {
        parent::__construct($name);

        $this->add([
            'name' => 'title',
            'type' => Element\Text::class,
            'attributes' => [
                'class' => 'form-control',
            ],
            'options' => [
                'label' => 'Title',
                'label_attributes' => [
                    'class' => 'col-sm-2 control-label required',
                ],
            ],
        ], ['priority' => 1])
     };
}

Solution

  • The second parameter of the constructor can be anything (in fact in Fieldset it is an empty array if not given), so you should be able to just pass in an array of items to use:

    class ZoneDefaultElement extends Fieldset implements InputFilterProviderInterface
    {
    
        public function __construct($name, $options)
        {
            parent::__construct($name);
    
            $entity = $options['entity'];
            $user = $options['user'];
    
            // Standard element
            $this->add([
                'name' => 'title',
                'type' => Element\Text::class,
                'attributes' => [
                    'class' => 'form-control',
                ],
                'options' => [
                    'label' => 'Title',
                    'label_attributes' => [
                        'class' => 'col-sm-2 control-label required',
                    ],
                ],
            ], ['priority' => 1]);
    
            if ($user->isAdmin()) {
                // Add "admin-only" elements
            }
        };
    }