如何在magento2的自定义选项中设置默认值


9

我想将默认选项设置为产品级别的自定义选项值。

如何在Magento 2中做到这一点? 在此处输入图片说明

请帮助我解决这个问题。


请详细说明您的问题。
Sheshgiri Anvekar '17

似乎您正在要求在输入字段中放置一些默认文本。
Dinesh Yadav

在我的问题中,我有2个选项m我想将一个选项设置为前端上的默认选项。
rajat kara

如何实施呢?我想添加默认值?
Mahi M

Answers:


2

我不确定您可以通过管理员执行此操作。我只是在做一个工作,以确保所有“默认选项”都是admin中的第一个选项,然后将以下内容添加到商店的js中。

<script>
require(['jquery', 'jquery/ui'], function($){ 
  $('.product-add-form .field select').each(function(i, obj) {
    $(obj).find('option:eq(1)').prop('selected', true);
  });
});
</script>

这适用于自定义选项,因为它们全部在页面加载时呈现。该代码只是循环遍历所有自定义选项,并将第二个选项设置为第一个选项是“ please select”。

我对可配置产品有更多的困难,因为所有选项都是在页面加载后加载的,但是这样做也可以在这里看到我的问题:Magento 2:如何在可配置选项中设置默认选项?



1

我认为您想要实现的目标是这样的?

在此处输入图片说明

我实现了对于下拉字段,应该与单选按钮相同。

  1. 在表中为默认选项(is_default或其他)添加一列catalog_product_option_type_value
  2. 添加一个插件,该插件拦截的ModifyMeta方法Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions

例:

供应商/模块/etc/adminhtml/di.xml

<?xml version="1.0"?>
<config>
  <type name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions">
    <plugin name="CustomOptionsUiPlugin" type="Vendor\Module\Plugin\CustomOptionsUiPlugin" sortOrder="1"/>
  </type>
</config>

供应商\模块\插件\ CustomOptionsUiPlugin.php

namespace Vendor\Module\Plugin;

class CustomOptionsUiPlugin
{

...

    public function afterModifyMeta(\Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions $subject,$meta)
    {

        $result = $meta;

        $result['custom_options']['children']['options']['children']['record']['children']["container_option"]['children']['values']['children']['record']['children']['is_default'] = [
            'arguments' => [
                'data' => [
                    'config' => [
                        'label' => __('Default'),
                        'componentType' => 'field',
                        'formElement' => 'checkbox',
                        'dataScope' => 'is_default',
                        'dataType' => 'number',
                        'additionalClasses' => 'admin__field-small',
                        'sortOrder' => 55,
                        'value' => '0',
                        'valueMap' => [
                            'true' => '1',
                            'false' => '0'
                        ]
                    ]
                ]
            ]
        ];

        return $result;

    }

}
  1. 最后一点,你需要覆盖文件Magento\Catalog\Block\Product\View\Options\Type\Select.php像这样的东西

    $defaultAttribute = array();
    
    if($_value->getData('is_default') == true){
        $defaultAttribute = ['selected' => 'selected','default' => 'default'];
    }
    
    $select->addOption(
        $_value->getOptionTypeId(),
        $_value->getTitle() . ' ' . strip_tags($priceStr) . '',
        ['price' => $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false),$defaultAttribute]
    );

    希望有帮助!


感谢您的解决方案。我已经尝试过使用您的代码,并且能够显示“默认”选项,但是未显示自定义值。请帮助我解决问题。
Umarfarooq Galibwale

@TrytoFly $defaultAttribute作为选项的额外属性添加将与预配置的值(buy_request,...)冲突。例如,在编辑购物车项目时,客户选择的值 “ is_default”值都将标记为selected="selected"代码中的。
Cladiuss

0

@TrytoFly谢谢您的解决方案。我已经尝试过使用您的代码,并且能够显示“默认”选项,但是未显示自定义值。请帮助我解决问题。请找到图片

在此处输入图片说明

在此处输入图片说明


从屏幕截图中,我想您必须$result = $meta;在afterModifyMeta()方法的开头进行设置。否则,您将只覆盖您的返回值,而不是向其添加默认选项。
TrytoFly

0

@TrytoFly这对我有用。

<?php
namespace Sigma\DefaultCustomOptions\Plugin;

class CustomOptionsUiPlugin
{
       public function afterModifyMeta(
    \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions $subject,
    $result
) {

    $subject;
    $result['custom_options']['children']['options']['children']['record']['children']["container_option"]
    ['children']['values']['children']['record']['children'] =array_replace_recursive(
        $result['custom_options']['children']['options']['children']['record']['children']
        ["container_option"]['children']['values']['children']['record']['children'],
        [
            'is_default' => [
                'arguments' => [
                    'data' => [
                        'config' => [
                            'label' => __('Default'),
                            'componentType' => 'field',
                            'formElement' => 'checkbox',
                            'dataScope' => 'is_default',
                            'dataType' => 'number',
                            'sortOrder' => 70,
                            'value' => '0',
                            'valueMap' => [
                                'true' => '1',
                                'false' => '0'
                            ]
                        ]
                    ]
                ]
            ]
        ]
    );
    return $result;
    }
}

你能在这里写完整的代码吗?通过这种方式,我可以在admin中显示带有自定义选项的复选框,但是当我要保存产品时,默认情况下不会保存所选选项。以及如何显示在正面选择的默认设置?
Magecode '18

0

您可以像下面的代码功能一样覆盖Select.php文件:

class AroundOptionValuesHtml extends \Magento\Catalog\Block\Product\View\Options\Type\Select
{

    public function getValuesHtml()
    {
        $_option = $this->getOption();
        $configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
        $store = $this->getProduct()->getStore();

        $this->setSkipJsReloadPrice(1);
        // Remove inline prototype onclick and onchange events

        if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN ||
            $_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE
        ) {
            $require = $_option->getIsRequire() ? ' required' : '';
            $extraParams = '';
            $select = $this->getLayout()->createBlock(
                \Magento\Framework\View\Element\Html\Select::class
            )->setData(
                [
                    'id' => 'select_' . $_option->getId(),
                    'class' => $require . ' product-custom-option admin__control-select'
                ]
            );
            if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN) {
                $select->setName('options[' . $_option->getId() . ']')->addOption('', __('-- Please Select --'));
            } else {
                $select->setName('options[' . $_option->getId() . '][]');
                $select->setClass('multiselect admin__control-multiselect' . $require . ' product-custom-option');
            }
            foreach ($_option->getValues() as $_value) {
                $priceStr = $this->_formatPrice(
                    [
                        'is_percent' => $_value->getPriceType() == 'percent',
                        'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
                    ],
                    false
                );

                // custom code   
                $defaultAttribute = array();
                if($_value->getData('is_default') == true){
                    $defaultAttribute = ['selected' => 'selected'];
                }

                // custom code

                $select->addOption(
                    $_value->getOptionTypeId(),
                    $_value->getTitle() . ' ' . strip_tags($priceStr) . '',
                    ['price' => $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false),$defaultAttribute]
                );
            }

            // custom code added 

            if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE) {
                $extraParams = ' multiple="multiple"';
            }
            if (!$this->getSkipJsReloadPrice()) {
                $extraParams .= ' onchange="opConfig.reloadPrice()"';
            }
            $extraParams .= ' data-selector="' . $select->getName() . '"';
            $select->setExtraParams($extraParams);

            if ($configValue) {
                $select->setValue($configValue);
            }

            return $select->getHtml();

        }


    }

}

0

这是我发现为可自定义选项设置默认值的最简洁的方法:

(基于@TrytoFly答案)

注意:我假设你在一个已经创建的模块上工作,我称之为Vendor_Module

1.将is_default列添加到catalog_product_option_type_value

应用/代码/供应商/模块/设置/UpgradeSchema.php

<?php
namespace Vendor\Module\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        if (version_compare($context->getVersion(), '2.0.1') < 0) {
            $setup->getConnection()->addColumn(
                $setup->getTable('catalog_product_option_type_value'),
                'is_default',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
                    'length' => 1,
                    'unsigned' => true,
                    'nullable' => false,
                    'default' => '0',
                    'comment' => 'Defines if Is Default'
                ]
            );
        }
    }
}

注意:不要忘记根据模块更改版本

2.定义并创建一个插件以将复选框元素添加到后台

应用程序/代码/供应商/模块/etc/adminhtml/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions">
        <plugin name="vendor_module_custom_options_ui_plugin"
                type="Vendor\Module\Plugin\CustomOptionsUiPlugin" />
    </type>
</config>

应用/代码/供应商/模块/插件/CustomOptionsUiPlugin.php

<?php
namespace Vendor\Module\Plugin;

use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions;
use Magento\Ui\Component\Form\Field;
use Magento\Ui\Component\Form\Element\Checkbox;
use Magento\Ui\Component\Form\Element\DataType\Number;

/**
 * Data provider for "Customizable Options" panel
 */
class CustomOptionsUiPlugin
{
    /**
     * Field values
     */
    const FIELD_IS_DEFAULT = 'is_default';

    /**
     * @param \Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\CustomOptions $subject
     * @param bool $meta
     * @return bool
     */
    public function afterModifyMeta(CustomOptions $subject, $meta) {

        $result = $meta;

        $result[CustomOptions::GROUP_CUSTOM_OPTIONS_NAME]['children']
        [CustomOptions::GRID_OPTIONS_NAME]['children']['record']['children']
        [CustomOptions::CONTAINER_OPTION]['children']
        [CustomOptions::GRID_TYPE_SELECT_NAME]['children']['record']['children']
        [static::FIELD_IS_DEFAULT] = $this->getIsDefaultFieldConfig(70);

        return $result;

    }

    /**
     * Get config for checkbox field used for default values
     *
     * @param int $sortOrder
     * @return array
     */
    protected function getIsDefaultFieldConfig($sortOrder)
    {
        return [
            'arguments' => [
                'data' => [
                    'config' =>[
                        'label' => __('Default'),
                        'componentType' => Field::NAME,
                        'formElement' => Checkbox::NAME,
                        'dataScope' => static::FIELD_IS_DEFAULT,
                        'dataType' => Number::NAME,
                        'additionalClasses' => 'admin__field-small',
                        'sortOrder' => $sortOrder,
                        'value' => '0',
                        'valueMap' => [
                            'true' => '1',
                            'false' => '0'
                        ]
                    ],
                ],
            ],
        ];
    }
}

注意:这里我们使用Magento\Ui\Component\Form\Element\Checkbox而不是Magento\Ui\Component\Form\Element\Radio组件,因为Magento似乎从未在其Form Elements中定义它。

vendor\magento\module-ui\view\base\ui_component\etc\definition.xml第112行

3.覆盖Magento\Catalog\Block\Product\View\Options\Type\Select以检查已选择为“默认元素”的元素。

应用程序/代码/供应商/模块/etc/adminhtml/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Product\View\Options\Type\Select"
                type="Vendor\Module\Block\Rewrite\Catalog\Product\View\Options\Type\Select" />
</config>

应用程序/代码/供应商/模块/块/重写/目录/产品/视图/选项/类型/Select.php

<?php
namespace Vendor\Module\Block\Rewrite\Catalog\Product\View\Options\Type;

/**
 * Product options text type block
 */
class Select extends \Magento\Catalog\Block\Product\View\Options\Type\Select
{
    /**
     * Return html for control element
     *
     * @return string
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function getValuesHtml()
    {
        $_option = $this->getOption();
        $configValue = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $_option->getId());
        $store = $this->getProduct()->getStore();

        $this->setSkipJsReloadPrice(1);
        // Remove inline prototype onclick and onchange events

        if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN ||
            $_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE
        ) {
            $require = $_option->getIsRequire() ? ' required' : '';
            $extraParams = '';
            $select = $this->getLayout()->createBlock(
                \Magento\Framework\View\Element\Html\Select::class
            )->setData(
                [
                    'id' => 'select_' . $_option->getId(),
                    'class' => $require . ' product-custom-option admin__control-select'
                ]
            );
            if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_DROP_DOWN) {
                $select->setName('options[' . $_option->getId() . ']')->addOption('', __('-- Please Select --'));
            } else {
                $select->setName('options[' . $_option->getId() . '][]');
                $select->setClass('multiselect admin__control-multiselect' . $require . ' product-custom-option');
            }
            foreach ($_option->getValues() as $_value) {
                $priceStr = $this->_formatPrice(
                    [
                        'is_percent' => $_value->getPriceType() == 'percent',
                        'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
                    ],
                    false
                );

                if($_value->getData('is_default') == true && !$configValue){
                    $configValue = $_value->getOptionTypeId();
                }
                $select->addOption(
                    $_value->getOptionTypeId(),
                    $_value->getTitle() . ' ' . strip_tags($priceStr) . '',
                    ['price' => $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false)]
                );
            }
            if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_MULTIPLE) {
                $extraParams = ' multiple="multiple"';
            }
            if (!$this->getSkipJsReloadPrice()) {
                $extraParams .= ' onchange="opConfig.reloadPrice()"';
            }
            $extraParams .= ' data-selector="' . $select->getName() . '"';
            $select->setExtraParams($extraParams);

            if ($configValue) {
                $select->setValue($configValue);
            }

            return $select->getHtml();
        }

        if ($_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO ||
            $_option->getType() == \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX
        ) {
            $selectHtml = '<div class="options-list nested" id="options-' . $_option->getId() . '-list">';
            $require = $_option->getIsRequire() ? ' required' : '';
            $arraySign = '';
            switch ($_option->getType()) {
                case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_RADIO:
                    $type = 'radio';
                    $class = 'radio admin__control-radio';
                    if (!$_option->getIsRequire()) {
                        $selectHtml .= '<div class="field choice admin__field admin__field-option">' .
                            '<input type="radio" id="options_' .
                            $_option->getId() .
                            '" class="' .
                            $class .
                            ' product-custom-option" name="options[' .
                            $_option->getId() .
                            ']"' .
                            ' data-selector="options[' . $_option->getId() . ']"' .
                            ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
                            ' value="" checked="checked" /><label class="label admin__field-label" for="options_' .
                            $_option->getId() .
                            '"><span>' .
                            __('None') . '</span></label></div>';
                    }
                    break;
                case \Magento\Catalog\Api\Data\ProductCustomOptionInterface::OPTION_TYPE_CHECKBOX:
                    $type = 'checkbox';
                    $class = 'checkbox admin__control-checkbox';
                    $arraySign = '[]';
                    break;
            }
            $count = 1;
            foreach ($_option->getValues() as $_value) {
                $count++;

                $priceStr = $this->_formatPrice(
                    [
                        'is_percent' => $_value->getPriceType() == 'percent',
                        'pricing_value' => $_value->getPrice($_value->getPriceType() == 'percent'),
                    ]
                );

                $htmlValue = $_value->getOptionTypeId();
                if ($arraySign) {
                    $checked = is_array($configValue) && in_array($htmlValue, $configValue) ? 'checked' : '';
                } else {
                    $checked = $configValue == $htmlValue ? 'checked' : '';
                }

                $dataSelector = 'options[' . $_option->getId() . ']';
                if ($arraySign) {
                    $dataSelector .= '[' . $htmlValue . ']';
                }

                $selectHtml .= '<div class="field choice admin__field admin__field-option' .
                    $require .
                    '">' .
                    '<input type="' .
                    $type .
                    '" class="' .
                    $class .
                    ' ' .
                    $require .
                    ' product-custom-option"' .
                    ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"') .
                    ' name="options[' .
                    $_option->getId() .
                    ']' .
                    $arraySign .
                    '" id="options_' .
                    $_option->getId() .
                    '_' .
                    $count .
                    '" value="' .
                    $htmlValue .
                    '" ' .
                    $checked .
                    ' data-selector="' . $dataSelector . '"' .
                    ' price="' .
                    $this->pricingHelper->currencyByStore($_value->getPrice(true), $store, false) .
                    '" />' .
                    '<label class="label admin__field-label" for="options_' .
                    $_option->getId() .
                    '_' .
                    $count .
                    '"><span>' .
                    $_value->getTitle() .
                    '</span> ' .
                    $priceStr .
                    '</label>';
                $selectHtml .= '</div>';
            }
            $selectHtml .= '</div>';

            return $selectHtml;
        }
    }
}

4.升级模块版本并更新数据库

升级您setup_versionapp/code/Vendor/Module/etc/module.xml

更新你versionapp/code/Vendor/Module/composer.json

运行以下命令:

php bin/magento cache:clean
php bin/magento setup:upgrade
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.