Подтвердить что ты не робот

Измените текст "Выберите вариант..." на странице продукта Magento

Я создал настраиваемый продукт, у него есть три варианта: цвет, размер и стиль.

Теперь на странице продукта каждый вариант имеет текст по умолчанию " Выбрать параметр..." в раскрывающемся списке, но я хочу, чтобы текст был " Выбрать цвет", " Выбрать размер" и " Выбрать стиль".

Я редактировал функцию getJsonConfig() в приложении \code\core\Mage\Catalog\Block\View\Type\Configurable.php

From:

    'chooseText'        => Mage::helper('catalog')->__('Choose an Option...'),

To:

    'chooseText'        => ('Select ').$attribute->getLabel(),

И отредактируйте строку 39 файла frontend/base/default/template/catalog/product/view/type/options/configurable.phtml до:

<option><?php echo $this->__('Select ') ?><?php echo $_attribute->getLabel() ?></option>

Но результат не очень хорош, он всегда показывает текст "Выберите стиль" в трех вариантах. Пожалуйста, дайте мне подсказку по этому вопросу, большое вам спасибо!

4b9b3361

Ответ 1

Моя версия той же проблемы. Вам нужно изменить только шаблон Каталог/продукта/вид/тип/опции/configurable.phtml:

<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <?php $chooseText = $this->__('Select %s', $_attribute->getLabel()); ?>
                <select data-choose-text="<?php echo $chooseText; ?>" name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
                    <option><?php echo $chooseText; ?></option>
                </select>
              </div>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        Product.ConfigDefaultText = new Class.create(Product.Config, {
            fillSelect: function($super, element) {
                $super(element);
                var chooseDefaultText = element.getAttribute('data-choose-text');
                $(element).options[0] = new Option(chooseDefaultText, '');
            }
        });
        var spConfig = new Product.ConfigDefaultText(<?php echo $this->getJsonConfig() ?>);
    </script>
<?php endif;?>

Примечание (извлечено из комментариев) Если выбранное значение по умолчанию не является "Выберите% s", замените

$(element).options[0] = new Option(chooseDefaultText, '');

с

$(element).options[0].innerHTML = chooseDefaultText;

Ответ 2

Я искал более простой способ сделать это. Я не хотел распространять файлы ядра или гадать с расширением JavaScript. Вместо этого я проанализировал настройки JSON, обновил параметр chooseText и преобразовал обратно в JSON:


/~theme/default/template/catalog/product/view/type/options/configurable.phtml

<?php
$jsonConfig = json_decode($this->getJsonConfig());
$jsonConfig->chooseText = 'Select..';
?>

<script type="text/javascript">
    var spConfig = new Product.Config(<?php echo json_encode($jsonConfig); ?>);
</script>

Дополнительная информация и дальнейшие примеры здесь.

Ответ 3

Единственный способ, по-моему, только изменить класс javascript, который заполняет эти выпадающие списки. Как мы видим в frontend/base/default/template/catalog/product/view/type/options/configurable.phtml, этот класс:

    <script type="text/javascript">
        var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
    </script>

Файл с необходимым классом, расположенный в js/varien/product.js

Место, где установлен первый тег <option>:

    fillSelect: function(element){
        var attributeId = element.id.replace(/[a-z]*/, '');
        var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);
        element.options[0] = new Option(this.config.chooseText, '');
        ...

Переменная chooseText используется там в строке 368. Эта переменная была создана в функции getJsonConfig() в app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php (вы копали правильный путь). Вам нужно изменить javascript, который я описал ранее, чтобы получить то, что вам нужно (на основе var attributeId вы можете назначать опции с различным текстом в нужные вам элементы)

Ответ 4

Я расширил класс Product.Config(метод fillselect) следующим кодом:

fillSelect: function(element){
                    var attributeId = element.id.replace(/[a-z]*/, '');
                    var options = this.getAttributeOptions(attributeId);
                    this.clearSelect(element);
                      element.options[0] = new Option('Select '+element.config.label,'');
                    ........

Это нормально!

Ответ 5

Если вы меняете файл configurable.js
Он изменится только при первом выборе при загрузке страницы
Поэтому я должен изменить файл шаблона
Получите прикрепленный файл для теста. (Я просто пишу его на небольшое расширение)

<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <?php
        $_attributeId = $_attribute->getAttributeId();
        $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
        $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel()));
        ?>
            <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
                <div class="input-box">
                    <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select kevin-black-<?php echo $_attributeLabel;?>">
                    <option><?php echo $_attributeInfo->getFrontendLabel() ?></option>
                    </select>
                </div>
            </dd>
        <?php endforeach; ?>
    </dl>
<script type="text/javascript">
    var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
    //[email protected] Change Text follow attribute Label
    function changeFristText(){
        <?php foreach($_attributes as $_attribute): ?>
            <?php
            $_attributeId = $_attribute->getAttributeId();
            $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
            ?>
            var label = '<?php echo $_attributeInfo->getFrontendLabel();?>';
            $$('select.kevin-black-'+label).each(function(elem){
                var options = elem.childElements();
                options[0].update(label);
            });
        <?php endforeach;?>
    }
</script>
<?php endif;?>


in file : js/varien/configurable.js replace line 171 = element.options[0] = new Option(element.config.label, ‘’);

Это для всех атрибутов.

Ответ 6

простейший ответ:

заменить строку js/varien/configurable.js 172

element.options[0].innerHTML = 'Choose ' + this.config.attributes[attributeId].label;

Ответ 7

каталог файлов/продукт/представление/тип/параметры/configurable.phml

<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <?php 
            $_attributeId = $_attribute->getAttributeId();
            $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
            $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel()));
        ?>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <select  name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select kevin-black-<?php echo $_attributeLabel;?>">
                    <option><?php echo $this->__('Select '.$_attributeLabel) ?></option>
                  </select>
              </div>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
        //Change Text follow attribute Label
        function changeFristText(){
            <?php foreach($_attributes as $_attribute): ?>
                <?php 
                    $_attributeId = $_attribute->getAttributeId();
                    $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
                    $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel()));
                ?>
                var label = '<?php echo $_attributeLabel;?>';
                $$('select.kevin-black-'+label).each(function(elem){
                    var options = elem.childElements();
                    options[0].update('Select ' + label);
                });
            <?php endforeach;?>
        }
    </script>
<?php endif;?>

и добавьте одну строку changeFristText(); после строки 171 (element.options[0] = new Option(this.config.chooseText, '');) в файле js/varien/configurable.js

Это для всех атрибутов.

Ответ 8

    <script type="text/javascript">
    <?php
        $jsonConfig = $this->getJsonConfig();
        $jsonConfig = str_replace("Choose an Option...", "Select Size", $jsonConfig);
    ?>
    var spConfig = new Product.Config(<?php echo $jsonConfig; ?>);
</script>

Ответ 9

Это работало для меня на CE 1.8.1. Он основывается на ответе Шеина и устраняет неправильный выбор, выбранный при загрузке. Я просто скопировал/ввел метод Product.Config. fillSelect() из /js/varien/product.js. Внутри вставленного кода я изменил:

element.options[0].innerHTML = this.config.chooseText;

к

element.options[0].innerHTML = element.config.label;

Это позволяет сохранить product.js немодифицированным и просто переопределить метод. Единственный недостаток - любые будущие обновления ядра для этого метода будут нуждаться в переносе.

Поскольку новый код просто получает параметр "label", атрибут data-select-text не нужен в теге select


<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
                    <option><?php echo $_attribute->getLabel() ?></option>
                </select>
              </div>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        Product.ConfigDefaultText = new Class.create(Product.Config, {
            fillSelect: function (element) {
                var attributeId = element.id.replace(/[a-z]*/, '');
                var options = this.getAttributeOptions(attributeId);
                this.clearSelect(element);
                element.options[0] = new Option('', '');
                element.options[0].innerHTML = element.config.label;

                var prevConfig = false;
                if (element.prevSetting) {
                    prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
                }

                if (options) {
                    var index = 1;
                    for (var i = 0; i < options.length; i++) {
                        var allowedProducts = [];
                        if (prevConfig) {
                            for (var j = 0; j < options[i].products.length; j++) {
                                if (prevConfig.config.allowedProducts
                                    && prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                                    allowedProducts.push(options[i].products[j]);
                                }
                            }
                        } else {
                            allowedProducts = options[i].products.clone();
                        }

                        if (allowedProducts.size() > 0) {
                            options[i].allowedProducts = allowedProducts;
                            element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                            element.options[index].config = options[i];
                            index++;
                        }
                    }
                }
            }
        });
        var spConfig = new Product.ConfigDefaultText(<?php echo $this->getJsonConfig() ?>);
    </script>
<?php endif;?>