Magento2.1 desplegable de atributos personalizados de categoría

10

pasos para reproducir

1. El script del Módulo UpgradeData.php contiene:

$categorySetup->addAttribute(Category::ENTITY, 'roflcopter', [
                    'type' => 'int',
                    'label' => 'CMS Block',
                    'input' => 'select',
                    'source' => 'Magento\Catalog\Model\Category\Attribute\Source\Page',
                    'required' => false,
                    'sort_order' => 20,
                    'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                    'group' => 'Display Settings',
            ]);

2. ver / adminhtml / ui_component / category_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="Navigation">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Navigation</item>
                <item name="collapsible" xsi:type="boolean">true</item>
                <item name="sortOrder" xsi:type="number">100</item>
            </item>
        </argument>
        <field name="roflcopter">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">60</item>
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="label" xsi:type="string" translate="true">Roflcopter</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

Resultado Esperado

  1. En el formulario de categoría debe aparecer desplegable, seleccione Roflcopter con bloques CMS como opciones

Resultado actual

  1. Desplegable vacío
Sergejs Zakatovs
fuente

Respuestas:

14

Agregar etiqueta de opciones para crear opciones seleccionadas. En tu caso esto debería ser


<field name="roflcopter">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Magento\Catalog\Model\Category\Attribute\Source\Page</item>
        <item name="config" xsi:type="array">
            <item name="sortOrder" xsi:type="number">70</item>
            <item name="dataType" xsi:type="string">string</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="label" xsi:type="string" translate="true">Roflcopter</item>
        </item>
    </argument>
</field>

Sohel Rana
fuente
¿Quizás sabe si puedo mostrar / ocultar esta pestaña y / o sus atributos en función de algunas condiciones, por ejemplo, la profundidad de la categoría?
Sergejs Zakatovs
¡GRACIAS! Estuve buscando esto por tanto tiempo. Los documentos no son tan claros sobre este tema. ¿Cómo sabes esto?
CompactCode
Los datos no se guardan en la base de datos @Sohel Rana
Chirag Parmar
2

Lo he hecho en mi caso. Tengo opciones personalizadas ej. L1, L2 y L3. Necesito ponerlos en atributos personalizados como valores. Así que creé un archivo fuente en el módulo: proveedor \ módulo \ Modelo \ Configuración \ Fuente \ Opciones.php

este archivo contiene el código pequeño para crear las opciones, aquí puede seguir el código

 <?php
    /**
     * Copyright © 2013-2017 Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
    namespace Vendor\module\Model\Config\Source;
    /**
     * Catalog category landing page attribute source
     *
     * @author      Magento Core Team <[email protected]>
     */
    class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
    {
        /**
         * {@inheritdoc}
         * @codeCoverageIgnore
         */
        public function getAllOptions()
        {
            if (!$this->_options) {
                $this->_options = [
                    ['value' => 'l1', 'label' => __('L1')],
                    ['value' => 'l2', 'label' => __('L2')],
                    ['value' => 'l3', 'label' => __('L3')],
                ];
            }
            return $this->_options;
        }
          /**
         * Get options in "key-value" format
         *
         * @return array
         */
        public function toArray()
        {
            return [
                'l1' => __('L1'),
                'l2' => __('L2'),
                'L3' => __('L3'),
                ];
        }

    }

luego, en su installdata.php, debe llamar a esto como fuente

$eavSetup->addAttribute(
            Category::ENTITY,
            'category_level_rendering',
            [
                'type' => 'varchar',
                'backend' => '',
                'frontend' => '',
                'label' => 'Category Level rendering',
                'input' => 'select',
                'required' => false,
                'sort_order' => 100,
                'source' => '',
                'visible'  => true,
                'source' => 'vendor\module\Model\Config\Source\Options',
                'default'  => '0',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
                'used_in_product_listing' => true,
             ]
        );

Luego también agregue la línea en el archivo xml

<field name="category_level_rendering">
                <argument name="data" xsi:type="array">
/*Here is the code added to get the options on dropdown*/
<item name="options" xsi:type="object">Vendor\module\Model\Config\Source\Options</item>
                    <item name="config" xsi:type="array">
                        <item name="sortOrder" xsi:type="number">10</item>
                        <item name="dataType" xsi:type="string">string</item>
                        <item name="formElement" xsi:type="string">select</item>
                        <item name="label" xsi:type="string" translate="true">Category Level Rendering</item>
                    </item>
                </argument>
            </field>

Guárdelo, vacíe el caché y verifique.

Ojalá te ayude.

Por favor, dame una respuesta si te funciona.

Jdprasad V
fuente
Obtuve este tipo de error: Elemento 'campo': este elemento no se espera. Se espera que sea uno de (configuración, columna, accionesColumna, seleccionesColumna). Línea: 681
Pratik Mehta
¿Cómo
guardaste
Los datos no se guardan en la base de datos @Jdprasad V
Chirag Parmar
Esto funcionó para mí, compruebe nuevamente si realizó algún cambio en la página de esquema.
Jdprasad V
1
+1 por esto. Esto funciona para mi. ] falta en la matriz. Lo edito
Chirag Parmar el