2

I'm making a custom form with some dropdown data a user can select.

The content which get's inserted needs to come from the backend configuration.

This is the form I have made, this form will be shown on the frontend, not the backend.

enter image description here

I have no idea how to insert data in the dropdown above from the admin backend, this is the adminhtml I've already created:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="tab"
             translate="label"
             sortOrder="1000">
            <label>UT</label>
        </tab>
        <section id="trendsquare_module"
                 translate="label"
                 type="text"
                 sortOrder="1"
                 showInDefault="1"
                 showInWebsite="1"
                 showInStore="1">
            <label>Module settings</label>
            <tab>tab</tab>
            <resource>AdminTabs::config</resource>
            <group id="trendsquare_module"
                   translate="label"
                   type="text"
                   sortOrder="2"
                   showInDefault="1"
                   showInWebsite="1"
                   showInStore="1">
                <label>Dropdown Data</label>
                <field id="dropdown" translate="label" type="editablemultiselect" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Dropdown Data</label>
                </field>
            </group>
        </section>
    </system>
</config>

Which gives me this as a result:

enter image description here

  • let me know if you have any issue – Prince Patel Oct 3 '17 at 12:51
1

Add dropdown <source_model> in field like this

<field id="dropdown" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
    <label>Your Label</label>
    <source_model>Vendor\Module\Model\Config\Myoptions</source_model>
</field>

Now create Myoptions.php at

app/code/Vendor/Module/Model/Config/Myoptions.php

<?php

namespace Vendor\Module\Model\Config;

class Myoptions implements \Magento\Framework\Option\ArrayInterface
{   
    protected $modelFactory;

    public function __construct(modelFactory $modelFactory)
    {
        $this->modelFactory = $modelFactory;
    }

    public function toOptionArray()
    {
        $collection = $this->modelFactory->create()->getCollection();
        $options = [];
        foreach ($collection as $value) {
            $options[] = ['label' => $value->getName(), 'value'=>$value->getId()];
        }
        return $options;
    }
}
  • Many thanks for your answer, but the values and labels are now static. These values need to be filled with the data provided in the backend configuration. – Frank Groot Oct 3 '17 at 12:54
  • @FrankGroot check my updated answer. you can load your model in construct and get option dynamically – Prince Patel Oct 3 '17 at 12:59
  • I don't really understand what you mean, the values and labels in the dropdown need to be set in the admin configuration. I feel like they stay static when i insert them with a model... – Frank Groot Oct 3 '17 at 13:06
  • For that add data in dropdown like option1,option2,option3. then use explode function and fill option with foreach – Prince Patel Oct 3 '17 at 13:28
  • Thank you for your suggestions, but the dropdown will be shown in a form on the frontend. The data which needs to be in the dropdown comes from the backend.. If I fully understand your suggestion above there will be a dropdown added in the backend... – Frank Groot Oct 4 '17 at 7:47
0

You need to add a Source Model for this to work:

<field id="dropdown" translate="label" type="editablemultiselect" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
    <label>Dropdown Data</label>
    <source_model>Vendor\Module\Model\Config\Source\Example</source_model>
</field>

Your source model needs to implement \Magento\Eav\Model\Entity\Attribute\Source\SourceInterface

class Example implements \Magento\Eav\Model\Entity\Attribute\Source\SourceInterface
{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Example constructor.
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @return array
     */
    public function getAllOptions()
    {
        $content = $this->scopeConfig->getValue('path/to/config');

        $values = [];
        $lines = explode("\n", $content);
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line)) {
                $values[] = [
                    'value' => $line,
                    'label' => $line
                ];
            }
        }

        return $values;
    }

    /**
     * @param string $value
     * @return string
     */
    public function getOptionText($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
    }
}
  • Many thanks for your answer, but the values and labels are now static. These values need to be filled with the data provided in the backend configuration. – Frank Groot Oct 3 '17 at 12:54
  • No problem. I've updated my answer to reflect your use case. – Giel Berkers Oct 3 '17 at 14:05
  • Thank you Giel, after i tested your code i got this error Call to undefined method Vendor\Module\Model\Config\Source\DropdownOptions::toOptionArray() I renamed the class from Example to DropdownOptions – Frank Groot Oct 3 '17 at 14:50
0

I finally managed to populate the dropdown on the frontend according to the backend configuration.

First you need to create a tab in the admin configuration like this:
app/code/Vendor/Module/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="tab"
             translate="label"
             sortOrder="1000">
            <label>Your tab label</label>
        </tab>
        <section id="AdminTabs"
                 translate="label"
                 type="text"
                 sortOrder="1"
                 showInDefault="1"
                 showInWebsite="1"
                 showInStore="1">
            <label>ReCaptcha settings</label>
            <tab>tab</tab>
            <resource>Vendor_Module::config</resource>
            <group id="general"
                   translate="label"
                   type="text"
                   sortOrder="1"
                   showInDefault="1"
                   showInWebsite="1"
                   showInStore="1">
                <label>Your child tab label</label>
                <field id="dropdown" translate="label" type="text" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Dropdown values</label>
                    <comment>Data needs to be separated with a ; (semicolon).</comment>
                </field>
            </group>
        </section>
    </system>
</config>

If you would like to have a default value for the dropdown field you can do that with the config.xml which gets called with <resource>.

app/code/Vendor/Module/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <AdminTabs>
            <general>
                <dropdown>i.e: 01-01-2000 11:00; 01-01-2001 11:00</dropdown>
            </general>
        </AdminTabs>
    </default>
</config>

Now you have created the admin configuration tab with a text field. (And maybe a default value)

Next thing to do is create a function in your block.
/app/code/Vendor/Module/Block/Form.php

    /**
     * Retrieve dropdown data
     */
    public function getDropdownData()
    {
        $content = $this->_scopeConfig->getValue('AdminTabs/general/dropdown');
        $lines = explode(";", $content);
        foreach ($lines as $line) {
            $line = trim($line);
            if (!empty($line)) {
                echo '<option value="' . $line . '">' . $line . '</option>';
            }
        }
    }

Above function returns option tags with the values which are set in the admin configuration.

Here is an example to use the function in your template file.
/app/code/Vendor/Module/view/frontend/templates/form.phtml

<select required>
    <option value="" disabled selected>- Label -*</option>
    <?php echo $block->getDropdownData(); ?>
</select>

Result: enter image description here

I hope this helps other people.

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.