Magento 2 : How to generate Add to Cart URL - magento2

I am looping some specific products on the home page but unable to generate the ADD TO CART URL in magento 2
How to generate ADD TO CART URL when displaying products in loop.

I know it's been a year since this has been touched on, but as I've just done what has been requested, I thought that I may post my solution to help others.
The other answers will work, but only for simple products, where no further input is required (e.g. selecting options). When using getAddToCartUrl(), Magento first checks if the products requires any options to be selected; if it does, then it will simply supply the URL to the product page instead.
To skip all of these checks and directly obtain the add to cart URL, then make use of the Magento\Checkout\Helper\Cart helper instead. If you are within a .phtml file, then this can be utilised simply by calling $this->helper:
$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
From there, you can generate the add to cart URL via getAddUrl(), ensuring you pass the product object as the parameter:
echo $cartHelper->getAddUrl($product)
For it to fully work, you must have a hidden field for the form key as described in the other answers, and if the product in question has compulsory options to choose from (e.g. a configurable product), then make sure you include those fields as well, otherwise you will get redirected to the product page itself, with a message informing the user that options are required.

The excellent solution is to use
$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
and after that
echo $cartHelper->getAddUrl($product);
this give add to cart URL every time
(for a simple product, for a simple product with custom options etc)

use following to generate add to cart URL in magento2:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl = $listBlock->getAddToCartUrl($product);

Add your button code into form with form key.. It will work
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl = $listBlock->getAddToCartUrl($product);
<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post">
<?php echo $block->getBlockHtml('formkey')?>
<button type="submit"
title="Add to Cart"
class="action tocart primary">
<span>Add to Cart</span>
</button>
</form>

You can generate "add to cart" url by following code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl = $listBlock->getAddToCartUrl($_product);

Related

Zend Framework Routing Get Parameters

With Zend Framework 1.10 I'm having a list with articles and an search field.
When typing something in the searchfield and hit the search button it generates me the following url:
https://example.org/products?category=12&no=
On the result of the searchpage you'll find the products matching to the search field.
If there are more than 10 products with the search attribute, there is a next button. For this next button im using the following code to generate the url, which will sadly not extend the already passed arguments (category and no).
<a href="<?php echo $this->url(array('page' => $this->next)); ?>">
<?php echo $this->translate('NextPage'); ?> >
It will redirect me on https://example.org/products
How to add the already passed GET argument from the form?
You can store the GET parameters from the search in the session so when you are requesting with the next url, you can retrieve the parameters previously entered in the search form.

How to call specific Static Blocks inside product descriptions in Magento?

I tried adding a static block to my product description by adding the following code to my description page:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('description02')->toHtml() ?>
This works. But what can I do if I want to use different static blocks for different products? I don't want the same static block to show on all products. Is there way that I can choose which static block shows?
Thanks!
You can proceed as follows :
Create a new text type product attribute from Catalog -> Attributes and add it in used Attribute set from Catalog -> Attribute sets
After this you can add different static block names into this field while adding/editing products.
On product details page use the same you are using above, just make the static block to fetch name from the above created attribute.
Hope this will help.
UPDATE
Lets suppose you created a new attribute named "static_block" then go to Attribute sets, click on the set you are using for the product you want to show the block into.
Drag and drop the static_block from the unassigned to assigned attribute and save Attribute set.
After this create multiple static block block for ex : block_1, block_2
Edit product and in the field assigned above enter block_1 or block_2
After this on product description template i.e catalog/product/view.phtml add code as per following example :
<?php
$blockId = $_product->getData('static_block');
OR
$blockId = $_product->getStatic_block();
Whichever works
echo $this->getLayout()->createBlock('cms/block')->setBlockId($blockId)->toHtml() ?>
you may need to tweak in above code as i have not tested this.
Hope this helps.
1) Create Attribute caller for example static_block_description_code
2) Attach this attribute to proper Attributes Set in Admin section too (set, which You use for you're desired product)
3) go to (in my example) app/design/frontend/PACKAGE/default/template/catalog/product/view/description.phtml and search line responsible to display standard description
I have:`
<div class="std">
<?php echo $this->helper('catalog/output')->productAttribute($this->getProduct(), $_description, 'description') ?>
</div>`
and i've changed it to `
<div class="std block-description">
<?php echo $this->helper('catalog/output')->productAttribute($this->getProduct(), $_description, 'description') ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId($block_description)->toHtml() ?>
</div>`
On top of this file I've added:
<?php $_product = $this->getProduct(); ?>
<?
$block_description = $_product->getData('static_block_description_code');
?>

Custom Form in Custom Joomla Component

I have a basic front-end form within a component that I created using ComponentCreator.
How and where do I direct the form "action"? Where can I handle this so that I am following the MVC design pattern? My form is within a view (default.php)
The form should simply insert to the database upon submission. I don't want to use a form building extension, I have tried these and they don't meet my requirements.
What version of Joomla? Assuming your not using AJAX then just direct to your controller.
<form id='MyForm' method='post' action='index.php?option=com_mycomponent&task=myoperation'>
<input type='text' name='myname'/>
...</form>
Then you will have a function in your controller (controller.php) called myoperation that will process all the things in your form (not forgetting the token of course)
JSession::checkToken('request') or jexit( JText::_( 'JINVALID_TOKEN' ) );
$jinput = JFactory::getApplication()->input;
$add_name = $jinput->get('myname', '', 'STRING');
//whatever you need to do...
//add to model if you wanted to add name to DB
$model = &$this->getModel();
$model->updateDB(...);
Then create function updateDB in model.
This is a rough example with Joomla 2.5 but should work with 3.x. Hope this helps.

How to reuse codeigniter form on multiple pages

I have a simple search form I want to reuse across multiple pages in my codeigniter application. For example, right now I have a search form in the sidebar and I'm planning on displaying that sidebar on the index, about, and other pages.
I want to have the form validation display errors on the same page the users submits the form from.
For example:
User is on About page.
User submits form with invalid data
User sees error in the sidebar on the About page
and
User is on Index page.
User submits form with invalid data
User sees error in the sidebar on the Index page
But I'd like to reuse that form validation logic. I just want it to display the error on whichever page the user posted from.
Any ideas how to do that? Sorry for the noob question, I'm pretty new to CI.
Here you have to think globally.
Step.1 : Make one view file : display.php
which contains :
<div id = "main">
<div id = "header">
[load header file here]
</div>
<?php
if(validation_errors() != '') {
?>
<div id = "error">
<?=validation_errors()?>
</div>
<?php
}
?>
<div id = "content">
<?=$page?>
</div>
<div id = "footer">
[load footer file here]
</div>
</div>
Step.2 : About us Page.(controlller)
.... Your data ....
at end of controller function
$data['page'] = 'aboutus';
$this->load->view('display',$data);
With regards to your comment on the above question you could use Flash data
With the assumption that you have the session library loaded, here is a helper function.
function last_page($page = null){
$ci = get_instance();
if($page === null)
return $ci->session->flashdata('last_page');
$ci->session->set_flashdata('last_page', $page);
}
then you can call last_page('about'); at the top of the about page, and then when you want to find out what the last page you were on was you can just call last_page(); with no params.
In the User Guide, there's different ways to configure sets/groups of rules. Then you can simply have something like:
if ($this->form_validation->run('signup') == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
Which will run your "signup" group of validations. To me, this is the cleanest way to achieve reusable validation rules.
This is a perfectly valid question.
I'm not a PHP expert, nor a CI expert, but the fact is sometimes you want to post to a controller that didn't create the view from which you're posting. Which means posting back to itself is not going to work.
I came across this post on the Ellislab forum:
http://ellislab.com/forums/viewthread/217176/
On this page, There are 2 methods of going about it. Both of which use flashdata and both of which are totally valid, IMHO.
The first: create a helper function
http://ellislab.com/forums/viewreply/1003010/
The second: extend the CI_Form_Validation Class.
http://ellislab.com/forums/viewreply/1047536/
The second is the way I went as it seems cleanest although some may argue whether the form validation class should know anything about flash data.

question about CodeIgniter urls

I am using an application (a blog) written using the CodeIgniter framework and would like to search my blog from my browsers location bar by adding a string to the end of my blogs url like this:
http://mysite.com/blog/index.php/search...
As you can see in the example above I am not really sure how to format the rest of the url after the search part so I am hoping someone here might be able to point me in the right direction.
This is what the form looks like for the search box if that helps at all.
form class="searchform" action="http://mysite.com/blog/index.php/search" method="post">
<input id="searchtext" class="search_input" type="text" value="" name="searchtext">
<input type="submit" value="Search" name="Search">
</form>
Thx,
Mark
Since your form is posting to http://mysite.com/blog/index.php/search, I'm assuming this 'search' controller's default function is the one your are attempting to submit your data to. I think that the easiest way to do this would be to just grab the post data inside of the controller method you're posting to. Example:
function search()
{
$search_params = $this->input->post('search_text');
}
Then you would have whatever the user input stored as $search_params, and you can take actions from there. Am I misunderstanding what you're asking?
It seems like you're kind of discussing two different approaches. If you wanted to make a request to
mysite.com/blog/index.php/search&q=what_I_am_looking_for
This is going to call the search controllers default method (which is index by default). If you wanted to use the URL to pass parameters like that you would go to your function in the search controller and do:
print_r($this->input->get('q'));
This will print out "what_am_I_looking_for".
An easier approach in my opinion would be to:
1. Create a view called "search_view" with the HTML content you pasted above, and have the form "action" http://www.mysite.com/blog/index.php/test/search
Create a controller called "Test" that looks like the following:
class Test extends CI_Controller {
function search()
{
$search = $this->input->post('searchtext');
print_r($search);
}
public function display_search()
{
$this->load->view('search_view');
}
}
Visit http://www.mysite.com/blog/index.php/test/display_search in your browser. This should present you with the form you placed in search_view.php. Once the form is submitted, you should be sent to the search function and print out the variable $search, which will have whatever text you submitted on that form.
If this isn't what you were looking for then I am afraid I do not understand your question.