Skip to content

How to add a custom column to admin user grid?

I am new to Magento and I am stuck with adding a column to a grid. I have created a new module (StoreAdmin) to assign every admin to specific store (for some reasons I have been asked to do so). I have added a new column (store_id) to the table admin_user using an UpgradeSchema class. I also have added a dropdown field in the users edit form populated with the available stores and it works (assigning the store id to the admin).

Now I am trying to add a new column to the admin users grid but it does not appear there. I wonder what I am missing. I am not even sure if I am on the right track to do it.

di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagentoUserBlockUserEditTabMain"
                type="VendorStoreAdminBlockEditTabMain"/>
    <type name="MagentoUserModelResourceModelUserCollection">
        <plugin name="add_store_id_column"
                type="VendorStoreAdminPluginAddStoreIdColumn"/>
    </type>
    <type name="MagentoUserModelUser">
        <plugin name="vendor_storeadmin_save_store_id"
                type="VendorStoreAdminPluginAdminUserSaveStoreId"/>
    </type>
</config>

AddStoreIdColumn.php:

<?php

namespace VendorStoreAdminPlugin;

use MagentoUserModelResourceModelUserCollection;

class AddStoreIdColumn
{
    /**
     * Add store_id to the grid collection
     *
     * @param Collection $collection
     * @return void
     */
    public function beforeLoad(Collection $collection)
    {
        $collection->getSelect()->columns(['store_id' => 'main_table.store_id']);
    }
}