Редактировать отображаемые группы пользователей в выпадающем меню

#php #magento

#php #magento

Вопрос:

Мне нужно предоставить моему клиенту возможность выбирать свою группу пользователей. Я использовал скрипт, найденный здесь, в StackOverflow (если кому-то нужна ссылка, вот она https://magento.stackexchange.com/questions/239067/magento-2-customer-registration-with-customer-group/239071#239071 ): Код, который я использовал, является:

 <?php
$blockObj= $block->getLayout()->createBlock('NanoCommissionAgentsBlockCustomerGroups');
$groups = $blockObj->getCustomerGroup();
?>
<div class="field group_id required">
    <label for="group_id" class="label"><span><?php /* @escapeNotVerified */ echo __('I buy as:') ?></span></label>
    <div class="control">
        <select name="group_id">
            <?php foreach ($groups as $key => $data) { ?>
            <option value="<?php echo $data['value'] ?>"><?php echo $data['label'] ?></option>
            <?php } ?>
        </select>
    </div>
</div>
  

CustomerGroup.php

 <?php

namespace NanoCommissionAgentsBlock;

use MagentoFrameworkViewElementTemplate;
use MagentoCustomerModelResourceModelGroupCollection as CustomerGroup;

Class CustomerGroups extends Template {
    public $_customerGroup;
    public function __construct(
            CustomerGroup $customerGroup
    ) {
        $this->_customerGroup = $customerGroup;
    }

    public function getCustomerGroup() {
        $groups = $this->_customerGroup->toOptionArray();
        return $groups;
    }
}
  

SaveCustomerGroupId.php

 <?php

namespace NanoCommissionAgentsObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoCustomerApiCustomerRepositoryInterface;
use MagentoFrameworkMessageManagerInterface;

Class SaveCustomerGroupId implements ObserverInterface {
    public $_customerRepositoryInterface;
    public $_messageManager;
    public function __construct(
            CustomerRepositoryInterface $customerRepositoryInterface,
            ManagerInterface $messageManager
    ) {
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
        $this->_messageManager = $messageManager;
    }

    public function execute(MagentoFrameworkEventObserver $observer) {
       $accountController = $observer->getAccountController();
       $request = $accountController->getRequest();
       $group_id = $request->getParam('group_id');

       try {
           $customerId = $observer->getCustomer()->getId();
           $customer = $this->_customerRepositoryInterface->getById($customerId);
           $customer->setGroupId($group_id);
           $this->_customerRepositoryInterface->save($customer);

       } catch (Exception $e){
           $this->_messageManager->addErrorMessage(__('Something went wrong! Please try again.'));
       }
    }
}
  

И это отлично работает, за исключением того, что оно, очевидно, показывает также группы пользователей «НЕ ВОШЕДШИХ В систему». Мне нужно, чтобы он просто отображал группы пользователей с идентификаторами 1 (Клиент) и 6 (корпоративный), а не ту, идентификатор которой равен 0 (НЕ АВТОРИЗОВАН).

Ответ №1:

Вы можете обновить CustomerGroup.php и выполните следующее:

  • Создайте массив идентификаторов для удаления
  • Цикл по группам
  • Выполните array_search для исключенных групп
  • Удалите (используя unset()) любые идентификаторы, которые соответствуют
 namespace NanoCommissionAgentsBlock;

use MagentoFrameworkViewElementTemplate;
use MagentoCustomerModelResourceModelGroupCollection as CustomerGroup;

Class CustomerGroups extends Template {
    public $_customerGroup;
    public function __construct(
            CustomerGroup $customerGroup
    ) {
        $this->_customerGroup = $customerGroup;
    }

    public function getCustomerGroup() {
        $groups = $this->_customerGroup->toOptionArray();

        // Add group id's to this array you don't want to display in dropdown
        $excludeGroups = [0];

        foreach ($groups as $group) {
            // Check if the group is equal to any groups you want to exclude
            $groupKeyToRemove = array_search($group['value'], $excludeGroups);

            // remove the group from the array
            unset($groups[$groupKeyToRemove]);
        }

        // return the groups with only the values you want
        return $groups;
    }
}
  

Комментарии:

1. Решена проблема с этим кодом. Большое вам спасибо.