I want to save costume data in cart item, I have check data has been save in data base but when I am getting then it will return null.
I have add event for add costume data into cart.
Observer.php
public function checkoutCartProductAddAfter(Varien_Event_Observer $observer){
try {
$data = $this->_getRequest()->getPost();
$item = $observer->getEvent()->getQuoteItem();
$item->setData('customize_data', $data['customize_data']);
$item->setData('customize_image', $data['customize_image']);
$item->save();
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
I want to change image in cart page so I have create below file.
<?php
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{
public function getProductThumbnail()
{
$customize_data = $this->getItem()->getData('customize_data');
$customize_image = $this->getItem()->getData('customize_image');
Mage::log('customize_data');
Mage::log($customize_data);
Mage::log('customize_image');
Mage::log($customize_image);
if (!empty($customize_image)) {
return $customize_image;
} else {
return parent::getProductThumbnail();
}
}
}
I am getting below logs in system.log file
2017-01-02T06:38:29+00:00 DEBUG (7): customize_data
2017-01-02T06:38:29+00:00 DEBUG (7):
2017-01-02T06:38:29+00:00 DEBUG (7): customize_image
2017-01-02T06:38:29+00:00 DEBUG (7):
You can do this thing without adding a new column in item table,
Observer.php
public function checkoutCartProductAddAfter(Varien_Event_Observer $observer){
try {
$data = Mage::app()->getRequest()->getPost();
$item = $observer->getQuoteItem();
$additional_info = $item->getadditional_info();
$additional_info = unserialize($additional_info);
$additional_info['customize']['customize_data'] = $data['customize_data'];
$additional_info['customize']['customize_image'] = $data['customize_image'];
$item->setAdditionalInfo(serialize($additional_info));
$item->save();
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
CART Page :
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{
public function getProductThumbnail()
{
$additional_info = $this->getItem()->getData('additional_info');
$additional_info = unserialize($additional_info);
if(isset($additional_info['customize']) && $additional_info['customize']){
Mage::log('customize_data');
Mage::log($additional_info['customize']['customize_data']);
Mage::log('customize_image');
Mage::log($additional_info['customize']['customize_image']);
return $additional_info['customize']['customize_image'];
}
return parent::getProductThumbnail();
}
}
Related
I have a model ProductOffer inside of it I use afterSave to generate the coupon.
Right now the status is null and in aftersave I want to update it.
public function afterSave($insert, $changedAttributes) {
if (floatval($this->offer) >= floatval($this->product->threshold_price)) {
$coupon = false;
$createCoupon = "";
$ctr = 1;
while ($coupon == false) {
$createCoupon = $this->createCoupon(
"Offer for " . $this->customer_name . ' #' . $this->id,
$this->product->sale_price - $this->offer,
$this->product_id
);
if ($createCoupon || $ctr > 3) {
$coupon = true;
}
$ctr++;
}
$this->status = self::STATUS_ACCEPTED_COUPON_GENERATED;
$this->coupon_code = $createCoupon->code;
// todo this
// echo "Accepted automatically then send email to customer as the same time to merchant email";
} else {
$this->status = self::STATUS_REJECTED;
}
return parent::afterSave($insert, $changedAttributes);
}
So here at afterSave I want to update the status of record and save the coupon code.
What I wan't to do is simply like this.
public function afterSave($insert, $changedAttributes) {
// So basically I want to update the status in afterSave
$this->status = "What ever value rejected or accepted it depends of the outcome of generating coupon";
$this->coupon = "AddTheCoupon";
// Save or Update
$this->save();
return parent::afterSave($insert, $changedAttributes);
}
But It seems not working for me and if you going to analyze it, it seems to do endless updating of the data since every save() it will pass through the afterSave().
Is there other way to do it?
Thanks!
You should use the updateAttributes method, which skips all the events.
See reference updateAttributes(['some_field']).
/** After record is saved
*/
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$this->some_field = 'new_value';
$this->updateAttributes(['some_field']);
}
I'm testing on Magento 2.2.3 and I've created an observer for the event sales_order_save_after which I'm using to automatically create an invoice.
Here is the current error that I'm receiving after placing an order:
Order saving error: Rolled back transaction has not been completed correctly.
And my MyCompany/MyModule/Observer/SalesOrderSaveAfter.php
<?php
namespace MyCompany\MyModule\Observer;
use Magento\Framework\Event\ObserverInterface;
class SalesOrderSaveAfter implements ObserverInterface
{
protected $_invoiceService;
protected $_transactionFactory;
public function __construct(
\Magento\Sales\Model\Service\InvoiceService $invoiceService,
\Magento\Framework\DB\TransactionFactory $transactionFactory
) {
$this->_invoiceService = $invoiceService;
$this->_transactionFactory = $transactionFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
try {
if(!$order->canInvoice()) {
return null;
}
if(!$order->getState() == 'new') {
return null;
}
$invoice = $this->_invoiceService->prepareInvoice($order);
$invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE);
$invoice->register();
$transaction = $this->_transactionFactory->create()
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
} catch (\Exception $e) {
$order->addStatusHistoryComment('Exception message: '.$e->getMessage(), false);
$order->save();
return null;
}
}
}
If I remove the transaction portion of the code, eg:
$transaction = $this->_transactionFactory->create()
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
then the order will pass through with the products marked as invoiced, but no invoice is actually created or saved to the order.
Any ideas what I could be missing?
https://magento.stackexchange.com/questions/217045/magento-2-how-to-automatically-create-invoice-from-order-observer
The answer to this is that I was using the wrong event. With the event sales_order_save_after the order hasn't been committed to the Database yet.
I changed my event to fire on checkout_submit_all_after and my observer is now working.
guys sorry for bad English.
I am using in Magento enterprise I am working in wishlist there is a function in core at path
C:\xampp\htdocs\projects\baab.bh\app\code\core\Mage\Wishlist\Helper\Data.php
getWishlist()
When I am calling this function to get wishlist from front-end phtml file it's giving me correct wishlist but when I am calling this function from controller it's giving me default wishlist only not the current wishlist here is the code of this function
public function getWishlist()
{
if (is_null($this->_wishlist)) {
if (Mage::registry('shared_wishlist')) {
$this->_wishlist = Mage::registry('shared_wishlist');
} elseif (Mage::registry('wishlist')) {
$this->_wishlist = Mage::registry('wishlist');
} else {
$this->_wishlist = Mage::getModel('wishlist/wishlist');
if ($this->getCustomer()) {
$this->_wishlist->loadByCustomer($this->getCustomer());
}
}
}
return $this->_wishlist;
}
I am calling it with the same code but it behaves differently from front-end phtml file and from controller. How can I get current wishlist from the controller as well?
For this, you will get all customers wishlist:
public function getWishlist()
{
$customer = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*');
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer);
$wishListAllItem = $wishList->getItemCollection();
if (count($wishListAllItem)) {
$arrOfProductIds = array();
foreach ($wishListAllItem as $item) {
$arrOfProductIds[] = $item->getProductId();
}
}
return $arrOfProductIds;
}
For this, you can get current user wishlist:
$wishList = Mage::getSingleton('wishlist/wishlist')->loadByCustomer($customer)
$wishListAllItem = $wishList->getItemCollection();
if (count($wishListAllItem)) {
$arrOfProductIds = array();
foreach ($wishListAllItem as $item) {
$product = $item->getProduct();
$arrOfProductIds[] = $product->getId();
}
}
I tried with following observer code.
...
public function automaticallyInvoiceShipCompleteOrder($observer)
{
$order = $observer->getEvent()->getOrder();
$orders = Mage::getModel('sales/order_invoice')->getCollection()
->addAttributeToFilter('order_id', array('eq'=>$order->getId()));
$orders->getSelect()->limit(1);
if ((int)$orders->count() !== 0) {
return $this;
}
try {
if($order->canShip())
{
$itemQty = $order->getItemsCollection()->count();
$items[] = $itemQty;
// This first definition and 2nd look overlapping, our one is obsolete?
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
$ship = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $ship->create($order->getId(), $items, 'Shipment created through ShipMailInvoice', true, true);
//getting Error here
}
}
} catch (Exception $e) {
$order->addStatusHistoryComment(' Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
$order->save();
}
return $this;
}
.....
When i place the order, i can capture the order success event using observer. Finally getting "Fatal error: Maximum function nesting level of '100' reached, aborting!" in ajax call itself.
I could not found the solution. Kindly give some advice on this
Each time your order is saved, this observer method is called, which again saves your order due to some error in try block. That's the reason I think it will endlessly execute and after 100th time Fatal error will be thrown.
In your try block's $ship->create(), you need to pass Order Increment ID and not Order Entity ID.
I tried with below code,
public function automaticallyInvoiceShipCompleteOrder($observer)
{
//$order = $observer->getEvent()->getOrder();
$incrementid = $observer->getEvent()->getOrder()->getIncrementId();
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementid);
try {
// Is the order shipable?
if($order->canShip())
{
$shipmentid = Mage::getModel('sales/order_shipment_api')->create($order->getIncrementId(), array());
}
//END Handle Shipment
} catch (Exception $e) {
$order->addStatusHistoryComment(' Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
}
return $this;
}
Shipment Created now...
I wanted to add an action on Sales>Order in Magento admin.
Screenshot-
I followed the second method from this blog- www.blog.magepsycho.com/adding-new-mass-action-to-admin-grid-in-magento/
My problem-
I am not able to get the order id (for performing the action on it) in the action controller.
My code in class MyPackage_MyModule_IndexController extends Mage_Adminhtml_Controller_Action
protected function _initOrder()
{
$id = $this->getRequest()->getParam('order_id'); ///TROUBLE HERE
$order = Mage::getModel('sales/order')->load($id);
if (!$order->getId()) {
$this->_getSession()->addError($this->__('This order no longer exists.'));
$this->_redirect('dash/sales_order');
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return false;
}
Mage::register('sales_order', $order);
Mage::register('current_order', $order);
return $order;
}
public function approvecodAction() {
if ($order = $this->_initOrder()) {
try {
$order->setStatus('codapproved')
->save();
$this->_getSession()->addSuccess(
$this->__('The order has been approved for COD.')
);
}catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}catch (Exception $e) {
$this->_getSession()->addError($this->__('The order has not been approved for COD.'));
Mage::logException($e);
}
$this->_redirect('*/sales_order/view', array('order_id' => $order->getId()));
}
}
Note I copied the above two functions from app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php and modified for my purpose.
Please tell me how and where to set the parameter order id? Or if they are getting set, then how to get them?
Thanks!
You're dealing with a mass action callback on the controller, so you will be getting an array of values in the parameter instead of a single value. You're going to need to do something more like this in your action method:
public function approvecodAction() {
$orderIds = $this->getRequest()->getPost('order_ids', array());
foreach ($orderIds as $orderId) {
$order = Mage::getModel('sales/order')->load($orderId);
try {
$order->setStatus('codapproved')
->save();
$this->_getSession()->addSuccess(
$this->__('The order has been approved for COD.')
);
}catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}catch (Exception $e) {
$this->_getSession()->addError($this->__('The order has not been approved for COD.'));
Mage::logException($e);
}
}
$this->_redirect('*/sales_order/view', array('order_id' => $order->getId()));
}
Hope that helps!