Як додати поле зображення до моїх спеціальних динамічних полів у конфігурації системи?


10

Я хочу дозволити користувачеві адміністратора генерувати стільки полів, скільки він хоче. Я знайшов рішення в іншому розширенні, і я використав його як мою вихідну точку. Тож у мене є такий код:

В system.xml:

<showcases translate="label">
    <label>Showcases</label>
    <frontend_type>text</frontend_type>
    <sort_order>10</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
    <fields>
        <showcase translate="label">
            <label>Showcases</label>
            <frontend_type>select</frontend_type>
            <frontend_model>awesomehome/adminhtml_showcases</frontend_model>
            <backend_model>adminhtml/system_config_backend_serialized</backend_model>
            <sort_order>410</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
        </showcase>
    </fields>
</showcases>

І в Namespace/Awesomehome/Block/Adminhtml/Showcases.php:

class Namespace_Awesomehome_Block_Adminhtml_Showcases 
    extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected $_addRowButtonHtml = array();
    protected $_removeRowButtonHtml = array();

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $this->setElement($element);

        $html = '<div id="showcase_template" style="display:none">';
        $html .= $this->_getRowTemplateHtml();
        $html .= '</div>';

        $html .= '<ul id="showcase_container">';
        if ($this->_getValue('showcases')) {
            foreach (array_keys($this->_getValue('showcases')) as $row) {
                if ($row) {
                    $html .= $this->_getRowTemplateHtml($row);
                }
            }
        }
        $html .= '</ul>';
        $html .= $this->_getAddRowButtonHtml(
            'showcase_container',
            'showcase_template', $this->__('Add new showcase')
        );

        return $html;
    }

    protected function _getRowTemplateHtml($row = 0)
    {
        $html = '<li><fieldset>';

        $html .= $this->_getShowcaseTypeHtml($row);

        $html .= $this->_getRemoveRowButtonHtml();
        $html .= '</fieldset></li>';

        return $html;
    }

    protected function _getShowcaseTypeHtml($row) {
        $html = '<label>' . $this->__('Showcase type:') . '</label>';

        $html .= '<select style="width:100%;" class="input-text" name="' . $this->getElement()->getName() . '[type][]">';
        $html .= '<option value="1" '
                . ($this->_getValue('type/' . $row) == "1" ? 'selected="selected"' : '') .'>'
                . $this->__("Simple") . "</option>";
        $html .= '<option value="2" '
                . ($this->_getValue('type/' . $row) == "2" ? 'selected="selected"' : '') .'>'
                . $this->__("With Image") . "</option>";

        $html .= '</select><br/>';
        return $html;
    }

Це працює як очікувалося, і це так:

введіть тут опис зображення

Тепер я хочу додати поле для завантаження зображень у свій набір полів. Як мені це зробити?

Оновлення :

Я знаю, що у system.xmlвас можна написати цей код для додавання полів зображення:

<image translate="label">
    <label>Image</label>
    <frontend_type>image</frontend_type>
    <backend_model>adminhtml/system_config_backend_image</backend_model>
    <upload_dir config="system/filesystem/media" scope_info="1">awesomehome/topcategories</upload_dir>
    <base_url type="media" scope_info="1">awesomehome/topcategories</base_url>
    <sort_order>30</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
    <comment>Allowed file types: jpeg, gif, png.</comment>
</image>

Але я не можу використовувати цей підхід, тому що я хочу мати кілька полів, а не одне.

Відповіді:


2
Add this in your system.xml

<logo translate="label comment">
<label>Logo</label>
<comment>Allowed file types: jpeg, gif, png.</comment>
<frontend_type>image</frontend_type>
<backend_model>adminhtml/system_config_backend_image</backend_model>
<upload_dir config="system/filesystem/media" scope_info="1">theme</upload_dir>
<base_url type="media" scope_info="1">theme</base_url>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</logo>

Елемент представляє місце, куди буде завантажено зображення. У наведеному вище прикладі зображення буде збережено у підпапці під папкою медіа. напр. / медіа / тема /. Елемент використовується для візуалізації тегу. Для виведення зображення з наведеного вище прикладу ви можете використовувати наступний код

echo Mage::getBaseUrl('media') . Mage::getStoreConfig('system_config_name/group/logo');

Я не можу використовувати system.xmlв своєму випадку. Прочитайте ще раз моє запитання.
Педрам Бехрозі

Але чому ви не можете його використовувати
Вівек Ханделваль

Тому що ваш підхід додає до конфігурації системи одне поле зображення. Я хочу мати динамічну кількість полів зображення.
Педрам Бехрозі

добре. Я скажу вам інший підхід
Vivek Khandelwal

1

Я спробував щось подібне і вирішив лише частково.

По-перше, для того, щоб додати кілька типів полів у ваш параметр масиву / серіалізованої конфігурації, я створив розширену версію класу, Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstractяка включає типи select, multiselectі file(оскільки оригінальна функція дозволяла використовувати лише textтип), див. Https: / /github.com/Genmato/Core/blob/master/app/code/community/Genmato/Core/Block/System/Config/Form/Field/Array/Ab абстракт.php (файл трохи великий, щоб включити сюди).

Далі я з’ясував, що поєднання типу файлу з іншими полями (select / text) не працює належним чином. Під час збереження даних зберігаються лише дані про файли, де вони доступні, і масив переплутався. Тому я вибрав рішення, щоб було одне поле для збереження завантажень:

<templates translate="label comment">
                            <label>Templates</label>
                            <frontend_model>genmato_addresslabel/system_config_form_templates</frontend_model>
                            <backend_model>genmato_addresslabel/system_config_backend_storefile</backend_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                            <upload_dir config="system/filesystem/media" scope_info="1">addresslabel</upload_dir>
                            <base_url type="media" scope_info="1">addresslabel</base_url>
                            <comment>Label templates, to be used as background in the PDF (only PDF files are allowed)</comment>
                        </templates>

Відповідний клас блоків:

class Genmato_AddressLabel_Block_System_Config_Form_Templates extends Genmato_Core_Block_System_Config_Form_Field_Array_Abstract
{
    public function __construct()
    {
        $this->addColumn('template', array(
            'label' => Mage::helper('genmato_addresslabel')->__('Template'),
            'style' => 'width:300px',
            'class' => '',
            'type' => 'file',
        ));

        $this->_addAfter = false;
        $this->_addButtonLabel = Mage::helper('genmato_addresslabel')->__('Add new item');
        $this->setTemplate('genmato/core/system/config/form/field/array.phtml');
        parent::__construct();
    }

}

І клас резервної моделі:

class Genmato_AddressLabel_Model_System_Config_Backend_Storefile extends Mage_Adminhtml_Model_System_Config_Backend_File
{

    protected function _afterLoad()
    {
        $value = (string)$this->getValue();
        $this->setValue(empty($value) ? false : unserialize($value));
    }

    protected function _beforeSave()
    {

        $value = $this->getValue();

        // Load current template data
        $data = unserialize(Mage::getStoreConfig($this->getPath()));

        // Check for deleted records
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (!isset($value[$key])) {
                    unset($data[$key]);
                }
            }
        }

        // check for new uploads.
        foreach ($value as $key => $val) {
            if (!is_array($val)) {
                continue;
            }
            foreach ($val as $filefield => $filevalue) {
                try {
                    if ($_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value'][$key][$filefield]) {
                        $file = array();
                        $tmpName = $_FILES['groups']['tmp_name'];
                        $file['tmp_name'] = $tmpName[$this->getGroupId()]['fields'][$this->getField()]['value'][$key][$filefield];
                        $name = $_FILES['groups']['name'];
                        $file['name'] = $name[$this->getGroupId()]['fields'][$this->getField()]['value'][$key][$filefield];

                        if (isset($file['tmp_name']) || empty($file['tmp_name'])) {
                            $uploadDir = $this->_getUploadDir();

                            $uploader = new Mage_Core_Model_File_Uploader($file);
                            $uploader->setAllowedExtensions($this->_getAllowedExtensions());
                            $uploader->setAllowRenameFiles(true);
                            $result = $uploader->save($uploadDir);

                            $filename = $result['file'];
                            if ($filename) {
                                if ($this->_addWhetherScopeInfo()) {
                                    $filename = $this->_prependScopeInfo($filename);
                                }

                            }
                            $data[$key]['template'] = $filename;
                        } else {

                        }
                    }

                } catch (Exception $e) {
                    Mage::throwException($e->getMessage());
                    return $this;
                }
            }
        }

        $this->setValue(serialize($data));

        return $this;
    }

}

І друге поле, де я зберігаю свою конфігурацію:

<config translate="label comment">
                            <label>Label configurations</label>
                            <frontend_model>genmato_addresslabel/system_config_form_config</frontend_model>
                            <backend_model>genmato_pdflib/system_config_backend_storeserial</backend_model>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                            <comment>Label configuration, you can create multiple label configurations for different usages</comment>
                        </config>

І блок-клас використовується:

class Genmato_AddressLabel_Block_System_Config_Form_Config extends Genmato_Core_Block_System_Config_Form_Field_Array_Abstract
{
    public function __construct()
    {

        $this->addColumn('name', array(
            'label' => Mage::helper('genmato_addresslabel')->__('Name'),
            'style' => 'width:100px',
        ));

        $this->addColumn('template', array(
            'label' => Mage::helper('genmato_addresslabel')->__('Use template'),
            'style' => 'width:100px',
            'type' => 'select',
            'options' => Mage::getModel('genmato_addresslabel/system_config_source_templates')->getTemplates(),
        ));

        $this->addColumn('width', array(
            'label' => Mage::helper('genmato_addresslabel')->__('W (mm)'),
            'style' => 'width:40px'
        ));

        $this->addColumn('height', array(
            'label' => Mage::helper('genmato_addresslabel')->__('H (mm)'),
            'style' => 'width:40px'
        ));

        $this->addColumn('rotate', array(
            'label' => Mage::helper('genmato_addresslabel')->__('Rotate 90'),
            'type' => 'select',
            'options' => array("0" => "No", "1" => "Yes"),
            'style' => 'width:50px'
        ));

        $this->addColumn('multiple', array(
            'label' => Mage::helper('genmato_addresslabel')->__('Multiple labels'),
            'type' => 'select',
            'options' => array("0" => "No", "1" => "Yes"),
            'style' => 'width:50px'
        ));

        $this->addColumn('label_width', array(
            'label' => Mage::helper('genmato_addresslabel')->__('W (mm)'),
            'style' => 'width:40px'
        ));

        $this->addColumn('label_height', array(
            'label' => Mage::helper('genmato_addresslabel')->__('H (mm)'),
            'style' => 'width:40px'
        ));

        $this->_addAfter = false;
        $this->_addButtonLabel = Mage::helper('genmato_addresslabel')->__('Add new item');
        $this->setTemplate('genmato/core/system/config/form/field/array.phtml');
        parent::__construct();
    }

}

Тут я використовую параметр select / dropdown для вибору завантаженого файлу для кожного конфігураційного рядка, це також дозволяє мені використовувати один і той же файл у кількох рядках.

Це може бути не ідеальним рішенням для вашої ситуації, але може стати відправною точкою для вирішення вашої проблеми. Не соромтесь використовувати частини коду, що використовується у модулі Genmato_Core (Див. Https://github.com/Genmato/Core ) для власного рішення.


Дякую. Я спробую сьогодні і дам вам знати. Це здається перспективним.
Педрам Бехрозі

@PedramBehroozi ви спробували це, і чи спрацювало? Мені також було б цікаво :)
simonthesorcerer

@simonthesorcerer ще немає, але я мав би розібратися з цим до суботи. Незабаром оновиться.
Педрам Бехрозі

-1

Замість того, щоб розміщувати посилання, публікуйте якийсь код на випадок, якщо посилання більше не працюють
rob3000
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.