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.
Related
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 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
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 pretty new to Magento, and having problems trying to set a custom shipping method programmatically. I'm converting an xml from a thrid party into an order, and everything else (that I've worked on so far) is working fine. Also I'm having problems spelling "programmatically" but I won't ask for you help with that.
I set up my custom shipping method as follows:
To activate the shipping module in
app/etc/modules/Extension_Shipping.xml
<?xml version=
"1.0"?>
<config>
<modules>
<Extension_Shipping>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Shipping/>
</depends>
</Extension_Shipping>
</modules>
</config>
then to configure it in
app/code/local/Extension/Shipping/etc/config.xml
<?xml version=
"1.0" ?>
<config>
<modules>
<Extension_Shipping>
<version>0.1.0</version>
</Extension_Shipping>
</modules>
<global>
<models>
<extension_shipping>
<class>Extension_Shipping_Model</class>
</extension_shipping>
</models>
</global>
<default>
<carriers>
<extension_myrate>
<active>1</active>
<model>extension_shipping/carrier_myrate</model>
<title>Extension Shipping</title>
<name>Default Rate</name>
</extension_myrate>
</carriers>
</default>
</config>
then to add the class in
app/code/local/Extension/Shipping/Model/Carrier/MyRate.php
<?php
class Extension_Shipping_Model_Carrier_MyRate
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{
protected $_code = 'extension_myrate';
protected $_isFixed = true;
public function collectRates(Mage_Shipping_Model_Rate_Request
$request)
{
if (!$this->getConfigFlag('active')) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('extension_myrate');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('extension_myrate');
$method->setMethodTitle($this->getConfigData('name'));
$method->setPrice(5);
$method->setCost(2);
$result->append($method);
return $result;
}
public function getAllowedMethods()
{
return array('extension_myrate' => $this->getConfigData('name'));
}
}
Basically I followed http://www.magentotricks.com/creating-a-customer-magento-shipping-method/
I thought it all worked fine, as the shipping method now shows up in the checkout screen, and can be set both by customers or in the admin "create new order." However, I'm not able to set it programmatically.
In my controller I'm trying to set the shipping method using the code
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('extension_myrate')
->setPaymentMethod('checkmo');
To add to my confusion, it worked once. but only once out of quite a few test orders. changing the "setShippingMethod" to "freeshipping_freeshipping" or "flatrate_flatrate" makes it update the shipping to those correctly. because of that and because I'm new and still having problems with the file structure, I'm guessing my problem is with setShippingMethod('extension_myrate') but I'm not entirely sure. Any advice would be helpful and appreciated.
I'm trying to create my first Magento extension and I'm stuck at the first step already.
When adding {{block type="rick_printer/print" text="Hello world"}} to a CMS page or block, I want "Hello world" to be displayed.
Unfortunately nothing happens. Here's my code:
app\code\local\Rick\Printer\etc\config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Rick_Printer>
<version>0.0.1</version>
</Rick_Printer>
</modules>
<global>
<blocks>
<rick_printer>
<class>Rick_Printer_Block_Print</class>
</rick_printer>
</blocks>
</global>
</config>
app\etc\modules\Rick_Printer.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Rick_Printer>
<active>true</active>
<codePool>local</codePool>
</Rick_Printer>
</modules>
</config>
app\code\local\Rick\Printer\Block\Print.php
class Rick_Printer_Block_Print extends Mage_Core_Block_Abstract
{
protected function _construct()
{
$this->setTemplate('rick/printer/view.phtml');
parent::_construct();
}
public function printIt()
{
$text = $this->getText();
if (!$text) {
$msg = "Please provide a text!";
echo $msg;
return array();
}
return $text;
}
}
app\design\frontend\default\default\template\rick\printer\print.phtml
<?php
$text = $this->spinIt();
echo $text;
?>
I know the code is ugly and I'm probably doing it all wrong.
Any help is highly appreciated!
Thanks
Update: After applying the fix from Vinai's answer my app\code\local\Rick\Printer\etc\config.xml looks now like this:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Rick_Printer>
<version>0.0.1</version>
</Rick_Printer>
</modules>
<global>
<blocks>
<rick_printer>
<class>Rick_Printer_Block</class>
</rick_printer>
</blocks>
</global>
</config>
and I'm getting the following error message when accessing the CMS page (which doesn't show):
class Rick_Printer_Block_Print extends Mage_Core_Block_Abstract
{
protected function _construct()
{
$this->setTemplate('rick/printer/view.phtml');
parent::_construct();
}
public function printIt()
{
$text = $this->getText();
if (!$text) {
$msg = "Please provide a text!";
echo $msg; return array();
}
return $text;
}
}
Fatal error: Class 'Rick_Printer_Block_Print' not found in /home/www/xyz/htdocs/app/code/core/Mage/Core/Model/Layout.php on line 491
First, your block class prefix is wrong. Despite the node name being <class>, what you are actually specifying is a class prefix.
Another way to look at it is that this node declares the directory, in which the blocks for the module are located.
The correct way is
<!-- language: xml -->
<global>
<blocks>
<rick_printer>
<class>Rick_Printer_Block</class>
</rick_printer>
</blocks>
</global>
Second, in your template you are calling $this->spinIt(); instead of $this->printIt();.
Just a typo...
Otherwise the code looks okay.
UPDATE
The error message indicates a file system path to class name mismatch. Check the casing and for typos.
Also, since you want your block to render a template, you want to extend Rick_Printer_Block_Print from Mage_Core_Block_Template instead of the _Abstract block class.