Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custome Backend Multiselect Attribute is not saving #4545

Closed
stepzerosolutions opened this issue May 18, 2016 · 8 comments
Closed

Custome Backend Multiselect Attribute is not saving #4545

stepzerosolutions opened this issue May 18, 2016 · 8 comments

Comments

@stepzerosolutions
Copy link

Steps to reproduce

  1. Create InstallData in module with following,
                $eavSetup->addAttribute(
                    \Magento\Catalog\Model\Product::ENTITY,
                    'groupcatalogavailability',
                    [
                        'type' => 'varchar',
                        'label' => 'Customer Group Visibility',
                        'input' => 'multiselect',
                        'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                        'backend' => 'Stepzerosolutions\Groupcatalogvisibility\Model\Product\Attribute\Backend\Groupcatalogvisibility',
                        'input_renderer' => 'Stepzerosolutions\Groupcatalogvisibility\Block\Adminhtml\Product\Helper\Form\Groupcatalogvisibility',
                        'required' => false,
                        'sort_order' => 9,
                        'visible' => true,
                        'group' => 'General',
                    ]
                );  
  1. Above code will generate Custom Attribute to collect Multiple Customer Groups So product can be visible base on this Group Selection
  2. Input render script
namespace Stepzerosolutions\Groupcatalogvisibility\Block\Adminhtml\Product\Helper\Form;

use Magento\Customer\Model\ResourceModel\Group\Collection;
use Magento\Framework\AuthorizationInterface;

/**
 * Product form category field helper
 */
class Groupcatalogvisibility extends \Magento\Framework\Data\Form\Element\Multiselect
{
    /**
     * @var \Magento\Framework\View\LayoutInterface
     */
    protected $_layout;

    /**
     * Backend data
     *
     * @var \Magento\Backend\Helper\Data
     */
    protected $_backendData;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $_collectionFactory;

    /**
     * @var \Magento\Framework\Json\EncoderInterface
     */
    protected $_jsonEncoder;

    /**
     * @var AuthorizationInterface
     */
    protected $authorization;
    protected $_logger;
    /**
     * @param \Magento\Framework\Data\Form\Element\Factory $factoryElement
     * @param \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection
     * @param \Magento\Framework\Escaper $escaper
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collectionFactory
     * @param \Magento\Backend\Helper\Data $backendData
     * @param \Magento\Framework\View\LayoutInterface $layout
     * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
     * @param AuthorizationInterface $authorization
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\Data\Form\Element\Factory $factoryElement,
        \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection,
        \Magento\Framework\Escaper $escaper,
        \Magento\Customer\Model\ResourceModel\Group\CollectionFactory $collectionFactory,
        \Magento\Backend\Helper\Data $backendData,
        \Magento\Framework\View\LayoutInterface $layout,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        AuthorizationInterface $authorization,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
        $this->_jsonEncoder = $jsonEncoder;
        $this->_collectionFactory = $collectionFactory;
        $this->_backendData = $backendData;
        $this->authorization = $authorization;
        parent::__construct($factoryElement, $factoryCollection, $escaper, $data);
        $this->_layout = $layout;
        if (!$this->isAllowed()) {
            $this->setType('hidden');
            $this->addClass('hidden');
        }
        $this->_logger = $logger;
    }

    /**
     * Get values for select
     *
     * @return array
     */
    public function getValues()
    {
        $options = [];
        $values = $this->getValue();//die(var_dump($values));
        if (!is_array($values) && $values!=NULL ) {
            $values = explode(',', $values);
        }

        $collection = $this->_getGroupsCollection();
        if( $values==NULL ){
            $collection->addFieldToFilter( 'customer_group_id', array('null' => true ) );
        } else { 
            $collection->addFieldToFilter( 'customer_group_id', array('in' => $values ) );
        }
        foreach ($collection as $group) {
            $options[] = ['label' => $group->getCustomerGroupCode(), 'value' => $group->getCustomerGroupId()];
        }
        return $options;
    }

    /**
     * Get categories collection
     *
     * @return Collection
     */
    protected function _getGroupsCollection()
    {
        return $this->_collectionFactory->create();
    }

    /**
     * Attach category suggest widget initialization
     *
     * @return string
     */
    public function getAfterElementHtml()
    {
        if (!$this->isAllowed()) {
            return '';
        }
        $htmlId = $this->getHtmlId();
        $suggestPlaceholder = __('start typing customer group name');
        $selectorOptions = $this->_jsonEncoder->encode( $this->_getSelectorOptions() );
        $return = <<<HTML
    <input id="{$htmlId}-suggest" placeholder="$suggestPlaceholder" />
    <script>
        require(["jquery", "mage/mage"], function($){
            $('#{$htmlId}-suggest').mage('treeSuggest', {$selectorOptions});
        });
    </script>
HTML;
        return $return;
    }

    /**
     * Get selector options
     *
     * @return array
     */
    protected function _getSelectorOptions()
    {
        return [
            'source' => $this->_backendData->getUrl('groupcatalogvisibility/groups/suggestGroup'),
            'valueField' => '#' . $this->getHtmlId(),
            'className' => 'groupcatalogavailability-select',
            'multiselect' => true,
            'showAll' => true
        ];
    }

    /**
     * Whether permission is granted
     *
     * @return bool
     */
    protected function isAllowed()
    {
        return $this->authorization->isAllowed('Magento_Customer::group');
    }
}
  1. In Magento Catalog Now I can select Multiple Customer Groups, and it's similar to Product Category selection (Up to This point it's working)

Expected result

  1. When I save the product it should save the Customer Groups in a string, same as category_ids attribute

Actual result

  1. Only save One Customer Group (First Item from the selection)
@katmoon
Copy link
Contributor

katmoon commented May 19, 2016

Hi @stepzerosolutions

Currently there are known problems with multiselect attribute
Please see #4346 and #4312

@katmoon katmoon added the MX label May 19, 2016
@KrystynaKabannyk
Copy link

Hello @stepzerosolutions, this issue has been fixed in the 2.1.0 Release, that's why I'm closing it. If you any questions or additional information regarding the issue feel free to reopen it or create a new one.

@Styopchik
Copy link

Issue still present in 2.1.3

@sinamiandashti
Copy link

2.1.4 still happening

@sinamiandashti
Copy link

@KrystynaKabannyk

@nkajic
Copy link
Member

nkajic commented May 26, 2017

Seems like duplicate of #6253 #6281 #6787
and that this is fixed by
https://github.com/nagno/magento2/commit/b380502570b92449326ab6ed50e6ce0359287240

@A-1A
Copy link

A-1A commented Jun 19, 2018

I Found Solution after R&D On Magento database.
Login In your phpmyadmin
Go to your website database
Open "eav_attribute" table
Find Your multiselect "attribute_id"
Edit Row
If "backend_model" Column blank then paste this Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend
And Also Please check this
https://magento.stackexchange.com/questions/224621/warning-array-filter-expects-parameter-1-to-be-array/230444#230444

@collinanderson
Copy link

in addition to changing backend_model, I needed to change backend_type from varchar to text

magento-cicd2 pushed a commit that referenced this issue Oct 8, 2019
[owls] MC-17701: Downloadable Product links
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants