2

I am developing a plugin to add custom column to entries table for which I am using EVENT_REGISTER_TABLE_ATTRIBUTES and EVENT_SET_TABLE_ATTRIBUTE_HTML and code example is:

Event::on(
    Element::class, 
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES, 
    function(craft\events\RegisterElementTableAttributesEvent $e) {
        return array(
            'foo' => "Foo",
            'bar' => "Bar",
        );
});
Event::on(
    Entry::class, 
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML, 
    function(craft\events\SetElementTableAttributeHtmlEvent $e) {
        if ($e->attribute === 'foo') {
            return 'bar';
        }
});

Unfortunately, its not working. Could anyone please help what I am mistaking here.

3

You don't need to return anything in an event. As you can see how the Event is triggert

Event::trigger(static::class, self::EVENT_REGISTER_TABLE_ATTRIBUTES, $event);

It does not expect any return value. So you don't add something by returning an array. Instead you'll have to manipulate the properties of your event

When you take a look at your RegisterElementTableAttributesEvent it contains the following property

/**
 * @var array List of registered table attributes for the element type.
 */
public $tableAttributes = [];

In order to add attributes you have to do

Event::on(
    Element::class,
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function(craft\events\RegisterElementTableAttributesEvent $e) {
        $e->tableAttributes['foo'] = [
            'label' => "Foo"
        ];
});

It's the same for your SetElementTableAttributeHtmlEvent. It has the properties

// Properties
// =========================================================================

/**
 * @var array|null The table attribute associated with this event.
 */
public $attribute;

/**
 * @var string|null The HTML to represent a table attribute.
 */
public $html;

You can var_dump the $event to see the current properties to get to know which structure you have to include. Usually you would do

Event::on(
    Entry::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function(craft\events\SetElementTableAttributeHtmlEvent $e) {
        if($e->attribute === 'foo'){
            $e->html = 'FOOOOO';
        }
    }
);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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