Magento – M2 Save custom attribute on Customer Group form

customermagento2moduleplugin

I've created a plugin to save an attribute on customer group form. The form input is a multi select, so I added a table field (string) in the customer_group database via updateSchema.php I figured that a text field will contain comma separated values.

The field is showing fine, I then added a before plugin to the default controller. But I'm stuck right there. I don know how to save this field.
The field appears in the db.

app/code/vendor/plug/Setup/UpgradeSchema.php

namespace vendor\plug\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if (version_compare($context->getVersion(), '0.1.0', '<')) {
            $setup->getConnection()->addColumn(
                $setup->getTable('customer_group'),
                'shipping_method',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 100,
                    'nullable' => true,
                    'default' => null,
                    'unsigned' => true,
                    'comment' => 'Shipping method id'
                ]
            );
        }

        $setup->endSetup();
    }
}

app/code/vendor/plug/etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Customer\Block\Adminhtml\Group\Edit\Form">
    <plugin name="add_form_field" type="vendor\plug\Model\Plugin\Form" sortOrder="1"/>
</type>
<type name="Magento\Customer\Controller\Adminhtml\Group\Save">
    <plugin name="save_field" type="vendor\plug\Model\Plugin\Form" sortOrder="1"/>
</type>

The plugin:
app/code/vendor/plug/Model/Plugin/Form.php

namespace vendor\plug\Model\Plugin;

class Form extends \vendor\plug\Model\Source\Method
{

    public function aftersetForm(
        \Magento\Customer\Block\Adminhtml\Group\Edit\Form $forma)
    {
        $form = $forma->getForm();
        $fieldset=$form->addFieldset('base1_fieldset', ['legend' => __('Envio')]);
        $shipping = $fieldset->addField('shipping_method',
            'multiselect',
            [
                'name' => 'shipping_method',
                'label' => __('Shipping Method'),
                'title' => __('Shipping Method'),
                'class' => 'required-entry',
                'required' => true,
                'values' => $this->toOptionArray(),
            ]);
        return $form;
    } //this shows ok!

    public function beforeExecute(\Magento\Customer\Controller\Adminhtml\Group\Save $save)
    {
        echo 'Local before <br>';
        //Dont know what to do
        return $returnValue;
    }

Best Answer

Suppose you add two attributes hp_active and hp_msg:

namespace Vendor\Module\Plugin;

use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Model\GroupFactory;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\FilterBuilder;

class SavePlugin {

  protected $_filterBuilder;
  protected $_groupFactory;
  protected $_groupRepository;
  protected $_searchCriteriaBuilder;

  public function __construct(FilterBuilder $filterBuilder,GroupRepositoryInterface $groupRepository, SearchCriteriaBuilder $searchCriteriaBuilder, GroupFactory $groupFactory)
  {
    $this->_filterBuilder = $filterBuilder;
    $this->_groupRepository = $groupRepository;
    $this->_searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->_groupFactory = $groupFactory;
  }       

  public function afterexecute(\Magento\Customer\Controller\Adminhtml\Group\Save $save, $result)
  {   
    $active = $save->getRequest()->getParam('hp_active');
    $msg = $save->getRequest()->getParam('hp_msg');  
    $code = $save->getRequest()->getParam('code'); 
    if(empty($code))
      $code = 'NOT LOGGED IN';
    $_filter = [ $this->_filterBuilder->setField('customer_group_code')->setConditionType('eq')->setValue($code)->create() ];
    $customerGroups = $this->_groupRepository->getList($this->_searchCriteriaBuilder->addFilters($_filter)->create())->getItems();
    $customerGroup = array_shift($customerGroups);
    if($customerGroup){
     $group = $this->_groupFactory->create();
     $group->load($customerGroup->getId());
     $group->setCode($customerGroup->getCode());
     $group->setData('hp_active',$active);
     $group->setData('hp_msg',$msg);
     $group->save();
    }
    return $result;
  }       
}
Related Topic