I have this script to show the dynamic sku on select option, but i cannot get working.
Is loading the correct sku, but on select nothing happen.
This code get list of sku on Javascript and update a div on select option for product on configurable product view.
<?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" onchange="return changeSku(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();
echo '<script type="text/javascript">';
echo '
document.observe("dom:loaded", function() {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
});
';
echo ' function changeSku(sel){';
$itemId = array();
foreach($col as $simple_product){
$itemId[] = array($simple_product->getSelectLabel() => $simple_product->getSku());
}
//echo "<pre>";
//print_r($itemId);
//echo "</pre>";
foreach($itemId as $val){
foreach($val as $k => $v){
echo "\n".'if(sel.options[sel.selectedIndex].value == "'.$k.'"){'."\n";
echo '$("sku-container").update("<strong>Product Id: </strong>'.$v.'");'. "\n";
echo '}';
}
}
echo "\n".'if(sel.options[sel.selectedIndex].value == ""){'."\n";
echo '$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");'. "\n";
echo '}';
echo "}";
echo "\n</script>";
?>
I appreciate any help.
Thanks
The script is almost correct except for $simple_product->getSelectLabel() being a wrong key. No such method/property exists in a simple product model. In order to make the script work, this key should be replaced with a right one - a Product Id. Utilizing product id, it is possible to find the sku of the product being selected.
So, first of all you need to reorganize itemId array to make it a "productId => productSku" map:
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getSku();
}
Then you need to change the "onchange" function call to pass Configurable's attribute id to the changeSku() function. Thus the underlying logic is able to search appropriate simple product's attributes.
onchange="return changeSku(<?php echo $_attribute->getAttributeId() ?>, this);">
And after that you need utilize configurable's config in order to map selected simple product's attribute id to the product id selected:
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]
$("sku-container").update("<strong>Product Id: </strong>" + productMap[productId]);
} else {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
}
}
For your reference, below is the summary of how the whole template looks like (I've beautified it a little):
<?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"
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;?>
<div id="sku-container"></div>
<?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->getSku();
}
?>
<script type="text/javascript">
document.observe("dom:loaded", function() {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
});
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]
$("sku-container").update("<strong>Product Id: </strong>" + productMap[productId]);
} else {
$("sku-container").update("<strong>Product Id: </strong> Select an option to display Product Id");
}
}
</script>
This will do the task you originally needed.
Also note the following
Your approach won't work for a configurable product with two or more configurable attributes. For that product a final simple product is not known until a user selects values for all the select inputs. So an approach should be changed to check all the selects before outputting SKU.
The code doesn't consider a case, when user edits product configuration, rather than specifying configuration for a new product. You can go to editing mode from the Shopping Cart clicking the Edit link. In such a case all the select inputs will be pre-filled with previously chosen values. But the text will say "Select an option to display Product Id". The script might also produce other Javascript errors in Edit mode. The code should be slightly modified in order to support Edit mode as well.
The template is overfilled with logic. A Magento template should have only simple prints and foreach-iterations. All the methods like $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions() are better to be moved to block. This reduces code complexity.
Hope it helps.
Related
So I'm trying to merge two solutions together to form one..
I've been using the code from this answer to remove the "(Incl. Tax)" from the product page option selector for configurable products, and it works well.
As shown in the linked answer, in app/design/frontend/rwd/myTheme/template/catalog/product/view/type/configurable.phtml i've changed the line
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig(); ?>);
</script>
to the following:
<?php // get current drop down string
$currentstring = $this->getJsonConfig();
// create new string with true set to false using str_replace function (string replace)
$newstring = str_replace( '"showBothPrices":true,"','"showBothPrices":false,"', $currentstring );?>
<!-- render dropdown but with new var ($newstring) -->
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $newstring ?>);
</script>
This has the desired result of hiding the (Incl. tax) and makes me happy.
Later, I was asked if we could change the text in the select box from reading "Choose an option" to the name of the option or "Select (option name):"
I found the following answer which works perfectly - it replaces the complete contents of the same file with
<?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>
Now this works great, we can set the option labels to anything we like, but in the process our "(Incl. tax)" returned to ruin my day.
I'm looking for someone to show me how i can merge these two bits of code and make them play nicely together so I can have both custom product option text and prevent the "(Incl. tax)" string from appearing.
Any help most appreciated.
Found my own solution:
Firstly, scrap the code from the first answer, use the code from the second, and then change your varien/configurable.js (or for better better form, create an overridden version) as follows:
var str = option.label;
if(price){
if (this.taxConfig.showBothPrices) {
//CHANGE THIS
//str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
// TO THIS:
str+= ' ' + this.formatPrice(price, true);
} else {
str+= ' ' + this.formatPrice(price, true);
}
}
return str;
please visit link1 , you can see there is option to find shipping is available or not for particular zip code : image1
here shipping charges are working for instock products but not for out-of -stock products.
Form.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/form.phtml
<?php if ($this->isFieldVisible('postcode')): ?>
<li class="item">
<label for="search"<?php if ($this->isFieldRequired('postcode')):?> class="required" <?php endif;?>>
<?php if ($this->isFieldRequired('postcode')):?>
<em>*</em>
<?php endif;?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->__('') ?>
</label>
<div class="search">
<input placeholder="Enter your PIN Code"
class="input-text validate-postcode<?php if ($this->isFieldRequired('postcode')):?> required-entry<?php endif;?>"
type="text" id="estimate_postcode"
name="estimate[postcode]"
value="<?php echo $this->htmlEscape($this->getFieldValue('postcode')) ?>"
onkeydown="if (event.keyCode == 13) { return false;}" />
</div>
</li>
<?php endif; ?>
Script
<script type="text/javascript">
var $ = jQuery.noConflict();
(function($) {
$(document).ready(function(){
$('#estimate_postcode').keydown(function(e){
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var parameters = Form.serializeElements(items, true);
console.log("zipcode onkeypress worked");
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
//disable default enter action
e.preventDefault();
console.log("Enter button was pressed");
$('#shipping-estimate-loading-message').show();
$('#shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('#shipping-estimate-loading-message').hide();
$('#shipping-estimate-results').show();
$('#unique_id').hide();
//$('unique_id').hide();
$('estimate_postcode').val()
}
});
};
});
});
}) ( jQuery );
function estimateProductShipping()
{
var estimationUrl = '<?php echo $this->jsQuoteEscape($this->getEstimateUrl());?>';
var items = $$(['.shipping-estimation-form input',
'.shipping-estimation-form select',
'#product_addtocart_form input',
'#product_addtocart_form select']);
var validationResult = true;
// Check the valid input
if (!items.map(Validation.validate).all()) {
return;
}
var parameters = Form.serializeElements(items, true);
$('shipping-estimate-loading-message').show();
$('shipping-estimate-results').hide();
new Ajax.Updater('shipping-estimate-results', estimationUrl, {
parameters: parameters,
onComplete: function() {
console.log("ajax updater worked");
$('shipping-estimate-loading-message').hide();
$('shipping-estimate-results').show();
// $('#unique_id').hide();
$('unique_id').hide();
$('estimate_postcode').val()
}
});
}
//]]>
</script>
complete code of the file : https://gist.github.com/anonymous/ebe868508b2c21e9c032
result.phtml
app/design/frontend/default/default/template/webdevlopers/productpageshipping/estimate/result.phtml
<div class="block block-shipping-estimate block-shipping-results">
<div class="block-title">
<strong><span>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getShiptitle(); ?>
</span></strong>
</div>
<div class="block-content">
<?php if ($this->getResult()):?>
<dl>
<?php foreach ($this->getResult() as $code => $_rates): ?>
<dt><?php echo $this->getCarrierName($code) ?></dt>
<dd>
<ul>
<?php foreach ($_rates as $_rate): ?>
<li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
<?php if ($_rate->getErrorMessage()): ?>
<?php echo $_rate->getErrorMessage() ?>
<?php else: ?>
<?php
// echo $_rate->getMethodTitle()
?>
<?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
<?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
<!-- sat -->
<p>
<?php echo "Shipping is available";?>
</p>
<p class="vship1">
<?php echo "Selling Price + " . str_replace('.00','',$_excl) . " Delivery ";?>
</p>
<!-- sat -->
<?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
(<?php echo Mage::helper('webdevlopers_productpageshipping')->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
<?php endif; ?>
<?php endif ?>
</li>
<?php endforeach; ?>
</ul>
</dd>
<?php endforeach; ?>
</dl>
<?php else: ?>
<?php //echo $this->getMessagesBlock()->toHtml(); ?>
<?php echo Mage::helper('webdevlopers_productpageshipping')->getResult(); ?>
<?php endif;?>
</div>
</div>
app/code/community/webdevolopers/productpageshiping/Block/estimate/ Result.php
<?php
class WebDevlopers_ProductPageShipping_Block_Estimate_Result extends WebDevlopers_ProductPageShipping_Block_Estimate_Abstract
{
public function getResult()
{
return $this->getEstimate()->getResult();
}
public function hasResult()
{
return $this->getResult() !== null;
}
public function getCarrierName($code)
{
$carrier = Mage::getSingleton('shipping/config')->getCarrierInstance($code);
if ($carrier) {
return $carrier->getConfigData('title');
}
return null;
}
public function getShippingPrice($price, $flag)
{
return $this->formatPrice(
$this->helper('tax')->getShippingPrice(
$price,
$flag,
$this->getEstimate()
->getQuote()
->getShippingAddress()
)
);
}
public function formatPrice($price)
{
return $this->getEstimate()
->getQuote()
->getStore()
->convertPrice($price, true);
}
}
changing the settings in System > Config > Inventory
Easiest way to do this is select all products you want to allow to be backordered, then select Update attributes from the actions drop down and click submit. then shipping problem will not be problem.
I have select box with categories and I want to display subcategories in another select box using ajax an CodeIgniter.
This is part of my view:
<script type="text/javascript">
$(document).ready(function(){
$('#tip_category').change(function(){
msg = 'category_id='+$(this).val();
$.ajax({
type : 'POST',
url : '<?php echo base_url().'admin/tips/ajax_subcategory';?>',
data : msg
});
});
});
</script>
Category:<br/>
<select name="tip_category" id="tip_category">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?>
</option>
<?php endforeach; ?>
</select><br/>
Subcategory:<br/>
<select name="tip_subcategory"
<?php if(isset($subcategories)): ?>
<?php foreach($subcategories as $subcategory): ?>
<option value="<?php echo $subcategory['id'] ?>"><?php echo $subcategory['name'] ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select><br/>
This is part of my controller:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
}
My problem is that i dont know how to send data ($data['subcategories']) back to view and display subcategories. Thx for help !
I think you are just missing the return (in whatever format you need):
return $data;
You can modify your controller to:
public function ajax_subcategory() {
$this->load->model('tips_model');
$data['subcategories'] = $this->tips_model->get_subcategories($this->input->post('category_id'));
return $this->output->set_output($data);
}
I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.
The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink
I created a configurable product, it has three option: color, size and style.
Now in product page, each option has the default text "Choose an Option..." in dropdown, but I want the text should be "Select color", "Select size" and "Select style".
I edited function getJsonConfig() in app\code\core\Mage\Catalog\Block\View\Type\Configurable.php
From:
'chooseText' => Mage::helper('catalog')->__('Choose an Option...'),
To:
'chooseText' => ('Select ').$attribute->getLabel(),
And edit line 39 of the file frontend/base/default/template/catalog/product/view/type/options/configurable.phtml to:
<option><?php echo $this->__('Select ') ?><?php echo $_attribute->getLabel() ?></option>
But the result is not good, it alway show the text "Choose style" in three options.
Please give me a hint for this issue, thank you very much!
My version of the same problem. You need to change only template
catalog/product/view/type/options/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;?>
Note (extracted from comments)
If the selected default value happens not to be "Select %s", replace
$(element).options[0] = new Option(chooseDefaultText, '');
with
$(element).options[0].innerHTML = chooseDefaultText;
I was looking for a more simple way to do this. I didn't want to extend any core files or muck around with extending JavaScript. Instead I parsed the settings JSON, updated the chooseText setting, and converted back to 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>
More information and further examples here.
The only way I think is just to modify the javascript class that populates that dropdowns. As we can see in frontend/base/default/template/catalog/product/view/type/options/configurable.phtml that class is:
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
The file with needed class located in js/varien/product.js
The place where first <option> tag is set up is:
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, '');
...
The variable chooseText used there on line 368. This variable was created in function getJsonConfig() in app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php (you was digging the right way). You need to modify the javascript that I described earlier to achive what you need (based on var attributeId you can assign options with different text to elements you need)
If you only change file configurable.js
It will only change first select when page load
So I must change template file
Get attached file for test.(I just write it to an small extension)
<?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() ?>);
//kevin.qazware#gmail.com 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, ‘’);
It for all attribute set .
simplest answer:
replace js/varien/configurable.js line 172
element.options[0].innerHTML = 'Choose ' + this.config.attributes[attributeId].label;
I extended class Product.Config (method fillselect) by these code:
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,'');
........
It's ok!
<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>
file catalog/product/view/type/options/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;?>
and add one line changeFristText(); after line 171 (element.options[0] = new Option(this.config.chooseText, '');) in file js/varien/configurable.js
It for all attribute set.
This worked for me on CE 1.8.1. It's based off Shein's answer, and addresses the wrong option getting selected on load. I basically just copied/pasted the Product.Config.fillSelect() method from /js/varien/product.js. Within the pasted code I changed:
element.options[0].innerHTML = this.config.chooseText;
to
element.options[0].innerHTML = element.config.label;
This allows keeping product.js unmodified, and just override the method. The only drawback is any future core updates to that method will need migrating.
Since the new code just gets the "label" setting, the data-choose-text attribute on isn't needed on the select tag
<?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;?>