How do I get the SKU no to change once the the product attribute of an item is selected.
enter image description here
To get sku of selected associated product on configurable product page, please paste the following code in app/design/frontend///template/catalog/product/view/type/options/configurable.phtml in side the script:
spConfig.getIdOfSelectedProduct = function()
{
var existingProducts = new Object();
for(var i=this.settings.length-1;i>=0;i--)
{
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config)
{
for(var iproducts=0;iproducts<selected.config.products.length;iproducts++)
{
var usedAsKey = selected.config.products[iproducts]+"";
if(existingProducts[usedAsKey]==undefined)
{
existingProducts[usedAsKey]=1;
}
else
{
existingProducts[usedAsKey]=existingProducts[usedAsKey]+1;
}
}
}
}
for (var keyValue in existingProducts)
{
for ( var keyValueInner in existingProducts)
{
if(Number(existingProducts[keyValueInner])<Number(existingProducts[keyValue]))
{
delete existingProducts[keyValueInner];
}
}
}
var sizeOfExistingProducts=0;
var currentSimpleProductId = "";
for ( var keyValue in existingProducts)
{
currentSimpleProductId = keyValue;
sizeOfExistingProducts=sizeOfExistingProducts+1
}
if(sizeOfExistingProducts==1)
{
alert("Selected product is: "+currentSimpleProductId)
}
}
Now add onchange event to your dropdown in same page:
onchange="spConfig.getIdOfSelectedProduct()"
First code will alert simple associated product id. You can use it in below code now.
jQuery.ajax({
type: "POST",
url: "<?php echo $this->getBaseUrl()?><module_front_name>/<controller_name>/<action_name>/",
data:"id="+currentSimpleProductId,
success: function(msg)
{
alert(msg);
//var data = JSON.parse(msg);
//alert(data.id);
}
});
Now, go to controller file which you have used above and create a new action with name Action and put below code in it:
public function <action_name>Action()
{
$productId = $_REQUEST['id'];
/*$productId is your selected product id. do what ever you want to do here.*/
$product = Mage::getModel('catalog/product')->load($productId);
$productsku = $product->getSku();
$arraygroup = array("sku"=>$productsku);
echo json_encode($arraygroup);
}
Now you can use this information in your phtml file to show sku.
Please let me know if anything is unclear.
Go to Magento admin
In catalog > Manage attribues find sku and look for similar to "Visible on Product View Page on Front-end"
This should remove the sku from product page
Find the configurable product template and insert where you would like to have your SKU
echo $product->getSku()
Related
I am working with Magento. all I want just a button that add a product to cart and then go to check out page not to view cart. means I want direct order for the registered users. and I am working in PORTO Magento theme
I have tried it by creating copy of function addAction of cartController.php(app/code/core/checkout/controllers/) to myaddAction().
added below JS to end view.phtml(app/design/frontend/your package/your template/template/catalog/product/view.phtml)
productAddToCartForm.submitmy = function(button, url){
replaceURL = url.replace("add/","myadd/");
if(this.validator) {
var nv = Validation.methods;
delete Validation.methods['required-entry'];
delete Validation.methods['validate-one-required'];
delete Validation.methods['validate-one-required-by-name'];
// Remove custom datetime validators
for (var methodName in Validation.methods) {
if (methodName.match(/^validate-datetime-.*/i)) {
delete Validation.methods[methodName];
}
}
if (this.validator.validate()) {
if (url) {
this.form.action = replaceURL;
}
this.form.submit();
}
Object.extend(Validation.methods, nv);
}
}.bind(productAddToCartForm);
and changed addaction to myaddAction in cart controller and also changed
$this->_goBack();
to
$this->_redirect('checkout/onepage');
return;
But I am getting an error undefined funtion,
productAddToCartForm.submitmy
please hope someone help.
I would create an observer on add_to_cart_after and then set a redirect here. Something as simple as:
$response = $observer->getResponse();
$url = Mage::helper('checkout/url')->getCheckoutUrl();
$response->setRedirect($url);
die();
I'm looking to create "Addon Products" in Magento. What I mean is: If the product were a Greeting Card, and you were to add that to your cart, you might be presented with options on the checkout page to add an "Envelope" or "Stamps". These would be separate products with their own prices, however, they would not be available otherwise in the store. In other words, some sort of "Linked / Child Products" that only become available once the "Parent" product has been added.
Does this sort of product configuration exist within Magento? Doesn't seem to be a Bundled Product.
Yes Magento does this out of the box.
Against each product assign 'cross sell' products, using the cross sell tab on the left. When you first get to it, if the list is empty press the 'reset filter' button to show all the products in the store. Find the ones you want and put a tick next to them, then click save.
The block you are after is;
<block type="checkout/cart_crosssell" name="checkout.cart.crosssell" as="crosssell" template="checkout/cart/crosssell.phtml"/>
Which most template load within "content" in the layout/checkout.xml layout file of your theme,
<checkout_cart_index translate="label">
////
<reference name="content">
///// HERE
</reference>
/////
</checkout_cart_index>
And then add this to the checkout/cart.phtml template (if it's not there already);
<?php echo $this->getChildHtml('crosssell') ?>
But you can add it to wherever you wish.
To handle these products not appearing elsewhere, set their visibility to 'catalog' and either put them in a category that isnt visible or dont add them to a category.
TO ANSWER YOUR SECOND QUESTION...
You asked how you could remove all 'add on' items from the basket if there are no 'main product' items in the basket. Here is a quick solution that will do this.
Create a custom select product attribute, give it ID code 'product_type_var' and give it 2 options 'Main Product' and 'Addon Product'. Add it to your product attribute set and set the values against the appropriate products.
You can then run the following code against the basket. Ideally you would create a module with an event observer - but for the sake of this example, you could also place this code at the top of
app/design/frontend/XXX/YYY/template/checkout/cart.phtml
Here's the code;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$needsAction = true;
$toRemove = array();
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$productLoad = Mage::getModel('catalog/product')->load($product->getId());
$customVariable = $productLoad->getResource()->getAttribute('product_type_var')->getFrontend()->getValue($productLoad);
if($customVariable == 'Main Product') {
$needsAction = false;
break; // No need to do anything
}
if($customVariable == 'Addon Product') {
$toRemove[] = $productLoad->getId(); // Build list of addon IDs
}
}
if($needsAction && (!empty($toRemove))) {
// There are no Main Products and 1 or more Addons
foreach($toRemove as $removeId) {
$quote->removeItem($removeId)->save();
}
}
Revision 3
To make sure any 'addon' products only remain in the cart if they relate to a specific 'main product' found in the cart, try this;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$allowedUpsells = array();
$upsellsInCart = array();
$allIdsInCart = array();
foreach ($quote->getAllItems() as $item) {
$product = $item->getProduct();
$productLoad = Mage::getModel('catalog/product')->load($product->getId());
$customVariable = $productLoad->getResource()->getAttribute('product_type_var')->getFrontend()->getValue($productLoad);
if($customVariable == 'Main Product') {
$allIdsInCart[] = $productLoad->getId(); // Build list of all products in the cart
$upsells = $productLoad->getUpSellProductCollection(); // Get this products available upsells
foreach($upsells as $upsell) {
$allowedUpsells[] = $upsell->getId(); // Build full list of allowed addon IDs
}
}
if($customVariable == 'Addon Product') {
$allIdsInCart[] = $productLoad->getId(); // Build list of all products in the cart
$upsellsInCart[] = $productLoad->getId(); //Build full list of addon IDs
}
}
if(!empty($upsellsInCart)) { // Upsells might need attention
$allowedVsInCart = array_intersect($allowedUpsells, $allIdsInCart); // Remove other upsells that are avaiable to the product but not in the cart
$toBeRemoved = array_diff_assoc($allowedVsInCart, $upsellsInCart); // Now find the products in the cart that shouldnt be
if(!empty($toBeRemoved)) {
foreach($toBeRemoved as $removeId) {
$quote->removeItem($removeId)->save();
}
}
}
I'm trying to use jtable plugin in framework codeigniter but i got a problem. I'm confused how to pass variable from view (jtable javascript code) to controller and to pass json_encode from controller to view.
Here are my code.
in my view page(Attendance_view.php).
[html code]
<input style="width:100px" type="text" id="from" name="from" value="<?php echo date("Y-m")."-01";?>">
[js code]
//Prepare jTable
var base_url ="<?=base_url()?>";
$('#TableContainer').jtable({
title: 'Attendance',
paging: true,
sorting: true,
defaultSorting: 'month ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
actions: {
listAction: '<?=base_url()?>index.php/Attendance_controller/listRecord',
createAction: '<?=base_url()?>index.php/Attendance_controller/create',
updateAction: '<?=base_url()?>index.php/Attendance_controller/update',
deleteAction: '<?=base_url()?>index.php/AttendanceAbsensi_controller/delete'
},
....//another field here
});
//Load attendance from server
$('#TableContainer').jtable('load',{
month:$("#from").val()
});
in my controller(Attendance_controller.php)
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
$data['jTableResult']= json_encode($jTableResult);
$this->load->view('Attendance_view',$data['jTableResult']);
}
in my model (Attendance_action.php)
function list_record()
{
//get post variable
$date=$this->input->post('month'); // i can't get the value.
//Get record count
$result = //my query here[select "some data" from "mytable" where month='$date']
$recordCount = mysql_num_rows($result);
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
return $jTableResult;
}
When i load the controller page, the error message from jtable occured "An error occured while communicating to the server". Please help. thanks.
Why your using jtable .can you use Jquery Datatbles here having ignited Datatables Library using that one we can implement crud functionality simple
you can interest please check it once the bellow url
https://github.com/IgnitedDatatables/Ignited-Datatables/
http://datatables.net/examples/data_sources/server_side.html
https://ellislab.com/forums/viewthread/160896/
i am personal y like jquery data-tables.just check it once
First load view page in separate function .In that page you call call your crud Urls
Change like this your controller
function list()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
print_r(json_encode($jTableResult));
}
Note : Can you please check it once this here mentioned clearly how to implement this one
http://jtable.org/GettingStarted
i want to share my code. Now the problem fixed. I just change the controller code like this. Add "exit();" in controller.
function index()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Antendance_action->list_record();
print_r(json_encode($jTableResult));
exit();
}
I am trying to create dynamic dropdown of category and on selection of this category sub-category dropdown should appear. I have done this using OOP PHP but really having tought time with codeigniter.
Firstly I have created this category dropdown
<?php
$js =' onChange="callAjaxFunction(this.value)"';
echo form_dropdown('category', $categories, null, $js); ?>
Javascript to show sub-category
<script>
// JavaScript Document
var enableCache = false;
var jsCache = new Array();
var AjaxObjects = new Array(new sack(),new sack());
function ShowContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = AjaxObjects[ajaxIndex].response;
if(enableCache){
jsCache[url] = AjaxObjects[ajaxIndex].response;
}
AjaxObjects[ajaxIndex] = false;
document.getElementById("ajax_container").innerHTML = '';
}
function ShiftChanger(divId,url,id) {
//to show the div
document.getElementById(divId).innerHTML="";
if(enableCache && jsCache[url]){
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
var ajaxIndex = AjaxObjects.length;
AjaxObjects[ajaxIndex] = new sack();
AjaxObjects[ajaxIndex].requestFile = url+"?id="+id;
document.getElementById("ajax_container").innerHTML = '<img src=ajax_loader.gif hspace=10 vspace=10 />'; AjaxObjects[ajaxIndex].onCompletion = function(){ ShowContent(divId,ajaxIndex,url+"?id="+id);};
AjaxObjects[ajaxIndex].runAJAX();
}
function callAjaxFunction(value)
{
ShiftChanger('shiftcontainer','ajax_category.php',value);
}
</script>
But this is not working. As you can see ajax_category.php is not being able to pass. I think it should be done with controller, I had tried that also but nothing seems as working. I am really stuck with this. Please anyone with little help. Really getting depressed with it :(.
I am building a static page that contains several products. I took the static HTML that was generated by one of my product pages and added all the other products to this page. Each product has a radio button and the customer can only select one of them. The qty will always be 1.
How do I submit the product_addtocart_form?
I modified the form submit function like this:
var productAddToCartForm = new VarienForm("product_addtocart_form");
productAddToCartForm.submit = function(){
if(this.validator.validate()) {
var product_id = jQuery("input[name='product']:checked").val();
this.form.action = "/store/checkout/cart/add/product/"+product_id+"/qty/1";
this.form.submit();
}
}.bind(productAddToCartForm);
But it doesn't always work. If I modify the action to this, which is the same as my product page but changing the product_id:
this.form.action = "/store/checkout/cart/add/uenc/aHR0cDovL3N0YWdpbmcuY2ljLnNjaWMuY29tL3N0b3JlL3B1YmxpY2F0aW9ucy8yNS1tb3N0LWlubm92YXRpdmUtYWdlbnRzLWluLWFtZXJpY2EuaHRtbD9fX19TSUQ9VQ,,/"+product_id+"/qty/1";
It also works inconsistenty.
How do I do this??????
Just post the form as an action="get" to /checkout/cart/add
Name your radio field product and another hidden field named qty. Pass the Magento product ID to product and the quantity to qty