Magento 2 – How to Create Custom Table Field in system.xml

adminmagento2system.xml

Problem

I need two-column table. First — simple text field and the second should be an image.

What was done

Now I have this. The second column should be an image.

desc

Code

class Customermap extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{


    protected $_customerGroupRenderer;

    protected $_addAfter = false;


    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Data\Form\Element\Factory $elementFactory,
        array $data = [ ]
    ) {
        parent::__construct($context, $data);
    }


    protected function _prepareToRender()
    {
        $this->addColumn('field1', [ 'label' => __('Адрес'), 'size' => 300 ]);
        $this->addColumn('customer_group', [
                'label'    => __('Customer Group'),
                'renderer' => $this->_customerGroupRenderer
            ]);


    }

}

Additional information

Saw one example with something called "GroupRender", but suppose it was wrong. In source files saw some "renders" to transfer in "addColumn" method, but can't understand how to use it.

Best Answer

Try adding this method to your Customermap class:

    protected function getCustomerGroupRenderer()
    {
        if (!$this->_customerGroupRenderer) {
            $this->_customerGroupRenderer = $this->getLayout()->createBlock(
                'Path\To\CustomerGroup\Element',
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_customerGroupRenderer;
    }

'Path\To\CustomerGroup\Element' is a class that will extend AbstractBlock that has the logic for mapping customer groups to images. Use the _toHtml method to specify your image element.

You then change the _prepareToRender method in Customermap to this:

    protected function _prepareToRender()
    {
        $this->addColumn('field1', [ 'label' => __('Адрес'), 'size' => 300 ]);
        $this->addColumn('customer_group', [
                'label'    => __('Customer Group'),
                'renderer' => $this->getCustomerGroupRenderer()
            ]);


    }