I know in Magento 1 you can add product to cart by id via:
<a href="<?php echo Mage::getUrl("checkout/cart/add/product/4671/")?>
How do I do the same thing in Magento 2?
//you can use like this
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productHelper = $objectManager->get('\Magento\Catalog\Model\Product');
// get product object if you are not having
$product = $productHelper->load($id);
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
echo $listBlock->getAddToCartUrl($product);
Related
How to change add cart button text to backorder text while backorder product?
I was tried this but not working
if($_product->getStockItem()->getBackorders()!=0){
$buttonTitle=$this->__('Backorder');
}
<?php
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $obj->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$stockitem = $stockRegistry->getStockItem($_product->getId(),$_product->getStore()->getWebsiteId());
if($stockitem->getBackorders() == 1):
$buttonTitle = __('Backorders');
else:
$buttonTitle = __('Add to Cart');
endif;
?>
We currently using GTM for all our tracking codes.
To setup Facebook Dynamic ads and Facebook pixel, I need to collect events like AddToCart, Purchase etc.
<script>
fbq('track', 'Purchase', {
content_ids: ['1234', '4642', '35838'],
content_type: 'product'
value: 247.35,
currency: 'USD'
});
</script>
How to get Magento's SKUs and Cart value and pass to Facebook tracking code using Google Tag Manager?
For cart event, you can get the information using the following snippet code
<?php $quote = Mage::getSingleton('checkout/cart')->getQuote();
$productIds = "";
foreach($quote->getAllItems() as $item):
if($item->getParentItemId()) continue;
if (strlen($productIds)==0){
$productIds = "'".$item->getSku()."'";
}
else{
$productIds = $productIds.",'".$item->getSku()."'";
}
endforeach;
$pixelTotal = $quote->getBaseGrandTotal();
$pixelCurrency = $quote->getQuoteCurrencyCode();?>
<script>
fbq('track', 'Cart', {
content_ids: <?php echo $productIds;?>,
content_type: 'product'
value: <?php echo $pixelTotal;?>,
currency: <?php echo $pixelCurrency;?>
});
</script>
For purchase event, you can get the information using the following snippet code
<?php $orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$productIds = "";
foreach($order->getAllItems() as $item):
if($item->getParentItemId()) continue;
if (strlen($productIds)==0){
$productIds = "'".$item->getSku()."'";
}
else{
$productIds = $productIds.",'".$item->getSku()."'";
}
endforeach;
$pixelTotal = $order->getBaseGrandTotal();
$pixelCurrency = $order->getOrderCurrencyCode();?>
<script>
fbq('track', 'Purchase', {
content_ids: <?php echo $productIds;?>,
content_type: 'product'
value: <?php echo $pixelTotal;?>,
currency: <?php echo $pixelCurrency;?>
});
</script>
For Contact us event, use the following observer event controller_action_postdispatch_contacts_index_post
Config.xml
<controller_action_postdispatch_contacts_index_post>
<observers>
<custom_module_contact_submit_after>
<type>singleton</type>
<class>custom_module/observer</class>
<method>ContactPost</method>
</custom_module_contact_submit_after>
</observers>
</controller_action_postdispatch_contacts_index_post>
Observer.php
/**
* Triggers on contact us form
* #return void|Varien_Event_Observer
*/
public function ContactPost() {
Mage::getSingleton('core/session')->setContactPost('1');
}
header.phtml
if (Mage::getSingleton('core/session')->getContactPost()==1){
fbq('track', 'Lead');
}
For complete registration event, use the following observer event customer_register_success
Config.xml
<customer_register_success>
<observers>
<custom_module_customer_register_success>
<type>singleton</type>
<class>custom_module/observer</class>
<method>CustomerRegister</method>
</custom_module_customer_register_success>
</observers>
</customer_register_success>
Observer.php
/**
* Triggers on contact us form
* #return void|Varien_Event_Observer
*/
public function CustomerRegister() {
Mage::getSingleton('core/session')->setRegistered('1');
}
header.phtml
if (Mage::getSingleton('core/session')->getRegistered()=="1"){
fbq('track', 'CompleteRegistration');
}
For Checkout events (CheckoutInitiate and PaymentInfo), you can add them on onepage.pthml
CheckoutInitiate can be done on the page load and PaymentInfo can be triggered on Payment.prototype.save function
If you are a Magento developer then above events can easily be implemented but if not then I would recommend to use the following third party modules -:
For Magento 1
https://www.scommerce-mage.com/magento-google-tag-manager-enhanced-ecommerce-tracking.html
For Magento 2
https://www.scommerce-mage.com/magento-2-google-tag-manager-enhanced-ecommerce-tracking.html
The best way to go about this is a combination of datalayer variables and one custom html tag.
when the user clicks on the purchase button you push an event to the datalayer that has the information you need to pass along to facebook. something like
datalayer.push({
event:'PURCHASE_BUTTON_CLICKED',
PURCHASE_BUTTON_CLICKED: {
ids:['1234', '4642', '35838'],
type:'product,
value: getTotalValue(),
currency: 'USD'
})
then inside GTM use one or several (i recommend several) different datalayer variables referencing different attributes of this datalayer object. you can use these variables in your custom html tag by wrapping them in double curly braces as shown in the image. all that is left is to add a trigger to the custom html tag.
try and feed as much as you can into the datalayer and gtm so that you can reuse all these variables to send off any number of tags.
I am working with configurable product, I want simple product id of configurable product on cart.phtml, I am using this code
<?php foreach($this->getItems() as $_item): ?>
$_product = $_item->getProduct();
echo $_product->getId();
<?php endforeach ?>
but it always gives main product id, but I need its simple product id , any one help please.
I found solution
<?php foreach($this->getItems() as $_item): ?>
$_COnfigproduct = $_item->getProduct();
$simpleProduct=Mage::getModel('catalog/product')->loadByAttribute('sku',$_item->getSku());
echo $simpleProduct->getId();
<?php endforeach ?>
it works for me.
you can get simple product id associated to configurable product on cart page..
by below code
<?php $_item = $block->getItem();
$product = $_item->getProduct();
if($product->getTypeId() == 'configurable') {
echo $_item->getOptionByCode('simple_product')->getProduct()->getId();
} ?>
I am trying to build a simple CMS and have run into a problem I hope you can help me with.
I have a public display page that fetches data from a MySQL database. This works fine.
I also have an admin page where the data is loaded into a form field so that a maintainer can change it.
My problem is that after hitting the submit button, the data is successfully sent to the DB but I cannot find a way to get the form to show the latest data. It is always one submit step behind.
Sample code:
<?php
//retrieve data from MySQL
mysql_connect('localhost:3306','dundryor_show','show1');
mysql_select_db('dundryor_stofl_test');
$query = mysql_query("SELECT * FROM form_test where id = '0'");
$output = mysql_fetch_array($query);
$user_text = $output['user_text'];
mysql_close();
//display form and populate
echo '<form method="post">';
echo 'This text is stored in the database and can be changed by the user:<p>';
echo '<input type="Text" name="user_text" size="50" value="';
echo $user_text;
echo '"><br><input type="Submit" name="update" value="Update Database">';
echo '</form>';
//process submit event, write new data to DB
if ($_POST['update'])
{
$user_text = $_POST['user_text'];
mysql_connect('localhost:3306','dundryor_show','show1');
mysql_select_db('dundryor_stofl_test');
mysql_query("UPDATE form_test set user_text = '$user_text' where id = '0'");
mysql_close();
}
?>
As an added complication, the file name needs to be dynamic, i.e. not just "myform.php" but "myform.php?option=this_can_be_anything". So a reference to a static URL would not work.
Any suggestions much appreciated.
I have have a view in which there's a form that manages products (either add new product or -if an id passed- editing an existing one). If an id is passed then the form action should be eg 'admin/product/manage/5', if no id passed then it should be like this 'admin/product/manage'.
<?php echo form_open('admin/product/manage/{optional product id}', array('class' => 'ajax-form')); ?>
I have also created and this route:
$route['admin/product/manage'] = "admin/product/manage";
$route['admin/product/manage/(:num)'] = "admin/product/manage/$1";
How can I make my form action work correctly? is it possible to put inside the action the route somehow??
This is my Controller:
public function manage($id = NULL){
//fetch a single product to edit or create a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['vers'] = $this->product_version_model->get_by('product_id',$id);
} else {
$data['prod'] = $this->product_model->make_new();// this returns $product->product_name = ''; in order to be empty the input field and not throughing errors
}
$this->product_model->save_product();
$this->product_version_model->save_version();
// load the view
$this->layout->view('admin/products/manage', $data);
}
This is my view:
<?php echo form_open('admin/product/manage', array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<?php echo form_close() . PHP_EOL; ?>
You need to declare both possible routes in order of importance, so:
$route['admin/product'] = "admin/product/manage";
$route['admin/product/(:num)'] = "admin/product/manage/$1";
From the Codeigniter Docs:
Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
Edit:
According to the changes you have made to your question I can say the following:
First of all isset() returns boolean only, so you don't need the type check "=== true". isset($id) is sufficient.
In order to have your form action set to the id you need to include it either in a hidden field or in the action itself.
So for example:
$action_id = (isset($id) ? '/'.$id : ''); // Using ternary operators here
echo form_open('admin/product/manage'.$action_id, array('class' => 'ajax-form'));
and add the id to the view data in your controller:
$data['id'] = $id;
As a side note: In order to comply with SoC (Separation of Concerns) you'd prepare all data in your controller (with e.g. models all having their own task) and pass the processed data to the view instead of partially generating data in the view itself.