How to create multi-select type input in magento 2 custom form? – Usually in our custom module we have custom form to enter data. We use text box, Select, Text-area etc in our forms. Recently i faced an issue while creating the form with multi-select input type. So i will write this article to explain how to create a multi-select type input type and save the data.
Create the field – Main.php ( app/code/Ayakil/FreeGift/Block/Adminhtml/Freegifts/Edit/Tab/Main.php )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//---------- $fieldset->addField( 'elegible_products', 'multiselect', [ 'label' => __('Products'), 'title' => __('Products'), 'name' => 'elegible_products', 'required' => true, 'values' => \Ayakil\FreeGift\Block\Adminhtml\Freegifts\Grid::getValueArray4(), 'disabled' => $isElementDisabled ] ); //---------- |
Create the getOptionArray4 function – Grid.php ( app/code/Ayakil/FreeGift/Block/Adminhtml/Freegifts/Grid.php )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//------------ static public function getOptionArray4() { $data_array=array(); $data_array[0]='Product 1'; $data_array[1]='Product 2'; $data_array[2]='Product 3'; return($data_array); } static public function getValueArray4() { $data_array=array(); foreach(\Ayakil\FreeGift\Block\Adminhtml\Freegifts\Grid::getOptionArray4() as $k=>$v){ $data_array[]=array('value'=>$k,'label'=>$v); } return($data_array); } //------------ |
With these after i run the setup:upgrade. If i tried to add the data, i am getting an error like below.
{“0″:”Notice: Array to string conversion in /home/muja/www/ayakil-greens/vendor/magento/framework/DB/Adapter/Pdo/Mysql.php on line 3105″,”1”
For this we want to edit the save controller( app/code/Ayakil/FreeGift/Controller/Adminhtml/freegifts/Save.php ) with following code. Want to implode the values and set the data to save.
1 2 3 4 5 6 7 |
public function execute() { $data = $this->getRequest()->getPostValue(); $data['elegible_products'] = implode(',',$data['elegible_products']); //---------- Other codes going below } |
That’s it , many articles covered how to create a multi-select but i thought to include the error while saving the form and solution with this article,Hope this may help some one’s time in future.
That’s it. Have a nice day.Enjoy coding , Learn , Experience , Teach and Help.
Howdy very cool blog!! Guy .. Excellent .. Superb .. I will bookmark your web
site and take the feeds additionally? I’m glad to find a lot of helpful
info here in the put up, we need work out more strategies
on this regard, thanks for sharing. . . . . .
Great thanks for your thoughts and its really motivated me to write more