Jak dodać pole obrazu do niestandardowych pól dynamicznych w konfiguracji systemu?


10

Chcę pozwolić administratorowi na generowanie tylu pól, ile on / ona chce. Znalazłem rozwiązanie w innym rozszerzeniu i wykorzystałem je jako punkt wyjścia. Mam więc taki kod:

W 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>

I w 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;
    }

Działa zgodnie z oczekiwaniami i wygląda tak:

wprowadź opis zdjęcia tutaj

Teraz chcę dodać pole Przesyłanie obrazu do mojego zestawu pól. Jak mam to zrobić?

Aktualizacja :

Wiem, system.xmlże możesz napisać ten kod, aby dodać pola obrazu:

<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>

Ale nie mogę zastosować tego podejścia, ponieważ chcę mieć wiele pól, a nie jedno.

Odpowiedzi:


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>

Element reprezentuje lokalizację, do której obraz zostanie przesłany. W powyższym przykładzie obraz zostanie zapisany w podfolderze w folderze multimediów. np. / media / theme /. Element służy do renderowania znacznika. Aby wydrukować obraz z powyższego przykładu, możesz użyć następującego kodu

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

Nie mogę użyć system.xmlw moim przypadku. Przeczytaj ponownie moje pytanie.
Pedram Behroozi

Ale dlaczego nie możesz go użyć
Vivek Khandelwal

Ponieważ twoje podejście dodaje jedno pole obrazu do konfiguracji systemu. Chcę mieć dynamiczną liczbę pól obrazu.
Pedram Behroozi

w porządku. Powiem wam inne podejście
Vivek Khandelwal

1

Próbowałem czegoś podobnego i udało mi się to rozwiązać tylko częściowo.

Po pierwsze, aby dodać kilka rodzajów pól w tablicy / serializowane opcją config, stworzyłem rozszerzoną wersję klasy Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract, które obejmowały typy select, multiselecti file(jak pierwotna funkcja dozwolone wyłącznie na korzystanie z textrodzaju), patrz https: / /github.com/Genmato/Core/blob/master/app/code/community/Genmato/Core/Block/System/Config/Form/Field/Array/Abstract.php (plik jest nieco za duży, aby go tu dołączyć).

Następnie dowiedziałem się, że połączenie typu pliku z innymi polami (select / text) nie działa poprawnie. Podczas zapisywania danych tylko szczegóły pliku, jeśli są dostępne, i tablica została pomieszana. Wybrałem rozwiązanie, które ma jedno pole do zapisywania przesyłanych plików:

<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>

Odpowiednia klasa bloku:

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();
    }

}

I klasa modelu zaplecza:

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;
    }

}

I drugie pole, w którym przechowuję moją konfigurację:

<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>

A zastosowana klasa bloków:

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();
    }

}

Tutaj używam opcji wyboru / menu rozwijanego, aby wybrać przesłany plik dla wiersza konfiguracji, co pozwala mi również używać tego samego pliku w wielu wierszach.

To może nie być idealne rozwiązanie dla Twojej sytuacji, ale może być punktem wyjścia do rozwiązania problemu. Zapraszam do korzystania z części kodu używanego w module Genmato_Core (patrz https://github.com/Genmato/Core ) dla własnego rozwiązania.


Dzięki. Spróbuję dzisiaj i dam ci znać. Wydaje się obiecujące.
Pedram Behroozi

@PedramBehroozi próbowałeś i działało? Byłbym również zainteresowany :)
simonthesorcerer

@simonthesorcerer jeszcze nie, ale powinienem się tym zająć przed sobotą. Wkrótce się zaktualizuje.
Pedram Behroozi,

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.