Search results for: 'related products'
Results in Category pages.
Results in Magefan Blog.
-
Display Related products on magento
As a magento developer display related product on product view page.It’s easy to show related product by following few easy steps. First we will have to add products to a particular product as related product. Screen shows product added as related product
After selecting products it will show on your product view page if you can`t view related product on it .Do following steps it`s very easy to follow all the best friends.
1)Open catalog.xml
catalog.xml file available in .
{magento root}/app/design/frontend/default/{your theme}/layout/catalog.xml .
If you not have the file just copy file from
{magento toot}/app/design/frontend/base/default/layout/catalog.xml
to your theme i already mention the path.
2) Remove & Add some xml in catalog.xml
Search catalog_product_view in
{magento root}/app/design/frontend/default/{your theme}/layout/catalog.xml
. Command or remove the following line from there .Search in catalog.xml "catalog.product.related" in appropriately line 258 under <reference name="right"> .
<block type=“catalog/product_list_related” name=“catalog.product.related”before=“-” template=“catalog/product/list/related.phtml”/>
add following line in catalog.xml . Search in catalog.xml "<reference name="content">" in appropriately line 189 . Below "<block type="catalog/product_view"..........>" this linl add following line.
<block type=“catalog/product_list_related” name=“catalog.product.related”before=“-” as="catalog_product_relate" template=“catalog/product/list/related.phtml”/>
3) Adding related product in product view page.
Adding some code in view.phtml available in
{magento root}/app/design/frontend/default/{your theme}/template/catalog/product/view.phtml
If you not have the file just copy file from
{magento toot}/app/design/frontend/base/default/template/catalog/product/view.phtml .
Add following line in where you want to view.
<?php echo $this->getChildHtml('catalog_product_relate');?>
4) Related Product view
-
Magento 2: How to apply OR conditions to searchCriteria filter
Third Party Platform interact with Magento 2 by API. When you are working for API related stuff and using SearchCriteriaBuilder Object for your query and if you want to apply OR conditions for custom query, You need to define setFilterGroups([Object]) for OR query.
Whenever you are dealing with SearchCriteriaBuilder in Magento 2, You might be need to query with OR conditions for custom requirement, You can give OR conditions to Magento\Framework\Api\SearchCriteriaBuilder by simple code snippets.
Let’s imagine, We built a query using OR conditions for Products.
Fetch collection of only those products whose sku is like `MSH01%` OR `type_id` is equal to simple.
<?php namespace Rbj\Training\Block; class Training extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, \Magento\Framework\Api\FilterBuilder $filterBuilder, \Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder, array $data = [] ) { $this->customerRepository = $customerRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->filterBuilder = $filterBuilder; $this->filterGroupBuilder = $filterGroupBuilder; parent::__construct($context, $data); } /** * OR condition for searchCriteriaBuilder */ public function applyOrCondition() { $filter_1 = $this->filterBuilder ->setField('sku') ->setConditionType('like') ->setValue('MSH01%') ->create(); $filter_2 = $this->filterBuilder ->setField('type_id') ->setConditionType('eq') ->setValue('simple') ->create(); $filter_group = $this->filterGroupBuilder ->addFilter($filter_1) ->addFilter($filter_2) ->create(); // add filter group to setFilterGroups() $searchCriteria = $this->searchCriteriaBuilder ->setFilterGroups([$filter_group]) ->create(); $products = $this->productRepository->getList($searchCriteria)->getItems(); return $products; }Using Magento\Framework\Api\FilterBuilder class, You need to create filterBuilder for your separate field.
using Magento\Framework\Api\Search\FilterGroupBuilder class, apply AND conditions to addFilter( ) with filterGroupBuilderobject.
Now Our searchCriteriaBuilder instance is ready for fetch collection of products,
$products = $this->productRepository->getList($searchCriteria)->getItems();
gives the result of our OR query for a products. -
Magento Wordpress Related Post
Magento Wordpress Related Post using fishpig integration display Related Post
-
Magento 2 How to Add Product To Cart With Custom Price
With the support of seamless customization and integrations, Magento 2 e-commerce stores can serve excellent experiences to customers. In many cases, the store owners are willing to allow the shoppers to add the product to the cart with a custom price.
Frequently, the store owner is prepared to set a fixed product pricing even if the consumer selects various options/add-ons from the front end for all or some specific products. Instead of manually changing all store products, we’ll need to manually code to override all store product prices with your preferred custom price.
In this article, I will instruct you to set a custom price of the product when adding the product to the cart by using Observe.
Let’s explore two straightforward steps below!
Step 1: Create Events/xml File
Firstly, you need to create
events/xmlin the folderMageplaza/HelloWord/etc/frontendand use eventcheckout_cart_product_add_after<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="checkout_cart_product_add_after"> <observer name="customprice" instance="Mageplaza\HelloWord\Observer\CustomPrice" /> </event> </config>Step 2: Create CustomPrice.php File
Now, you have to create
CustomPrice.phpfile that overrides your price in theObserverFolder.<?php /** * Mageplaza Hello CustomPrice Observer * * @category Mageplaza * @package Mageplaza_HelloWord * */ namespace Mageplaza\HelloWord\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\RequestInterface; class CustomPrice implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $item = $observer->getEvent()->getData('quote_item'); $item = ( $item->getParentItem() ? $item->getParentItem() : $item ); $price = 100; //set your price here $item->setCustomPrice($price); $item->setOriginalCustomPrice($price); $item->getProduct()->setIsSuperMode(true); } }Note: According to your need for setting a custom price for one or more products, you can manipulate this by adding conditions.
Conclusion
That is the detailed instruction on how to add the product to the cart with the custom price in Magento 2. Let us know if you have any questions by commenting below!
-
Magento download product links opening in browser
I have a downloadable product. After I order the product and when my order is complete, I am able to download the product links from ‘My Downloadable Products’ menu in Customer Account section.
I go to ‘My Downloadable Products’ section and I click on the links to download. However, the PDF file opens in the browser itself. I would like to have the feature that asks to download / save as instead of directly opening in the browser.
It is fine with ZIP files. It asks to download and save. However, the PDF files, Images, HTML files, etc. are directly opened in the browser. I want them to download and save. So, a window appearing and asking to save and download the file is what I want.
Solution:
There is a very easy solution to this.
By default, Magento has the Configuration settings to make those files open in the browser itself. You can adjust the configuration settings in Magento Admin to ask for download files instead of opening in the browser.
- Go to System -> Configuration -> Catalog -> Downloadable Product Options -> Use Content Disposition
- Change the setting from inline to attachment.Now, whenever you click the downloadable link, a pop window will always open and ask to download or open the file.
Hope it helps. Thanks.
-
Magento Product Email Notification
Magento Product email Notification to send mail to subscriber to new product created and every time
product save with the price changes . You can alert your subscriber about the your new product or
the product price change . It have the following option to send notification .- Have an enable/disaple notification .
- Generate your own design email template .
- Email from name .
- Email from your email .
It have the feature to send newsletter of product notification manualy .
Feature
- Working with magento newsletter .
- Send mail to every subscriber.
- First time product save after "Mage Product Email Notification" extension installed .
- Every time product price changed increase or decrease .
- Mail sent only a product visibility "Enables" & Product have a stock .
- Manual send Newsletter of product notification .
- Related Product also added to email .
- Manual feach the subscriber log .
- Cron to Send mail .
- limit Daily mail .
- Limit to Daily mail per eamil .
- Limit to Mail Per cron .
- Send Mail by Email Order by Descending .
- Send Mail by Price Order by Descending .
- Send Mail by Product ID Order by Descending .
Newsletter Variable
Newsletter Variable can use in Transactional Emails
- {{var items_html}} get Product detail { Name , Description , Price } .
- {{var items_related}} get 3 Related Product detail { Name , Description , Price } .
-
Magento 2: Get all shopping cart items, subtotal, grand total, billing & shipping address
This article shows how to get shopping cart items/products, subtotal and grand total of cart, and shipping and billing address entered while doing checkout in Magento 2.
I will be using both Dependency Injection (DI) and Object Manager in the below example code.
Using Object Manager
– Get products id, name, price, quantity, etc. present in your cart.
– Get number of items in cart and total quantity in cart.
– Get base total price and grand total price of items in cart.
– Get billing and shipping addresses entered during checkout.Get all items information in cart
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); // retrieve quote items collection $itemsCollection = $cart->getQuote()->getItemsCollection(); // get array of all items what can be display directly $itemsVisible = $cart->getQuote()->getAllVisibleItems(); // retrieve quote items array $items = $cart->getQuote()->getAllItems(); foreach($items as $item) { echo 'ID: '.$item->getProductId().'<br />'; echo 'Name: '.$item->getName().'<br />'; echo 'Sku: '.$item->getSku().'<br />'; echo 'Quantity: '.$item->getQty().'<br />'; echo 'Price: '.$item->getPrice().'<br />'; echo "<br />"; }Get total items and total quantity in cart
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $totalItems = $cart->getQuote()->getItemsCount(); $totalQuantity = $cart->getQuote()->getItemsQty();Get subtotal and grand total price of cart
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $subTotal = $cart->getQuote()->getSubtotal(); $grandTotal = $cart->getQuote()->getGrandTotal();Get billing and shipping addresses
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); $billingAddress = $cart->getQuote()->getBillingAddress(); echo '<pre>'; print_r($billingAddress->getData()); echo '</pre>'; $shippingAddress = $cart->getQuote()->getShippingAddress(); echo '<pre>'; print_r($shippingAddress->getData()); echo '</pre>';Using Dependency Injection (DI)
In the above code in Object Manager, I have used object of class
\Magento\Checkout\Model\Cartto fetch shopping cart items and totals. But, we can also use the object of class\Magento\Checkout\Model\Session.Here is your block class code:
namespace YourCompany\YourModule\Block; class YourModule extends \Magento\Framework\View\Element\Template { protected $_cart; protected $_checkoutSession; public function __construct( \Magento\Backend\Block\Template\Context $context, ... \Magento\Checkout\Model\Cart $cart, \Magento\Checkout\Model\Session $checkoutSession, array $data = [] ) { $this->_cart = $cart; $this->_checkoutSession = $checkoutSession; parent::__construct($context, $data); } public function getCart() { return $this->_cart; } public function getCheckoutSession() { return $this->_checkoutSession; } }Your
.phtmltemplate code:// Get all items in cart $quote = $block->getCheckoutSession()->getQuote(); $items = $quote->getAllItems(); foreach($items as $item) { echo 'ID: '.$item->getProductId().'<br />'; echo 'Name: '.$item->getName().'<br />'; echo 'Sku: '.$item->getSku().'<br />'; echo 'Quantity: '.$item->getQty().'<br />'; echo 'Price: '.$item->getPrice().'<br />'; echo "<br />"; } // Get total items and total quantity in cart $totalItems = $quote->getItemsCount(); $totalQuantity = $quote->getItemsQty(); //Get subtotal and grand total price of cart $subTotal = $quote->getSubtotal(); $grandTotal = $quote->getGrandTotal(); //Get billing and shipping addresses $billingAddress = $quote->getBillingAddress(); $shippingAddress = $quote->getShippingAddress();Hope this helps. Thanks.
-
Integrity constraint violation: 1062 Duplicate entry ‘4-Images’ for key – Magento 2
Integrity constraint violation: 1062 Duplicate entry ‘4-Images’ for key ‘EAV_ATTRIBUTE_GROUP_ATTRIBUTE_SET_ID_ATTRIBUTE_GROUP_NAME’, query was: UPDATE `eav_attribute_group` SET `attribute_group_name` = ? WHERE (`attribute_group_id`=10)
This particular error presented itself while upgrading from Magento 2.0.2 to Magento 2.1.x and stops the upgrade process. We’ve discovered the issue is related to old data from the previous Magento 1.9.x installation. In order to over come this error, you’ll need to delete a row from the database.
Run the following MySQL query to find and delete the offending attribute.
deletefrom eav_attribute_group WHERE attribute_group_name ='Images';After that then you can attempt to run the upgrade command again and the issue should be resolved.
We understand not everyone can be a MySQL / Magento 2 expert so if you’re faced with a similar issue and stuck between an upgrade feel free to contact us to assist with your problem.
-
Magento 2: Create a Plugin for Save Payment Information Checkout
You can create a Plugin for the method SavePaymentInformation() in Magento 2 to add your logic before or after Payment information is saved.
The method will be called after a click on the Place order button from the second step of the Checkout page.
Original Class to create plugin:
Magento\Checkout\Model\PaymentInformationManagementYou can create a before or after plugin as per your requirement.
Create a global scope di.xml file,
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\Model\PaymentInformationManagement"> <plugin name="set_payment_data_before_save" type="Samdoit\SavePayment\Plugin\Model\SavePaymentPlugin" sortOrder="10"/> </type> </config>Create a Plugin Class for the Before saves payment information, We have used Before Plugin type,
<?php namespace Samdoit\SavePayment\Plugin\Model; use Magento\Quote\Api\Data\AddressInterface; use Magento\Quote\Api\Data\PaymentInterface; use Magento\Checkout\Model\PaymentInformationManagement; use Magento\Framework\Exception\AbstractAggregateException; class SavePaymentPlugin { /** * @param PaymentInformationManagement $subject * @param int $cartId * @param PaymentInterface $paymentMethod * @param AddressInterface|null $billingAddress * * @return array * * @throws AbstractAggregateException * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeSavePaymentInformation( PaymentInformationManagement $subject, int $cartId, PaymentInterface $paymentMethod, AddressInterface $billingAddress = null ): array { // Add your logic before Save Payment information return [$cartId, $paymentMethod, $billingAddress]; } }Before Plugin:
$cartId: You get the current quote Cart id, You can get the details of the active quote by cart id from the method.$paymentMethod contains the Payment related information, Payment method, Payment additional data
The $billingAddress field contains the billing data of the checkout billing section.
You can create an after plugin also for the above method if you need to do some logic after the Payment method successfully saved.
Above Code snippet, Save Payment Information Plugin for adding extra logic after or before Payment data save in Magento 2.
-
Magento 2: Search Repository using SearchCriteriaBuilder, Filter & FilterGroup
This article shows how we can search Magento Repositories using SearchCriteriaBuilder that implements SearchCriteriaInterface. An example is provided of how we can perform search on Product repository in Magento. Similarly, we can search for other entities like Category, Customer, Order, Invoice, CMS Page, CMS Block, etc.
We can add different conditions to build custom search criteria.
Filters
Filter class is used to add custom field, value, and condition type to the search criteria.
$filter ->setField("name") ->setValue("%laptop%") ->setConditionType("like");condition_typeis optional.- If
condition_typeis not provided then the defaultcondition_typeis set aseq.
Different condition types:
CONDITION NOTES eq Equals gt Greater than gteq Greater than or equal lt Less than lteq Less than or equal moreq More or equal neq Not equal in The value can contain a comma-separated list of values. nin Not in. The value can contain a comma-separated list of values. like The value can contain the SQL wildcard characters when like is specified. nlike Not like notnull Not null null Null finset A value within a set of values nfinset A value that is not within a set of values. from The beginning of a range. Must be used with to. to The end of a range. Must be used with from.Filter Groups
FilterGroup class is used to apply multiple search criteria filters.
For
ORcondition: Pass filters array inside the FilterGroup class object.
ForANDcondition: Pass filterGroups array inside the searchCriteria class object.$filter1 ->setField("name") ->setValue("%laptop%") ->setConditionType("like"); $filter2 ->setField("store_id") ->setValue("1") ->setConditionType("eq"); $filterGroup1->setFilters([$filter1, $filter2]); $filter3 ->setField("url_type") ->setValue(1) ->setConditionType("eq"); $filterGroup2->setFilters([$filter3]); $searchCriteria->setFilterGroups([$filterGroup1, $filterGroup2]);The above code will generate the following conditions:
(name like %laptop% OR store_id eq 1) AND (url_type eq 1)Sorting
SortOrder is used to apply sorting to the search criteria.
Field and Direction can be passed to the sortOrder object.
Field is the name of the field to sort.
Direction is how we would like to sort the result. The two sorting values areASCandDESC.$sortOrder ->setField("email") ->setDirection("ASC"); $searchCriteria->setSortOrders([$sortOrder]);Pagination
Limit the number in the result.
$searchCriteria->setPageSize(20); //retrieve 20 or less entitiesSet the current page
$searchCriteria ->setPageSize(20) ->setCurrentPage(2); //show the 21st to 40th entityThe search engine determines the maximum number of results that a query can return.
For Elasticsearch, the default value of10000is defined in the module’setc/di.xmlfile.Search Items Using Filters
Below is an example of how we can search Product Repository using Search Criteria Builder.
The ProductRepositoryInterface class has the
getList(SearchCriteria $searchCriteria)function which returns the search result object. The object is an instance of the class that implements the interface SearchResultInterface.FilterBuilder and SearchCriteriaBuilder are used to avoid shared instances, i.e. we will be using
create()method in the builder object so that Magento will instantiate a new object (unshared object).use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\FilterBuilder; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Api\Data\ProductInterface; ... ... $filter = $this->filterBuilder ->setField(ProductInterface::NAME) ->setValue('%headphone%') ->setConditionType('like') ->create(); $this->searchCriteriaBuilder->addFilters([$filter]); $this->searchCriteriaBuilder->setPageSize(20); $searchCriteria = $this->searchCriteriaBuilder->create(); $productsItems = $this->productRepository ->getList($searchCriteria) ->getItems();Search Items using FilterGroups
Using FilterGroups to add multiple
ANDandORconditions to search products.use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\Search\FilterGroupBuilder; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Api\Data\ProductInterface; ... ... $filter1 = $this->filterBuilder ->setField(ProductInterface::NAME) ->setValue("%laptop%") ->setConditionType("like") ->create(); $filter2 = $this->filterBuilder ->setField("store_id") ->setValue("1") ->setConditionType("eq") ->create(); $filterGroup1 = $this->filterGroupBuilder ->setFilters([$filter1, $filter2]); $filter3 = $this->filterBuilder ->setField("url_type") ->setValue(1) ->setConditionType("eq") ->create(); $filterGroup2 = $this->filterGroupBuilder ->setFilters([$filter3]); $this->searchCriteriaBuilder ->setFilterGroups([$filterGroup1, $filterGroup2]); $this->searchCriteriaBuilder->setPageSize(20); $searchCriteria = $this->searchCriteriaBuilder->create(); $productsItems = $this->productRepository ->getList($searchCriteria) ->getItems();Product Repository
use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Api\Data\ProductInterface;Category Repository
use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Api\Data\CategoryInterface;CMS Page Repository
use Magento\Cms\Api\PageRepositoryInterface; use Magento\Cms\Api\Data\PageInterface;CMS Block Repository
use Magento\Cms\Api\BlockRepositoryInterface; use Magento\Cms\Api\Data\BlockInterface;Customer Repository
use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\Data\CustomerInterface;Order Repository
use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Sales\Api\Data\OrderInterface;




