I want to save order data in custom Table After order success.
app/code/VendorName/Checkout/etc/event.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="checkout_onepage_controller_success_action">
<observer name="MyObserver" instance="VendorName\Checkout\Observer\MyObserver" />
</event>
</config>
app/code/VendorName/Checkout/Observer/MyObserver.php
<?php
namespace VendorName\Checkout\Observer;
use Magento\Framework\Event\ObserverInterface;
class MyObserver implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$orderIds = $observer->getEvent()->getOrderIds();
echo $orderId = $orderIds[0]; exit;
}
}
Event is not trigger success.phtml is redirected.
The event.xml file name should be events.xml. After renaming file check again
If still the problem, put your events file to
app/code/VendorName/Checkout/etc/frontend/events.xml
Confirm if the plugin installed by executing
php bin/magento module:status
If the module is not listed, execute
php bin/magento setup:upgrade
Related
I have been trying to filter the coupon coupons for hours now.
I tried to manipulate the function mapAssociatedEntities in the file /vendor/magento/module-sales-rule/Model/ResourceModel/Rule/Collection.php with a plugin, but I can't get it to work and now I'm hoping for your help.
/etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<type name="Magento\SalesRule\Model\ResourceModel\Rule\Collection">
<plugin name="coupon_restricted_plugin" type="Vendor\Modul\Plugin\CouponCollectionPlugin" sortOrder="1"/>
</type>
</config>
/app/code/Vendor/Modul/Plugin/CouponCollectionPlugin.php
<?php
namespace Vendor\Modul\Plugin;
class CouponCollectionPlugin
{
public function aroundMapAssociatedEntities(
\Magento\SalesRule\Model\ResourceModel\Rule\Collection $subject,
\Closure $proceed,
$entityType,
$objectField
){
var_dump('Here: ' . __METHOD__.__FUNCTION__'<br>');
$result = $proceed($entityType, $objectField);
return $result;
}
}
I also like to take another way to override the mapAssociatedEntities function.
I need to narrow down the coupon codes to the user
Edit// Magento 2.4.5-p1
I encountered a problem where my new module is not found when I tried to browse it.
Here is the detail of the code.
Ced/CsTermsAndServices/etc/Module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Ced_TermsAndServices" setup_version="1.0.0">
</module>
</config>
Ced/CsTermsAndServices/registration.php
<?PHP
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Ced_TermsAndServices',
__DIR__
);
Ced/CsTermsAndServices/etc/frontend/routes.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="cstermsandservices" id="cstermsandservices">
<module name="Ced_TermsAndServices"/>
</route>
</router>
</config>
Ced/CsTermsAndServices/Controller/Index/Index.php
<?php
namespace Ced\CsTermsAndServices\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
echo "Hello World";
exit;
}
}
The expected route supposed to be
http://localhost/cstermsandservices/index/index
But the result ended up as 404 not found.
Any fix to this?
1)make sure you have vendor/module-name vendor_module-name convention is followed( in your case modules name should be Ced_CsTermsAndServices if you want to follow current directory structure)
2) module.xml file name should be in all lower case
Hope this will work
Happy Magento
I have created a custom module in Magento 2.2.2 which extends the \Magento\GroupedProduct\Model\Product\Type\Grouped class.
The module is successfully installed and enabled on the website, however, I am receiving a PHP Fatal error: Uncaught Error: Class 'ExtraMile\Catalog\Model\Grouped' not found in ../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:111.
My module folder structure is as follows:
Image of module folder structure
The di.xml file contains:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'ExtraMile_GroupedProduct',
__DIR__
);
The module.xml file contains:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="ExtraMile_GroupedProduct" setup_version="1.0.2">
<sequence>
<module name="Magento_GroupedProduct"/>
</sequence>
</module>
</config>
The Grouped.php file contains:
<?php
namespace ExtraMile\GroupedProduct\Model;
class Grouped extends \Magento\GroupedProduct\Model\Product\Type\Grouped
{
public function getAssociatedProducts($product)
{
if (!$product->hasData($this->_keyAssociatedProducts)) {
$associatedProducts = [];
$this->setSaleableStatus($product);
$collection = $this->getAssociatedProductCollection(
$product
)->addAttributeToSelect(
['name', 'price', 'special_price', 'special_from_date', 'special_to_date', 'tax_class_id']
)->addFilterByRequiredOptions()->setPositionOrder()->addStoreFilter(
$this->getStoreFilter($product)
)->addAttributeToFilter(
'status',
['in' => $this->getStatusFilters($product)]
);
foreach ($collection as $item) {
$associatedProducts[] = $item;
}
$product->setData($this->_keyAssociatedProducts, $associatedProducts);
}
return $product->getData($this->_keyAssociatedProducts);
}
}
bin/magento setup:di:compile has been ran many times.
I have followed many tutorials such as: http://inchoo.net/magento-2/overriding-classes-magento-2/ and I cannot see why I am getting the error. Please can anyone advise what the issue is?
Issue solved:
I fixed this by moving the module folder from app/design/frontend/<vendor>/<module> into code/<vendor>/<module>.
Running bin/magento setup:di:compile then removed the class not found error.
I'm trying to create a simple event observer for my Magento 2 page.
app/code/Ndac/Orderinfo/etc/event.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="sales_order_place_after">
<observer name="OrderInfo" instance="Ndac\Orderinfo\Observer\OrderInfo" />
</event>
</config>
app/code/Ndac/Orderinfo/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Orderinfo" setup_version="1.0.0"></module>
</config>
app/code/Ndac/Orderinfo/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,"Orderinfo", __DIR__);
app/code/Ndac/Orderinfo/Observer/OrderInfo.php
<?php
namespace Ndac\Orderinfo\Observer;
use Magento\Sales\Model\Order;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class OrderInfo implements ObserverInterface {
// Tried it with constructor
public __construct() {
$file = fopen("/mnt/data/magento/test.txt", "w") or die ("die");
fwrite($file, "test");
fclose($file);
}
public function execute(Observer $observer)
{
$file = fopen("/mnt/data/magento/test.txt", "w") or die ("die")
fwrite($file, "test");
fclose($file);
}
}
?>
I run the following command: bin/magento setup:upgrade and the module appears on the dashboard, and its enabled, but the test.txt remains empty, after I place an order.
There is an issue with the file naming.
app/code/Ndac/Orderinfo/etc/event.xml
this has to be as:
app/code/Ndac/Orderinfo/etc/events.xml
It has to be events.xml. And also if this event doesn't work, then try with the checkout_onepage_controller_success_action event.
Now run the upgrade command and clear the cache.
I'm trying to write an observer that will export order data when an order is placed. I haven't written any modules before. Basing my implementation on this article: http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/customizing_magento_using_event-observer_method
so far I'm just trying to trigger some dummy code to write to a file. I'm not getting anything showing in my log, and the file's not being modified. The apache user has permission for the directory. I've disabled configuration caching in the Magento settings. I'm a little confused on some of the naming conventions; I just tried to follow the example. Anyone know where I'm going wrong?
in magento/app/etc/modules/Feed.xml:
<?xml version="1.0"?>
<config>
<modules>
<Feed_Sales>
<codePool>local</codePool>
<active>true</active>
</Feed_Sales>
</modules>
</config>
in magento/app/code/local/Feed/Sales/etc/config.xml:
<?xml version="1.0"?>
<config>
<global>
<models>
<feedsales>
<class>Feed_Sales_Model</class>
</feedsales>
</models>
<events>
<sales_order_place_after>
<observers>
<feed_sales_order_observer>
<type>singleton</type>
<class>sales/order_observer</class><!-- I've also tried Feed_Sales_Model_Order_Observer here -->
<method>export_new_order</method>
</feed_sales_order_observer>
</observers>
</sales_order_place_after>
</events>
</global>
</config>
in magento/app/code/local/Feed/Sales/Model/Order/Observer.php:
<?php
class Feed_Sales_Model_Order_Observer
{
public function __contruct()
{
}
/**
* Exports new orders to an xml file
* #param Varien_Event_Observer $observer
* #return Feed_Sales_Model_Order_Observer
*/
public function export_new_order($observer)
{
Mage::log("reached export_new_order");
try
{
$dumpFile = fopen('/home/jorelli/new_orders/testdump', 'w+');
fwrite($dumpFile, 'this is a test!');
}
catch (Exception $e)
{
Mage::log("order export failed.\n");
}
return $this;
}
}
?>
Magento 1.4 on Debian Lenny with Apache2 if it should matter for any reason.
Read my articles, they'll help you understand what's going on from a naming convention standpoint and get you grounded in some of Magento's conventions/assumptions.
Looking at the samples above, you have a few things not quite right.
First, your file in the etc folder is named wrong
magento/app/etc/modules/Feed.xml
This file needs to be named Packagename_Modulename, so you probably want
magento/app/etc/modules/Feed_Sales.xml
Look at System -> Configuration -> Advanced to see if your module shows up. If it does, you'll have named this file correctly. Without this, the module you created isn't being loaded into the system, and your code never has a chance to run.
Next, you're specifying the class incorrectly. You say
sales/order_observer
but that first part of the URI (sales) is incorrect. You defined your models section as
<models>
<feedsales> <!-- this is your model part -->
<class>Feed_Sales_Model</class>
</feedsales>
</models>
which means you want
feedsales/order_observer
Checkout the Class/URI tab of Commerce Bug and try entering some URIs (like sales/order) to get a better idea of what's going on here.
Another quick tip, when you're trying to get your handler setup, do it for an event that fires on every page load. Then, once you have your method being called, you can switch it to the specific event you want and not have to go through the entire purchase process.
Finally, and I realize you were copying examples, consider putting your module in a folder named something other than Sales. I find mimicking the names of Magento core folders only add an extra layer of confusion, which is not what you need while you're learning the system.
The problem seems to be with your observer declaration. Give this a try:
<events>
<sales_order_place_after>
<observers>
<feed_sales_order_observer>
<type>singleton</type>
<class>feedsales/order_observer</class>
<method>export_new_order</method>
</feed_sales_order_observer>
</observers>
</sales_order_place_after>
</events>
Holy crap. I was stupid. I tested it out with a command line script, like I do with a lot of things, but that particular file was only writeable by the command line interpreter, not the Apache interpreter. I should have left the office earlier last night.
Well for the record, this is how you trigger an action on order placement. I'll leave it up for posterity.
better use this event instead of sales_order_save_after and checkout_onepage_controller_success_action
checkout_submit_all_after
it will work even site not redirected to success page because of some errors like internet issue and all.
try to use below code my requirement also same
namespace Custom\Checkout\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Simplexml\Element as SimpleXMLElement;
class Afterplaceorder implements ObserverInterface
{
protected $_request;
protected $_layout;
protected $_dir;
protected $jsonHelper;
protected $timezone;
protected $_io;
protected $_RandomBytes;
public function __construct(
\Magento\Framework\View\Element\Context $context,
\Magento\Framework\Filesystem\DirectoryList $dir,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
\Magento\Framework\Filesystem\Io\File $io,
\Magento\Framework\Math\Random $RandomBytes
){
$this->_layout = $context->getLayout();
$this->_request = $context->getRequest();
$this->_dir = $dir;
$this->jsonHelper = $jsonHelper;
$this->timezone = $timezone;
$this->_io = $io;
$this->_RandomBytes = $RandomBytes;
}
/**
* #param \Magento\Framework\Event\Observer $observer
* #return void
*/
public function execute(EventObserver $observer)
{
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/orderdata.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$order = $observer->getData('order');
$quote = $observer->getQuote();
try{
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$data = array('total_stud' => 500);
// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><order></order>');
// function call to convert array to xml
array_to_xml($orderDeatails,$xml_data);
//saving generated xml file;
if ( ! file_exists($this->_dir->getPath('var').'/api/order')) {
$this->_io->mkdir($this->_dir->getPath('var').'/api/order', 0775);
}
$result = $xml_data->asXML($this->_dir->getRoot().'/var/api/order/order_'.$order->getIncrementId().'.xml');
}catch(\Exception $e){
$logger->info(print_r('error-> '.$e->getMessage(),true));
}
}
}
hope it will help you!
Happy Coding!!