0

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;
    }
3

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;
  }       
}
  • @ Konstantin thanks for your answer. Now I am able to store custom fields value in database in form. But those field values are not displaying in customer group grid.How to display custom field value in Customer Group Grid in admin. – Emipro Technologies Pvt. Ltd. Oct 6 '18 at 4:52
1

I used this code in the Plugin part to save.

public function beforeExecute(\Magento\Customer\Controller\Adminhtml\Group\Save $save)
{
    $id = $save->getRequest()->getParam('id');
    if($id!="") {
        $shipping = $save->getRequest()->getParam('shipping_method');
        if ($shipping != "") {
            $shipping = implode(', ', $shipping);
            $shipping = rtrim($shipping, ', ');
        }
        $shipping = preg_replace('/\s+/', '', $shipping);

        $db = $this->resourceConnection->getConnection();
        $result = $db->query('SELECT * FROM customer_group WHERE customer_group_id=' . $id);
        if($result->fetch()) {
            $update = $db->query('UPDATE customer_group SET shipping_method="'.$shipping.'" WHERE customer_group_id=' . $id);
        }
    }
}
  • 3
    Raw SQL??? This is far away from best practice. – Matthias Kleine May 18 '17 at 15:19
  • @oscar How it can work while creating a new customer group? you are updating already existing record? – Sarvagya Oct 4 '17 at 7:06
  • @sarvagya It's supposed to work with a new group! – Oscar Azpeitia Oct 10 '17 at 14:53

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.