2

I have a custom phtml file that contains a copy of the customer registration form in my Magento 2.1 site. Now in this form I have

<input type="hidden" name="group_id" id="group_id" value="3" />

I also created a file located in app/code/Magento/Customer/Model called CustomerExtractor.php and the contents of the file is below but now when I creat a test customer using the new registration for the user is not assigned to the group_id that is set in the form?

<?php
   /**
     *
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
      namespace Magento\Customer\Model;
      use Magento\Customer\Api\CustomerMetadataInterface;
      use Magento\Customer\Api\Data\CustomerInterface;
      use Magento\Customer\Api\GroupManagementInterface;
      use Magento\Framework\App\RequestInterface;
      class CustomerExtractor
      {
       /**
         * @var \Magento\Customer\Model\Metadata\FormFactory
         */
        protected $formFactory;
        /**
          * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
          */
        protected $customerFactory;
       /**
         * @var \Magento\Store\Model\StoreManagerInterface
         */
        protected $storeManager;
        /**
          * @var GroupManagementInterface
          */
        protected $customerGroupManagement;
        /**
          * @var \Magento\Framework\Api\DataObjectHelper
          */
        protected $dataObjectHelper;
        /**
          * @param Metadata\FormFactory $formFactory
          * @param \Magento\Customer\Api\Data\CustomerInterfaceFactory 
        $customerFactory
          * @param \Magento\Store\Model\StoreManagerInterface $storeManager
          * @param GroupManagementInterface $customerGroupManagement
          * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
        */
        public function __construct(
    \Magento\Customer\Model\Metadata\FormFactory $formFactory,
    \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    GroupManagementInterface $customerGroupManagement,
    \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
) {
    $this->formFactory = $formFactory;
    $this->customerFactory = $customerFactory;
    $this->storeManager = $storeManager;
    $this->customerGroupManagement = $customerGroupManagement;
    $this->dataObjectHelper = $dataObjectHelper;
}
/**
 * @param string $formCode
 * @param RequestInterface $request
 * @param array $attributeValues
 * @return CustomerInterface
 */
public function extract(
    $formCode,
    RequestInterface $request,
    array $attributeValues = []
) {
    $customerForm = $this->formFactory->create(
        CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
        $formCode,
        $attributeValues
    );
    $customerData = $customerForm->extractData($request);
    $customerData = $customerForm->compactData($customerData);
    $allowedAttributes = $customerForm->getAllowedAttributes();
    $isGroupIdAllow = isset($allowedAttributes['group_id']);
    $customerDataObject = $this->customerFactory->create();
    $this->dataObjectHelper->populateWithArray(
        $customerDataObject,
        $customerData,
        \Magento\Customer\Api\Data\CustomerInterface::class
    );
    $store = $this->storeManager->getStore();
    if (!$isGroupIdAllow || ($isGroupIdAllow &&(is_null($customerDataObject->getGroupId()))) ) {
        $customerDataObject->setGroupId(
            $this->customerGroupManagement->getDefaultGroup($store->getId())->getId()
        );
    }
    $customerDataObject->setWebsiteId($store->getWebsiteId());
    $customerDataObject->setStoreId($store->getId());
    return $customerDataObject;
}

}

  • Hey, is issue fixed? – Konrad Siamro Oct 12 '17 at 13:07
  • No I am still not able to figure out how to get this issue resolved. I even set a bounty to try to get more people into this thread but that did not work. – Jayreis Oct 12 '17 at 14:31
  • @user1739740 Do you want to have all registered customers in customer_group_id=3? if so, this can be easily accomplished by an observer.' – Yogesh Agarwal Oct 13 '17 at 8:03
4

This is not the only issue in Magento Custom registration form , also the issue exists in Default registration form.If we passing any group_id from default registration form then that customer group does not set for that customer it always takes store default group_id For in case of default registration form Issue in [Magento\Customer\Model\CustomerExtractor] c(https://github.com/magento/magento2/blob/develop/app/code/Magento/Customer/Model/CustomerExtractor.php#L92) class. Even , i enabled attribute group_id in customer registration form using

INSERT INTOcustomer_form_attribute(form_code,attribute_id) VALUES ('customer_account_creat', '10');

But still is does not work bcoz...

Logic issue in if ($isGroupIdEmpty) {

Means, instead of enabling group_id for customer registration form and sending this field value from , Magento forcefully set Customer group as the default group .

That is the problem.

Solution:

Solution is that, we need to modify condition

  1. don't execute $customerDataObject->setGroupId( when _group_id_ is enable for registration form

  2. execute $customerDataObject->setGroupId( when _group_id_ is not enable for registration form

  3. execute $customerDataObject->setGroupId( when _group_id_ is enable for registration form * but group id **does not selected from form

So. my suggestion change if ($isGroupIdEmpty) {

to

if (!$isGroupIdAllow || ($isGroupIdAllow &&(is_null($customerDataObject->getGroupId()))) ) { $customerDataObject->setGroupId( $this->customerGroupManagement->getDefaultGroup($store->getId())->getId() ); }

Also for use developer perspective change variable name $isGroupIdEmpty

to

isGroupIdAllow

  • thanks for the comments. So in which file and what path to the file and I changing the if ($isGroupIdEmpty) { line in? – Jayreis Sep 28 '17 at 17:57
  • So I created a the directrory /Magento/Customer/Model in the app/code directory. Now I created the file CustomerExtractor.php and put the contents in there from the github. and changed by !$isGroupIdAllow section but when I create a customer from my custom for where I have a hidden field setting the group_id it still does not work the customer is created by assigned to the default group ? – Jayreis Sep 28 '17 at 19:05
  • I am still looking for guidance on this. – Jayreis Oct 5 '17 at 20:44
  • 1
    i will do at today – Amit Bera Oct 6 '17 at 2:42
0

Im not sure exactly that you need.
This solution will add customer group select to registration form.
1. In template form/register.phtml in fieldset add :

    <div class="field customer-groups required">
        <label for="customer-group" class="label"><span><?php echo __('Customer Group') ?></span></label>
        <select name="customer_group" id="customer-group" data-validate="{required:true}">
            <option value=""><?php echo __('Customer Group') ?></option>
            <?php foreach ($block->getCustomerGroups() as $customerGroup) : ?>
                <option
                    value="<?php echo $customerGroup->getId(); ?>"
                    <?php echo ($customerGroup->getId()==$block->getFormData()->getCustomerGroup())? 'selected' : ""; ?>><?php echo $customerGroup->getCode(); ?></option>
            <?php endforeach ?>
        </select>
    </div>

In block add function getCustomerGroups :

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Directory\Helper\Data $directoryHelper,
    \Magento\Framework\Json\EncoderInterface $jsonEncoder,
    \Magento\Framework\App\Cache\Type\Config $configCacheType,
    \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory,
    \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
    \Magento\Framework\Module\Manager $moduleManager,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Customer\Model\Url $customerUrl,
    \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroupCollection,
    $data = []
)
{
    $this->customerGroupCollection = $customerGroupCollection;
    parent::__construct($context, $directoryHelper, $jsonEncoder, $configCacheType, $regionCollectionFactory,
        $countryCollectionFactory, $moduleManager, $customerSession, $customerUrl, $data);
}

/**
 * @return array
 */
public function getCustomerGroups()
{
    $result = [];
    $array = $this->customerGroupCollection->toOptionArray();
    foreach ($array as $item) {
        if($item['value'] == 0) {
            continue;
        }
        $result[] = $this->createGroupObject($item);
    }

    return $result;
}

/**
 * @param array $item
 * @return \Magento\Framework\DataObject
 */
private function createGroupObject(array $item)
{
    $object = new \Magento\Framework\DataObject();
    $object->setData('id', $item['value']);
    $object->setData('code', $item['label']);

    return $object;
}
  • Konrad what is the file path and name of file I would add the "In block function getCustomerGroups ?? – Jayreis Oct 13 '17 at 13:22
  • Konrad what is the file path and name of file I would add the "In block function getCustomerGroups ?? If I add the code to the CustomerData.php file located in /vendor/magento/module-customer/Block I get a 500 error – Jayreis Oct 13 '17 at 13:31
  • It should be done in block used by template form/register.phtml. The best way - create new module and rewrite form/register.phtml and block Magento\Customer\Block\Form\Register - here you should add function getCustomerGroups. – Konrad Siamro Oct 18 '17 at 10:33

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.