Multiselect category dropdown on admin form Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Magento 2: use a chooser widget as a system configuration fieldPassing multiselect via form with getRequest()->getParam in admin moduleMagento Move CategoryPopulating the multiselect field with available values pre-selected in Admin form edit mode is not workingMagento 2 : How to add category selector on admin form?Magento 2: Add UI Multiselect DropdownMagento 2 Custom Module admin form category treeCategory List Dropdown paddingAdmin form Save button is not workingMagento admin form select type dependency fieldCan't choose any category in admin

"Seemed to had" is it correct?

Why are there no cargo aircraft with "flying wing" design?

Gastric acid as a weapon

What would be the ideal power source for a cybernetic eye?

Problem drawing boxes with arrows in tikZ

Single word antonym of "flightless"

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Why is "Captain Marvel" translated as male in Portugal?

What do you call a phrase that's not an idiom yet?

How to find all the available tools in macOS terminal?

When is phishing education going too far?

Is the Standard Deduction better than Itemized when both are the same amount?

Why did the IBM 650 use bi-quinary?

How discoverable are IPv6 addresses and AAAA names by potential attackers?

Why is black pepper both grey and black?

Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?

Disable hyphenation for an entire paragraph

do i need a schengen visa for a direct flight to amsterdam?

Dominant seventh chord in the major scale contains diminished triad of the seventh?

How does a Death Domain cleric's Touch of Death feature work with Touch-range spells delivered by familiars?

Is the address of a local variable a constexpr?

Are my PIs rude or am I just being too sensitive?

Were Kohanim forbidden from serving in King David's army?

Sorting numerically



Multiselect category dropdown on admin form



Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Magento 2: use a chooser widget as a system configuration fieldPassing multiselect via form with getRequest()->getParam in admin moduleMagento Move CategoryPopulating the multiselect field with available values pre-selected in Admin form edit mode is not workingMagento 2 : How to add category selector on admin form?Magento 2: Add UI Multiselect DropdownMagento 2 Custom Module admin form category treeCategory List Dropdown paddingAdmin form Save button is not workingMagento admin form select type dependency fieldCan't choose any category in admin



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have created custom CRUD on new database table. I just wanted to save comma separated categories in a field.



I have this code for multiselect categories:



$fieldset->addField(
'categories',
'multiselect',
[
'label' => __('Categories'),
'title' => __('Categories'),
'name' => 'categories',
'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
'note' => __('Could be multiple'),
'disabled' => $isElementDisabled
]
);


I have created getCategories function in Grid.php.



Can anyone suggested how to populate categories in tree form and return categories array










share|improve this question
























  • I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

    – Renga
    Feb 6 at 15:05











  • @Renga thanks for your input. I need this on admin form, how would I do that from your code?

    – Shoaib Munir
    Feb 6 at 15:20











  • try with setRenderer() method.

    – Renga
    Feb 6 at 16:30











  • $field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

    – Renga
    Feb 6 at 16:32











  • I will try your code. I suggest you add these in answer

    – Shoaib Munir
    Feb 6 at 16:48

















1















I have created custom CRUD on new database table. I just wanted to save comma separated categories in a field.



I have this code for multiselect categories:



$fieldset->addField(
'categories',
'multiselect',
[
'label' => __('Categories'),
'title' => __('Categories'),
'name' => 'categories',
'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
'note' => __('Could be multiple'),
'disabled' => $isElementDisabled
]
);


I have created getCategories function in Grid.php.



Can anyone suggested how to populate categories in tree form and return categories array










share|improve this question
























  • I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

    – Renga
    Feb 6 at 15:05











  • @Renga thanks for your input. I need this on admin form, how would I do that from your code?

    – Shoaib Munir
    Feb 6 at 15:20











  • try with setRenderer() method.

    – Renga
    Feb 6 at 16:30











  • $field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

    – Renga
    Feb 6 at 16:32











  • I will try your code. I suggest you add these in answer

    – Shoaib Munir
    Feb 6 at 16:48













1












1








1








I have created custom CRUD on new database table. I just wanted to save comma separated categories in a field.



I have this code for multiselect categories:



$fieldset->addField(
'categories',
'multiselect',
[
'label' => __('Categories'),
'title' => __('Categories'),
'name' => 'categories',
'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
'note' => __('Could be multiple'),
'disabled' => $isElementDisabled
]
);


I have created getCategories function in Grid.php.



Can anyone suggested how to populate categories in tree form and return categories array










share|improve this question
















I have created custom CRUD on new database table. I just wanted to save comma separated categories in a field.



I have this code for multiselect categories:



$fieldset->addField(
'categories',
'multiselect',
[
'label' => __('Categories'),
'title' => __('Categories'),
'name' => 'categories',
'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
'note' => __('Could be multiple'),
'disabled' => $isElementDisabled
]
);


I have created getCategories function in Grid.php.



Can anyone suggested how to populate categories in tree form and return categories array







admin category magento-2.2.5 category-tree






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 16 mins ago







Shoaib Munir

















asked Feb 6 at 14:52









Shoaib MunirShoaib Munir

2,5262931




2,5262931












  • I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

    – Renga
    Feb 6 at 15:05











  • @Renga thanks for your input. I need this on admin form, how would I do that from your code?

    – Shoaib Munir
    Feb 6 at 15:20











  • try with setRenderer() method.

    – Renga
    Feb 6 at 16:30











  • $field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

    – Renga
    Feb 6 at 16:32











  • I will try your code. I suggest you add these in answer

    – Shoaib Munir
    Feb 6 at 16:48

















  • I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

    – Renga
    Feb 6 at 15:05











  • @Renga thanks for your input. I need this on admin form, how would I do that from your code?

    – Shoaib Munir
    Feb 6 at 15:20











  • try with setRenderer() method.

    – Renga
    Feb 6 at 16:30











  • $field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

    – Renga
    Feb 6 at 16:32











  • I will try your code. I suggest you add these in answer

    – Shoaib Munir
    Feb 6 at 16:48
















I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

– Renga
Feb 6 at 15:05





I have done with Default Category Chooser. magento.stackexchange.com/questions/116073/…. Please look at this maybe it will helps you.

– Renga
Feb 6 at 15:05













@Renga thanks for your input. I need this on admin form, how would I do that from your code?

– Shoaib Munir
Feb 6 at 15:20





@Renga thanks for your input. I need this on admin form, how would I do that from your code?

– Shoaib Munir
Feb 6 at 15:20













try with setRenderer() method.

– Renga
Feb 6 at 16:30





try with setRenderer() method.

– Renga
Feb 6 at 16:30













$field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

– Renga
Feb 6 at 16:32





$field = $fieldset->addField( 'store_id', 'select', [ 'label' => __('Store'), 'title' => __('Store'), 'values' => '1', 'name' => 'store_id', 'required' => true ] ); $renderer = $this->getLayout()->createBlock( 'MagentoBackendBlockStoreSwitcherFormRendererFieldsetElement' ); $field->setRenderer($renderer);

– Renga
Feb 6 at 16:32













I will try your code. I suggest you add these in answer

– Shoaib Munir
Feb 6 at 16:48





I will try your code. I suggest you add these in answer

– Shoaib Munir
Feb 6 at 16:48










1 Answer
1






active

oldest

votes


















0














After so many tries, I have figured out the solution for my own question.



I used this code to make multiselect (as mentioned in my question):



$fieldset->addField(
'categories',
'multiselect',
[
'label' => __('Categories'),
'title' => __('Categories'),
'name' => 'categories',
'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
'note' => __('Could be multiple'),
'disabled' => $isElementDisabled
]
);


In Grid.php file I have created two functions
one is to create simple array for multi select values:



static public function getCategories()

$data_array = array();
foreach (VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree() as $k => $v)
$data_array[] = array('value' => $k, 'label' => $v);

return ($data_array);




And the 2nd one is a recursive function to generate category tree



static public function getCategoryTree($categories = "", $data_array = array())

if(empty($categories))
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$categoryFactory = $_objectManager->create('MagentoCatalogModelResourceModelCategoryCollectionFactory');
$categories = $categoryFactory->create()
->addAttributeToSelect('*')//or you can just add some attributes
->addAttributeToFilter('level', 2)//2 is actually the first level
->addAttributeToFilter('is_active', 1)//if you want only active categories
->addAttributeToSort('position', 'ASC');


foreach($categories as $k=>$category)
$level = $category->getLevel();
$data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
$childCategories = $category->getChildrenCategories();
if(count($childCategories) > 0)
$data_array = VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree($childCategories, $data_array);


if(count($data_array) == 0)
return $data_array;

return ($data_array);



My final array $data_array contains the IDs in array key and Category title in values.






share|improve this answer























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f260718%2fmultiselect-category-dropdown-on-admin-form%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    After so many tries, I have figured out the solution for my own question.



    I used this code to make multiselect (as mentioned in my question):



    $fieldset->addField(
    'categories',
    'multiselect',
    [
    'label' => __('Categories'),
    'title' => __('Categories'),
    'name' => 'categories',
    'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
    'note' => __('Could be multiple'),
    'disabled' => $isElementDisabled
    ]
    );


    In Grid.php file I have created two functions
    one is to create simple array for multi select values:



    static public function getCategories()

    $data_array = array();
    foreach (VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree() as $k => $v)
    $data_array[] = array('value' => $k, 'label' => $v);

    return ($data_array);




    And the 2nd one is a recursive function to generate category tree



    static public function getCategoryTree($categories = "", $data_array = array())

    if(empty($categories))
    $_objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $categoryFactory = $_objectManager->create('MagentoCatalogModelResourceModelCategoryCollectionFactory');
    $categories = $categoryFactory->create()
    ->addAttributeToSelect('*')//or you can just add some attributes
    ->addAttributeToFilter('level', 2)//2 is actually the first level
    ->addAttributeToFilter('is_active', 1)//if you want only active categories
    ->addAttributeToSort('position', 'ASC');


    foreach($categories as $k=>$category)
    $level = $category->getLevel();
    $data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
    $childCategories = $category->getChildrenCategories();
    if(count($childCategories) > 0)
    $data_array = VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree($childCategories, $data_array);


    if(count($data_array) == 0)
    return $data_array;

    return ($data_array);



    My final array $data_array contains the IDs in array key and Category title in values.






    share|improve this answer



























      0














      After so many tries, I have figured out the solution for my own question.



      I used this code to make multiselect (as mentioned in my question):



      $fieldset->addField(
      'categories',
      'multiselect',
      [
      'label' => __('Categories'),
      'title' => __('Categories'),
      'name' => 'categories',
      'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
      'note' => __('Could be multiple'),
      'disabled' => $isElementDisabled
      ]
      );


      In Grid.php file I have created two functions
      one is to create simple array for multi select values:



      static public function getCategories()

      $data_array = array();
      foreach (VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree() as $k => $v)
      $data_array[] = array('value' => $k, 'label' => $v);

      return ($data_array);




      And the 2nd one is a recursive function to generate category tree



      static public function getCategoryTree($categories = "", $data_array = array())

      if(empty($categories))
      $_objectManager = MagentoFrameworkAppObjectManager::getInstance();
      $categoryFactory = $_objectManager->create('MagentoCatalogModelResourceModelCategoryCollectionFactory');
      $categories = $categoryFactory->create()
      ->addAttributeToSelect('*')//or you can just add some attributes
      ->addAttributeToFilter('level', 2)//2 is actually the first level
      ->addAttributeToFilter('is_active', 1)//if you want only active categories
      ->addAttributeToSort('position', 'ASC');


      foreach($categories as $k=>$category)
      $level = $category->getLevel();
      $data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
      $childCategories = $category->getChildrenCategories();
      if(count($childCategories) > 0)
      $data_array = VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree($childCategories, $data_array);


      if(count($data_array) == 0)
      return $data_array;

      return ($data_array);



      My final array $data_array contains the IDs in array key and Category title in values.






      share|improve this answer

























        0












        0








        0







        After so many tries, I have figured out the solution for my own question.



        I used this code to make multiselect (as mentioned in my question):



        $fieldset->addField(
        'categories',
        'multiselect',
        [
        'label' => __('Categories'),
        'title' => __('Categories'),
        'name' => 'categories',
        'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
        'note' => __('Could be multiple'),
        'disabled' => $isElementDisabled
        ]
        );


        In Grid.php file I have created two functions
        one is to create simple array for multi select values:



        static public function getCategories()

        $data_array = array();
        foreach (VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree() as $k => $v)
        $data_array[] = array('value' => $k, 'label' => $v);

        return ($data_array);




        And the 2nd one is a recursive function to generate category tree



        static public function getCategoryTree($categories = "", $data_array = array())

        if(empty($categories))
        $_objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $categoryFactory = $_objectManager->create('MagentoCatalogModelResourceModelCategoryCollectionFactory');
        $categories = $categoryFactory->create()
        ->addAttributeToSelect('*')//or you can just add some attributes
        ->addAttributeToFilter('level', 2)//2 is actually the first level
        ->addAttributeToFilter('is_active', 1)//if you want only active categories
        ->addAttributeToSort('position', 'ASC');


        foreach($categories as $k=>$category)
        $level = $category->getLevel();
        $data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
        $childCategories = $category->getChildrenCategories();
        if(count($childCategories) > 0)
        $data_array = VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree($childCategories, $data_array);


        if(count($data_array) == 0)
        return $data_array;

        return ($data_array);



        My final array $data_array contains the IDs in array key and Category title in values.






        share|improve this answer













        After so many tries, I have figured out the solution for my own question.



        I used this code to make multiselect (as mentioned in my question):



        $fieldset->addField(
        'categories',
        'multiselect',
        [
        'label' => __('Categories'),
        'title' => __('Categories'),
        'name' => 'categories',
        'values' => VendorModuleBlockAdminhtmlProductsGrid::getCategories(),
        'note' => __('Could be multiple'),
        'disabled' => $isElementDisabled
        ]
        );


        In Grid.php file I have created two functions
        one is to create simple array for multi select values:



        static public function getCategories()

        $data_array = array();
        foreach (VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree() as $k => $v)
        $data_array[] = array('value' => $k, 'label' => $v);

        return ($data_array);




        And the 2nd one is a recursive function to generate category tree



        static public function getCategoryTree($categories = "", $data_array = array())

        if(empty($categories))
        $_objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $categoryFactory = $_objectManager->create('MagentoCatalogModelResourceModelCategoryCollectionFactory');
        $categories = $categoryFactory->create()
        ->addAttributeToSelect('*')//or you can just add some attributes
        ->addAttributeToFilter('level', 2)//2 is actually the first level
        ->addAttributeToFilter('is_active', 1)//if you want only active categories
        ->addAttributeToSort('position', 'ASC');


        foreach($categories as $k=>$category)
        $level = $category->getLevel();
        $data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
        $childCategories = $category->getChildrenCategories();
        if(count($childCategories) > 0)
        $data_array = VendorModuleBlockAdminhtmlProductsgridGrid::getCategoryTree($childCategories, $data_array);


        if(count($data_array) == 0)
        return $data_array;

        return ($data_array);



        My final array $data_array contains the IDs in array key and Category title in values.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Feb 8 at 11:59









        Shoaib MunirShoaib Munir

        2,5262931




        2,5262931



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f260718%2fmultiselect-category-dropdown-on-admin-form%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

            Magento 2 disable Secret Key on URL's from terminal The Next CEO of Stack OverflowMagento 2 Shortcut/GUI tool to perform commandline tasks for windowsIn menu add configuration linkMagento oAuth : Generating access token and access secretMagento 2 security key issue in Third-Party API redirect URIPublic actions in admin controllersHow to Disable Cache in Custom WidgetURL Key not changing in Magento 2Product URL Key gets deleted when importing custom options - Magento 2Problem with reindex terminalMagento 2 - bin/magento Commands not working in Cpanel Terminal

            Aasi (pallopeli) Navigointivalikko