Я использую Magento 1.9.2.4 (1.9.2.3 на моей тестовой странице), и у меня есть некоторые настраиваемые продукты с более чем 1 опцией и каждым продуктом (дочерние продукты настраиваемого) имеет другое время доставки. Я создал атрибут под названием «delivery_time», который я хочу обновить, когда клиент выбирает вариант. Для этого я нашел некоторые фрагменты кода, которые я использую. Но он не обновляется правильно.Magento 1.9.2 - Обновление пользовательского атрибута 'delivery_time' в настраиваемом процессе продукта
так вот мое приложение/дизайн/интерфейс/RWD/fitgmbh/шаблон/Каталог/продукта/вид/тип/опции/configurable.phtml
<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes) && $_product->isConfigurable()):?>
<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"
onchange="return changeSku(<?php echo $_attribute->getAttributeId() ?>, this);">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
</div>
</dd>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
<?php endif;?>
<?php
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getDeliveryTime();
}
if($_product->getTypeId() == "configurable"):
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($simple_collection as $simple_product){
echo $simple_product->getName() . " - " . $simple_product->getDeliveryTime() . "<br>";
}
endif;
?>
<script type="text/javascript">
document.observe("dom:loaded", function() {
$("delivery").update("Bitte Optionen wählen");
});
function changeSku(confAttributeId, sel) {
var productMap = <?php echo Mage::helper('core')->jsonEncode($productMap);?>;
var selectedAttributeId = sel.options[sel.selectedIndex].value;
if (selectedAttributeId) {
var options = spConfig.config.attributes[confAttributeId].options;
var productId = options.find(function (option) {return option.id == selectedAttributeId}).products[0]
$("delivery").update("Lieferzeit: " + productMap[productId]);
} else {
$("delivery").reset(); //just a test ;-)
}
}
</script>
<?php echo $this->getChildHtml('after') ?>
и показываю выход в приложение/дизайн/интерфейс/RWD/fitgmbh/шаблон/Каталог/продукта/view.phtml с
<div id="delivery"></div>
Я знаю, что это может быть трудно понять мою проблему, так что я думаю, я должен дать ссылку на мой Testpage. В настраиваемом блоке я перечислял все доступные комбинации опций, где последнее число «означает» мое (тестовое) время доставки (1-12). Я действительно не знаю, что мне нужно сделать, чтобы этот код работал правильно. Я думаю, что часть «самого простого» решения может состоять в том, чтобы просто сбросить все входы, если клиент «возвращается» в процессе выбора варианта. Но мои навыки javascript не существуют. Кроме того, некоторые другие обновления доставки также не будут исправлены. Но после нескольких часов проб и ошибок я сдался, по крайней мере, на данный момент. Может, кто-то из вас может мне помочь. Я очень благодарен за каждый намек! Надеюсь, что я описал свою «проблему» соответствующим образом.
Я создал модуль под названием «Arithon_DeliveryUpdate», как предложил Крис Роджерс, но я никогда не создавал модули с наблюдателем или маршрутизатором. Поэтому в моем модуле определенно что-то не так. По крайней мере, его активной ;-)
приложение/код/местные/Arithon/DeliveryUpdate/и т.д./config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Arithon_DeliveryUpdate>
<version>1.0</version>
</Arithon_DeliveryUpdate>
</modules>
<frontend>
<routers>
<catalog>
<args>
<module>Arithon_DeliveryUpdate</module>
<frontName>delivery_time</frontName>
</args>
</catalog>
</routers>
</config>
приложение/код/местные/Arithon/DeliveryUpdate/Контроллеры/DeliveryController.php
<?php
public function updateAction() {
$match = 0;
if ($this->getRequest()->isPost()) {
extract($this->getRequest()->getPost());
$_storeId = Mage::app()->getStore()->getId();
$_attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attrId);
$_product = Mage::getModel('catalog/product')->load($productId);
if ($_product && $_attribute && is_object($_product) && $_product->type_id == 'configurable') {
$_attrCode = $_attribute->getData('attribute_code');
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $_product);
foreach($childProducts as $child) {
$cId = $child->getId();
$v = Mage::getResourceModel('catalog/product')->getAttributeRawValue($cId, $_attrCode, $storeId);
if ($v == $selectValue) {
$configAttr = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'delivery_time');
$configAttrId = $configAttr->getId();
$configAttrValue = Mage::getResourceModel('catalog/product')->getAttributeRawValue($cId, 'delivery_time', $storeId);
$match = array("attrId" => $configAttrId, "attrValue" => $configAttrValue);
break;
}
}
}
}
return $match;
}
?>
И мой модифицированный configurable.phtml
<?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes) && $_product->isConfigurable()):?>
<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" onchange="productAddToCartForm.updateDelivery(this, <?php echo $_product->getId() ?>);" name="super_attribute[<?php echo $attrId ?>]" id="attribute<?php echo $attrId ?>" class="required-entry super-attribute-select"
onchange="return changeSku(<?php echo $_attribute->getAttributeId() ?>, this) ;">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
</div>
</dd>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
<?php endif;?>
<?php
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getDeliveryTime();
}
//echo $simpleProduct->getDeliveryTime();
if($_product->getTypeId() == "configurable"):
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($simple_collection as $simple_product){
echo $simple_product->getName() . " - " . $simple_product->getDeliveryTime() . "<br>";
}
endif;
?>
<script type="text/javascript">
if (typeof productAddToCartForm != "undefined") {
productAddToCartForm.updateDelivery= function(select, product_id) {
if (select != null && product_id != null && typeof select.selectedIndex != "undefined") {
var keyword = 'attribute';
var url = '/deliveryupdate/delivery/update'; // don´t know what to put here
var val = select.options[select.selectedIndex].value;
var attrId = select.getAttribute("id").replace(keyword, "");
var formData = {
selectValue: val,
productId: product_id,
attrId: attrId
};
// Make request to controller which will determine which value the configurable_attr_placeholder
jQuery.ajax({
url: url,
type: 'POST',
data: formData,
success: function(data) {
// PHP returns string readily convertable to JSON
var response = JSON.parse(data);
if (typeof response == 'object') {
// JSON key values are attrId and attrValue
var delivEl = document.getElementById(keyword + response.attrId);
if (typeof delivEl != "undefined" && configSel) {
delivEl = response.attrValue;
break;
}
}
}
});
}
};
}
</script>
<?php echo $this->getChildHtml('after') ?>
Помимо ошибок, этот модуль должен ас тивно обновить пользовательский атрибут «delivery_time», так что я могу использовать
<?php echo $_product->getdelivery_time()?>
в моей view.phtml? Я бы не использовал
<div id="delivery"></div>
больше?
Заранее спасибо
Спасибо за предложение. Я попробую это как можно скорее! Я дам ответ, если он работает или нет, или я могу/не могу правильно применить ваше предложение. Еще раз спасибо! – CrynosArioch
Не беспокойтесь! –
Я пытался использовать ваши предложения, но мой модуль, как описано выше, не работает правильно. Может быть, вы могли бы снова взглянуть на мои упражнения? – CrynosArioch