Hello Guys. Can someone tell me how to get the shipment increment id by order id in Magento ?
I need this because I use an outside php file to add tracking information to a shipment and it needs the shipment id for this.
Thank you for all your help.
I am using the code below to add tracking info
$shipmentIncrementId='300000002';
$trackNumber='123456';
$carrier='custom';
$title='server10';
$shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentIncrementId);
/* #var $shipment Mage_Sales_Model_Order_Shipment */
$track = Mage::getModel('sales/order_shipment_track')
->setNumber($trackNumber)
->setCarrierCode($carrier)
->setTitle($title);
$shipment->addTrack($track);
try {
$shipment->save();
} catch (Mage_Core_Exception $e) {
$thiss->_fault('data_invalid', $e->getMessage());
}
return $track->getId();
print_r($shipment);
In theory an order can have more than one shipment. But if you make a convention to always have one single shipment per order you can get its increment id like this:
$orderIncrementId = 120000012;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$shipment = $order->getShipmentsCollection()->getFirstItem();
$shipmentIncrementId = $shipment->getIncrementId();
Related
controller/front/validation.php
<?php
class Paytr_CheckoutValidationModuleFrontController extends ModuleFrontController
{
public function postProcess()
{
$this->display_column_left = false;
$this->display_column_right = false;
$cart = $this->context->cart;
$total = $cart->getOrderTotal;
$currency = $this->context->currency;
$customer = new Customer( $cart->id_customer );
if ( !Validate::isLoadedObject($customer) )
Tools::redirect('index.php?controller=order&step=1');
//$this->context->cart->delete();
//$isOrderX = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT * FROM '._DB_PREFIX_.'orders WHERE id_cart = '.$cart->id);
//var_dump($_POST);
//Tools::redirect('index.php?controller=history');
//Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.(int)$this->module->currentOrder.'&key='.$customer->secure_key);
echo 'index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.(int)$this->module->currentOrder.'&key='.$customer->secure_key;
}
}
I need to find order id from cart id. These are I tried. I couldnt get id_order. I was hopeful for Db query. But it doesnt work I think.
You can get it with this code: $id_order = Order::getOrderByCartId($id_cart);
this is the problem cause deletes cookie after validate order. So It doesnt show id_cart. So I figure out like this.
$isOrderX = Db::getInstance()->getRow(' SELECT * FROM '._DB_PREFIX_.'orders WHERE id_customer = '.$cart->id_customer.' ORDER BY id_order DESC ');
Tools::redirect('index.php?controller=order-confirmation&id_cart='.$isOrderX['id_cart'].'&id_module='.$this->module->id.'&id_order='.$isOrderX['id_order'].'&key='.$customer->secure_key);
As long as the order is not registered, you can not get "id_order".
If the order is registered and you are sure that there is no better way, you can use the following code to find the latest cart that has been ordered:
$this->context->customer->getLastCart(true);
I want to add Order search functionality in customer account My Orders section. As if customer have many orders so they dont need to navigate instead of they can search by orders like this -
http://demo.dckap.com/m2/sales/order/history/
I tried to get customer session in Magento_Sales/templates/order/history.phtml page but its not working.
Is there any way we can pass input search box value to order object ?
Or Load customer orders collection ?
you need to override few files. you can try with below code, it should work.
for view access, override canView() function defined in Magento\Sales\Controller\AbstractController\OrderViewAuthorization.php
//overide getOrders() method in history.php block file as below
// to get customer id from customer session
if (!($customerId = $this->_customerSession->getCustomerId())) {
return false;
}
// to load orders for customer
$this->orders = $this->_orderCollectionFactory->create()->addFieldToFilter('customer_id', array('eq' => $customerId));
//to add filter for search
if (!empty(<yoursearchterm>)) {
$this->orders->addFieldToFilter(
'entity_id', ['like' => '%' . <yoursearchterm> . '%']
);
}
and finally add below line
return $this->orders;
Next you will need to override history.phtml and add your search boxes inside form. you can set action like below
action="<?php echo $block->getUrl('sales/order/history'); ?>"
Hope this helps!!
This is my solution to load logged In customer orders collection -
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
$customer_id = $customerSession->getCustomer()->getId();
$order_collection = $objectManager->create('Magento\Sales\Model\Order')->getCollection()->addAttributeToFilter('customer_id', $customer_id)->addAttributeToFilter('increment_id', array('eq' => $orderId));
}
Then after that I have replace order collection with my order collection $order_collection to get desired search order value from text box.
I'm using sales_order_shipment_save_after observer to collect tracking numbers. I have tried $event->getOrder but it will not load any order object. I suppose it's the shipment observer I use as opposed to order observer. Usually, getId or getIncrementId on Order would ok. Right now I was able to get tracking number and shipment ID just fine. Is there a way to get order ID from shipment ID in Magento?
Here is what I got
$shipment = $event->getShipment();
$tracks = $shipment->getAllTracks();
foreach ($tracks as $track) {
$orderTracking = $track->getTrackNumber();
}
need to try below code
$shipment = $observer->getEvent()->getShipment();
$order = $shipment->getOrder();
$shippingMethod = $order->getShippingMethod();
I am try to get order details form shipment object
Your function , should like this
public function you_function_name(Varien_Event_Observer $observer)
I need to change Magento default workflow. So, I should automatically create shipping as soon as customers buy something.(when customers see Receipt page). I am not sure where should I start. I started googling for some extension, but no luck for now. That's why I came here. Does anyone have an idea where can I start resolving this problem? Thanks!
You should never put this kind of code in view files. Besides it being bad practice in general, as #user2729065 mentioned: if the customer does not return to the thank you page after the payment, the code will not be run.
Better is to create a custom module with an observer. To do this, add the following code to your module etc/config.xml file:
<global>
<events>
<sales_order_invoice_pay>
<observers>
<[my]_[module]_automatically_complete_order>
<class>[module]/observer</class>
<method>automaticallyShipCompleteOrder</method>
</[my]_[module]_automatically_complete_order>
</observers>
</sales_order_invoice_pay>
</events>
</global>
Change my_module to your module name. This will triger when an invoice is paid.
Then create the Observer in My/Module/Model/Observer.php
<?php
class My_Module_Model_Observer
{
/**
* Mage::dispatchEvent($this->_eventPrefix.'_save_after', $this->_getEventData());
* protected $_eventPrefix = 'sales_order';
* protected $_eventObject = 'order';
* event: sales_order_invoice_pay
*/
public function automaticallyShipCompleteOrder($observer)
{
$order = $observer->getEvent()->getInvoice()->getOrder();
if ($order->getState() == Mage_Sales_Model_Order::STATE_PROCESSING) {
try {
$shipment = $order->prepareShipment();
$shipment->register();
$order->setIsInProcess(true);
$order->addStatusHistoryComment('Shippment automatically created.', false);
Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
} catch (Exception $e) {
$order->addStatusHistoryComment('Could not automaticly create shipment. Exception message: '.$e->getMessage(), false);
$order->save();
}
}
return $this;
}
}
This will check if the order is still in Processing ( the state it gets after it is paid for.). And if so, try to create the shipment. After the shipment is created, the order will automatically change its state to completed.
If you want the shipment to get created directly after the order is placed (before the invoice is created and paid for.), change
<sales_order_invoice_pay>
in
<sales_order_place_after>
in config.xml. And because this observer returns an order and not an invoice, also change:
$order = $observer->getEvent()->getInvoice()->getOrder();
to
$order = $observer->getEvent()->getOrder();
Code is based on an example from Inchoo so most credits go to them.
I found a solution. I guess this is not the best way to do it, but it works.
In file your_theme_name/template/checkout/success.phtml
add this code
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order') -> loadByIncrementId($orderId);
if ($order -> canShip()) {
$itemQty = $order -> getItemsCollection() -> count();
$shipment = Mage::getModel('sales/service_order', $order) -> prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment -> create($orderId);
}
?>
That will add shipping for the order on receipt page.
To put code in a template is a really bad idea: it adds the Shipping code to your Template / View. This functionality doesn't belong there. (For instance: if the payment is confirmed after 5 minutes it doesn't work).
Solution is to write an Observer to the Payment-Success event:
http://inchoo.net/ecommerce/magento/magento-orders/automatically-invoice-ship-complete-order-in-magento/
I want to get a shipping/billing address id from a just complete order out of Magento.
I have tried the following code but it's not worked:
Mage::getModel('sales/order')->load($array_data["order_id"])->getShippingAddressId()
Does someone have any ideas?
The following might help someone looking for a similar solution:
// Get the id of the last order for the current user(session)
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
// If an order actually exists
if ($orderId) {
//Get the order details based on the order id ($orderId)
$order = Mage::getModel('sales/order')->load($orderId);
// Get the id of the orders shipping address
$shippingId = $order->getShippingAddress()->getId();
// Get shipping address data using the id
$address = Mage::getModel('sales/order_address')->load($shippingId);
// Display the shipping address data array on screen
var_dump($address);
}
Note: Obviously this solution requires the user to have a current session
Good luck.
First, break apart your chained call to make make sure you're actually loading an order with
$order = Mage::getModel('sales/order')->load($array_data["order_id"]);
var_dump($order->getData());
Assuming you've loaded the order, look at the values dumped above. There's no shipping_address_id. That, combined with there being no method getShippingAddressId on a Mage_Sales_Model_Order is why your code isn't working.
Try
$order = Mage::getModel('sales/order')->load($array_data["order_id"]);
$id = $order->getShippingAddress()->getId();
The getShippingAddress address method will return an address object, which you can inspect for its id. If you look at the Mage_Sales_Model_Order class definition, you can see the method definitions
//magento 1.4
public function getShippingAddress()
{
foreach ($this->getAddressesCollection() as $address) {
if ($address->getAddressType()=='shipping' && !$address->isDeleted()) {
return $address;
}
}
return false;
}
public function getAddressesCollection()
{
if (is_null($this->_addresses)) {
$this->_addresses = Mage::getResourceModel('sales/order_address_collection')
->addAttributeToSelect('*')
->setOrderFilter($this->getId());
if ($this->getId()) {
foreach ($this->_addresses as $address) {
$address->setOrder($this);
}
}
}
return $this->_addresses;
}
The TL;DR for the code above is, address IDs aren't stored with the orders model. The addresses for all orders are stored as a sales/order_address or Mage_Sales_Model_Order_Address object.
$order = Mage::getModel('sales/order')->load($orderId);
//Get shipping address Id
$order->getShippingAddress()->getId();
//format output
echo $order->getShippingAddress()->format('html');
//Get shipping address data
print_r($order->getShippingAddress()->getData());
After uncountable debugging and googling, I got it solved:
For incremental order address id based on order,
$order_id=Mage::getSingleton('checkout/session')->getLastRealOrderId();
$sales_order=Mage::getModel('sales/order')->load($order_id);
$billing_address_id=$sales_order->billing_address_id;
$shipping_address_id=$sales_order->shipping_address_id;
For address entity id of the order based on customer,
$quote = Mage::getSingleton('checkout/session')->getQuote();
$billing_address_id=$quote->getBillingAddress()->customer_address_id;
$shipping_address_id=$quote->getShippingAddress()->customer_address_id;
Try This, you can get the shipping_address_id and billing_address_id
$orderCollection = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('main_table.customer_id',$session->getId());
echo "<pre>";
foreach ($orderCollection as $order){
$shippingAddress = Mage::getModel('sales/order_address')->load($order->getShippingAddressId());
$billingAddress = Mage::getModel('sales/order_address')->load($order->getBillingAddressId());
print_r($order->getData());
print_r($shippingAddress->getData());
print_r($billingAddress->getData());
}