0

I'm trying to add a new Tab in entry elements from my module using events.

Event::on(
            FieldLayout::class,
            FieldLayout::EVENT_DEFINE_NATIVE_FIELDS,
            static function(DefineFieldLayoutFieldsEvent $event) {
                /** @var FieldLayout $fieldLayout */
                $fieldLayout = $event->sender;


                $tabs = $fieldLayout->getTabs();

                $layoutElements = [
                    new TextField([
                        'label' => 'My Description',
                        'attribute' => 'description',
                        'mandatory' => true,
                        'instructions' => 'Enter a description.',
                    ])
                ];

                $newTab = new FieldLayoutTab();
                $newTab->name = 'Audit';
                $newTab->layoutId = $fieldLayout->id;
                $newTab->setLayout($fieldLayout);
                $newTab->setElements($layoutElements);

                $fieldLayout->setTabs([...$tabs, $newTab]);

            }
        );

What is the correct way to add a new tab in entry ?

1 Answer 1

1

If you want to add a tab dynamically to a field layout as it's being displayed, FieldLayout::EVENT_DEFINE_NATIVE_FIELDS is not the best event to use. This one would be appropriate if you wanted to add an additional native field that developers could add to the element's field layouts manually. Instead, use FieldLayout::EVENT_CREATE_FORM to add a FieldLayoutTab when the element form is being created. Inside a module:

// class imports
use craft\fieldlayoutelements\TextField;
use craft\models\FieldLayout;
use craft\models\FieldLayoutTab;
use yii\base\Event;

// init()
Event::on(
    FieldLayout::class,
    FieldLayout::EVENT_CREATE_FORM,
    function (CreateFieldLayoutFormEvent $e) {
        $element = $e->element;
        $e->tabs[] = new FieldLayoutTab([
            'name' => Craft::t('app', 'My custom tab'),
            'layout' => $e->sender,
            'elements' => [
                new TextField([
                    'label' => 'My Description',
                    'attribute' => 'description',
                    'instructions' => 'Enter a description.',
                ])
            ],
        ]);
    }
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.