Migrating Shipping Extension for Magento 1.9 to Magento 2.2 - magento

I am trying to migrate a custom magento 1.9 extension to magento 2.2. I have done a lot of searching and can't find information on the use case I'm trying to migrate. I originally followed this tutorial for the 1.9 extension. I understand there is a tool to help port extensions, but I am trying to do this manually as I couldn't get that tool to function for me.
The custom shipping extension would run each time the shopping cart was updated to calculate a custom shipping rate. The goal is to recreate this extension in magento 2.2 such that each time the shopping cart is opened or updated it will run and calculate a shipping cost which will then propagate through the checkout process.
Below is an overview of the magento 1.9 extension. Any advice on how to translate this to magento 2.2?
/app/etc/modules/Extensions_Shipper.xml
<?xml version="1.0"?>
<config>
<modules>
<Extensions_Shipper>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Shipping />
</depends>
</Extensions_Shipper>
</modules>
/app/code/local/Extensions/Shipper/etc/config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Extensions_Shipper>
<module>0.0.1</module>
</Extensions_Shipper>
</modules>
<global>
<models>
<extensions_shipper>
<class>Extensions_Shipper_Model</class>
</extensions_shipper>
</models>
</global>
<default>
<carriers>
<extensions_shipper>
<active>1</active>
<model>extensions_shipper/carrier</model>
<title>Shipping Options</title>
<sort_order>10</sort_order>
<sallowspecific>0</sallowspecific>
</extensions_shipper>
</carriers>
</default>
/app/code/local/Extensions/Shipper/Model/Carrier.php
<?php
class Extensions_Shipper_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface
{
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
//Are there magento 2.2 equivalence for the following?
$addressInfo = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData();
$result = Mage::getModel('shipping/rate_result');
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$currentItem = Mage::getModel('catalog/product')->load($items[$itemsArray[$i]]->getProduct()->getId());
Mage::getSingleton('core/session')->addNotice('some text');
//$result = some calculations for shipping rate
return $result;
}
public function getAllowedMethods()
{
return array();
}
}

You can create an event observer on the checkout_cart_add_product_complete event to execute the logic to update the shipping costs.
namespace MyCompany\MyModule\Observer;
use Magento\Framework\Event\ObserverInterface;
class MyObserver implements ObserverInterface
{
public function __construct()
{
//Observer initialization code...
//You can use dependency injection to get any class this observer may need.
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
//Observer execution code...
}
}
Subscribe to the event in events.xml:
<?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="my_module_event_before">
<observer name="myObserverName" instance="MyCompany\MyModule\Observer\MyObserver" />
</event>
<event name="my_module_event_after">
<observer name="myObserverName" instance="MyCompany\MyModule\Observer\AnotherObserver" />
</event>
</config>
See Magento docs on events and observers: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/events-and-observers.html
For a list of all Magento 2.2 events, see: https://cyrillschumacher.com/magento-2.2-list-of-all-dispatched-events/

Related

Magento 1.9.X add product with custom options to cart from external site

I have an external website which allows a customer to design a product, then uses an HTML form to post this data. I need to take this information and add this product (with custom options) to the customer's cart in our Magento website, but I'm not sure how to go about this.
I tried something simple at first using URL redirect, but Magento 1.9.X no longer supports adding to cart like this:
$cart_url = "website.com/checkout/cart/add/product=" . $product_id . "&qty=1" //Include custom options somehow
<form action=<?php echo $cart_url?>>
<input type="hidden" value="pid"> product id </input>
<input type="hidden" value="option1"> custom option 1</input>
</form>
Doing research shows that I can also add an item with custom options through either writing a custom Controller or Events/Observers to add the item, but as I'm new to Magento I'm not sure how to trigger events and observer functions from outside of Magento.
Any help to point me in the right direction would be appreciated.
You will have to create a custom module in magento.
Create a file app/etc/MyExtension_AddProductFromUrl.xml
<config>
<modules>
<MyExtension_AddProductFromUrl>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Checkout/>
</depends>
</MyExtension_AddProductFromUrl>
</modules>
</config>
Create a file app/code/local/MyExtension/AddProductFromUrl/etc/config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<MyExtension_AddProductFromUrl>
<version>0.1.0</version>
</MyExtension_AddProductFromUrl>
</modules>
<frontend>
<routers>
<checkout>
<args>
<modules>
<MyExtension_AddProductFromUrl before="Mage_Checkout">MyExtension_AddProductFromUrl</MyExtension_AddProductFromUrl>
</modules>
</args>
</checkout>
</routers>
</frontend>
</config>
Create a file app/code/local/MyExtension/AddProductFromUrl/controllers/CartController.php
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class MyExtension_AddProductFromUrl_Checkout_CartController extends Mage_Checkout_CartController {
# overloaded addAction
public function addAction() {
// generate form_key if missing or invalid
if (!($formKey = $this->getRequest()->getParam('form_key', null)) || $formKey != Mage::getSingleton('core/session')->getFormKey()) {
$this->getRequest()->setParams(array('form_key' =>Mage::getSingleton('core/session')->getFormKey()));
}
// do parent actions
parent::addAction();
}
}
?>
Also see
Magento - Add a product to the cart via query string without form_key parameter
https://magento.stackexchange.com/questions/37779/i-want-to-use-add-to-cart-via-url-in-magento-1-8-but-dont-know-which-files-to-c
I fought with this for a bit in 1.9.0.1, but St0iK's solution above worked with the following changes:
1) place the module .xml file in app/etc/modules (as opposed to app/etc)
2) In the controller file - i had to remove _Checkout_
class MyExtension_AddProductFromUrl_Checkout_CartController extends Mage_Checkout_CartController {
to
class MyExtension_AddProductFromUrl_CartController extends Mage_Checkout_CartController {
After these minor edits, it works perfectly. Not sure if these were only necessary for 1.9.0.1, but for whatever reason, they were.
To add a product to the cart, i just use the URL format
YOURSTORE.com/checkout/cart/add/product/123/qty/1
Great solution for external PPC or SEO landing pages that need a simple "buy now" button that drops right into your magento cart.

How to rewrite a Magento Block with an extension?

I want to rewrite the Mage_Catalog_Block_Product_View block.
I created this file: config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<JB_CustomPrice>
<version>0.1.0</version>
</JB_CustomPrice>
</modules>
<global>
<blocks>
<customprice>
<class>JB_CustomPrice_Block</class>
</customprice>
<catalog>
<rewrite>
<product_view>JB_CustomPrice_Block_Catalog_Product_View</product_view>
</rewrite>
</catalog>
</blocks>
</config>
Then I created the block in
/app/code/local/JB/CustomPrice/Block/Catalog/Product/View.php
<?php
class JB_CustomPrice_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View
{
public function getJsonConfig()
{
return 'test';
}
}
?>
Though, the product view doesn't change, even not when I call the getProduct() method. What's going wrong?
The global error was a typo, solved by using Mage::log(get_class($this)), that fixed it. The problem was that another plugin extended Mage_Catalog_Block_Product_View already. It was an old Yoast_MetaRobots plugin, which is deprecated. I disabled it and everything was fixed. Thanks for the answer!

Set Payment Method "Cash On Delivery" on Particular State Only

I want to set "Cash On Delivery" for the site owner's State only
I know how to set For "Specified Country"
I am using Magento 1.8
How can I achieve this ?
LuFFy,you doing this using magento event observer:
Create an extension and here the step:
create config.xml under :app/code/community/Devamitbera/Statewisecod/etc/config.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
#Author Amit Bera
#Email dev.amitbera#gmail.com
# Website: www.amitbera.com
*/-->
<config>
<modules>
<Devamitbera_Statewisecod>
<version>1.0.0</version>
</Devamitbera_Statewisecod>
</modules>
<global>
<models>
<statewisecod>
<class>Devamitbera_Statewisecod_Model</class>
</statewisecod>
</models>
</global>
<frontend> <!-- run observer event for frontend -->
<events>
<payment_method_is_active>
<observers>
<enable_cod_for_some_state>
<class>statewisecod/observer</class>
<method>EnableCod</method>
</enable_cod_for_some_state>
</observers>
</payment_method_is_active>
</events>
</frontend>
</config>
Create observer file
under Observer.php under app/code/community/Devamitbera/Statewisecod/Model
Code of this file:
<?php
class Devamitbera_Statewisecod_Model_Observer
{
public function EnableCod($observer){
$result=$observer->getEvent()->getResult();
$MethodInstance=$observer->getEvent()->getMethodInstance();
$quote=$observer->getEvent()->getQuote();
if($quote && $quote->getId()):
/* If Payment method is cashondelivery then conitnue */
if($MethodInstance->getCode()=='cashondelivery'){
#Mage::log('Payment is Cod',null,'Cod.log',true);
$ShippingAddress=$quote->getShippingAddress();
/* region_id is working when country have
* drop state/regions.
*/
/* Here i have put USA coutry new work & Washinton redion */
#Mage::log('redion'.$ShippingAddress->getRegionId(),null,'redion.log',true);
$CodEnableRegionIds=array(62,43);
if(in_array($ShippingAddress->getRegionId(),$CodEnableRegionIds)):
$result->isAvailable=true;
elseif(is_null($ShippingAddress->getRegionId()) && !is_null($ShippingAddress->getRegion())):
/* This section working when State/region is not dropdown
and state is dropdown
*/
$textListRegionName=array('West bengal','Delhi');
if(in_array($ShippingAddress->getRegion(),$textListRegionName)){
$result->isAvailable=true;
}else{
$result->isAvailable=false;
}
else:
$result->isAvailable=false;
endif;
return $result->isAvailable;
}
endif;
}
}
create module file Devamitbera_Statewisecod.xml under app/etc/modules
<?xml version="1.0" encoding="utf-8"?>
<!--
#Author Amit Bera
#Email dev.amitbera#gmail.com
# Website: www.amitbera.com
-->
<config>
<modules>
<Devamitbera_Statewisecod>
<codePool>community</codePool>
<active>true</active>
<depends><Mage_Payment/></depends>
</Devamitbera_Statewisecod>
</modules>
</config>
Here cashondelivery is payment method code of cash on delivery.... which is saved in database.
- Edited:
region_id is working when country have drop state/regions list.
if(in_array($ShippingAddress->getRegionId(),$CodEnableRegionIds)):
$result->isAvailable=true;
If State/region is not dropdown then Below logic is work
elseif(is_null($ShippingAddress->getRegionId()) && !is_null($ShippingAddress->getRegion())):
$textListRegionName=array('West bengal','Delhi');
if(in_array($ShippingAddress->getRegion(),$textListRegionName)){
$result->isAvailable=true;
}else{
$result->isAvailable=false;
}

magento how to change cart account in checkout page

in product detail page, the product price is 50 dollar, I use JavaScript change the price to 80 dollar, but when add to cart, it is still 50 dollar in checkout page. how to let it still 80 dollar in checkout page?
You need use "sales_quote_add_item" magento event to update the product price in cart session.
You have to make a custom module for that purpose.
Create a file in app/etc/modules/Company_All.xml
<?xml version="1.0"?> <config> <modules>
<Company_Product>
<codePool>local</codePool>
<active>true</active>
</Company_Product> </modules> </config>
Create configuration file for our module file in app/code/local/Company/Product/etc/config.xml
<?xml version="1.0"?> <config> <global>
<models>
<product>
<class>Company_Product_Model</class>
</product>
</models>
<events>
<sales_quote_add_item><!--Event to override price after adding product to cart-->
<observers>
<company_product_price_observer><!--Any unique identifier name -->
<type>singleton</type>
<class>Company_Product_Model_Price_Observer</class><!--Our observer class name-->
<method>update_book_price</method><!--Method to be called from our observer class-->
</company_product_price_observer>
</observers>
</sales_quote_add_item>
</events> </global> </config>
Create our observer file in app/code/local/Company/Product/Model/Price/Observer.php
class Company_Product_Model_Price_Observer{
public function update_book_price(Varien_Event_Observer $observer) {
$quote_item = $observer->getQuoteItem();
//if(){ //your logic goes here
$customprice = 50;
//}
$quote_item->setOriginalCustomPrice($customprice);
$quote_item->save();
return $this;
}
}

Change Magento default status for duplicated products

I have a Magento store installed, and when a product is duplicated in the backend, Magento sets its status to Disabled by default. I don't want that to happen, the duplicated product should have its status copied from the original product as well.
In this post a partial solution was given. I see where I can find the config.xml and make the necessarry changes. However, where do I put such an observer class? Which file should I use/create and would that require any changes to the config.xml input?
Or does somebody have an overall solution for this issue? Thanks in advance!
Try this:
Create: app/code/local/MagePal/EnableDuplicateProductStatus/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<MagePal_EnableDuplicateProductStatus>
<version>1.0.1</version>
</MagePal_EnableDuplicateProductStatus>
</modules>
<global>
<models>
<enableduplicateproductstatus>
<class>MagePal_EnableDuplicateProductStatus_Model</class>
</enableduplicateproductstatus>
</models>
<events>
<catalog_model_product_duplicate>
<observers>
<enableduplicateproductstatus>
<type>singleton</type>
<class>enableduplicateproductstatus/observer</class>
<method>productDuplicate</method>
</enableduplicateproductstatus>
</observers>
</catalog_model_product_duplicate>
</events>
</global>
</config>
Create: app/code/local/MagePal/EnableDuplicateProductStatus/Model/Observer.php
class MagePal_EnableDuplicateProductStatus_Model_Observer
{
/**
* Prepare product for duplicate action.
*
* #param Varien_Event_Observer $observer
* #return object
*/
public function productDuplicate(Varien_Event_Observer $observer)
{
$newProduct = $observer->getEvent()->getNewProduct();
$newProduct->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
return $this;
}
}
Create: app/etc/modules/MagePal_EnableDuplicateProductStatus.xml
<?xml version="1.0"?>
<config>
<modules>
<MagePal_EnableDuplicateProductStatus>
<active>true</active>
<codePool>local</codePool>
</MagePal_EnableDuplicateProductStatus>
</modules>
</config>
Then clear cache and try duplicating a product.
read more # :
http://magento4u.wordpress.com/2009/06/08/create-new-module-helloworld-in-magento/
http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/customizing_magento_using_event-observer_method
make a new product active by default in magento
I found error on this code and find out the solution below:
On app/code/local/MagePal/EnableDuplicateProductStatus/etc/config.xml change
<method> duplicateProduct </method>
TO
<method>productDuplicate</method>

Resources