Get customer object on an event - magento

I’m trying to createan observer on the following event.:
‘sales_order_payment_pay’.
However according to magento doc
http://www.magentocommerce.com/wiki/5_-_modules_and_development/reference/magento_events
I don’t have so much parameters avalaible on this event..
Do you have any idea how I could retrieve the customer object (i would need info such as customer id and customer email)?
Thanks for your feedback and anyway I wish you a nice day,
Anselme

This event does expose the payment object, so you should be able to chain off of that to get the object you want:
public function yourObserverFunction($event) {
$payment = $event['payment'];
$customer = $payment->getOrder()->getCustomer();
// ... do something useful
}
Generally objects in Magento can be chained like this, and now your code doesn't rely on the event being triggered from a customer session (which is not a good assumption anyway).
Hope that helps!
Thanks,
Joe

Every event exposes different objects inside of the $observer object that is passed around. In Magento you can often get a lot of stuff by referring to any number of objects that are in the request or session. In this case there is a customer/session object (Mage_Customer_Model_Session) which has the customer attached.
if(Mage::getSingleton('customer/session')->isLoggedIn()){
Mage::getSingleton('customer/session')->getCustomer();
}

Related

Deleting customer addresses in magento

I need to delete customer addresses programmatically, but I didn't find a function to do that.
$recordedAddresses = array();
foreach ($customer->getAddresses() as $address)
{
$recordedAddresses = $address->toArray();
}
I already took the addresses' collection as showed above, I just wanna delete them by id.
Curiously I didn't find examples but using API.
Could someone gimme a hand with that?
Somehow Magento keeps empty entities after using $address->delete() in my case. There were empty addresses on account preventing admin from saving the customer form when using this method.
Only way I've found to actually remove the address from user account is by changing the protected $_isDeleted flag to true:
$address = Mage::getModel('customer/address')->load($addressId);
$address->isDeleted(true);
Hope it saves some time for anyone who will stumble uppon same Magento behaviour.
Have a look at the Mage_Customer_AddressController controller class and deleteAction() method. Essentially all you need to is load the address by it's id:
$address = Mage::getModel('customer/address')->load($addressId);
and then delete it:
$address->delete();
delete() is a standard method you can run against all models (see Mage_Core_Model_Abstract), you can also set the _isDeleted flag and call save() which will have the same result.

How to get payment method in an observer in Magento?

I have an observer that handles the event: sales_payment_invoice_pay (or something like that).
What I'm trying to do is to send an invoice if the payment method is PayPal.
Everything is ok in version 1.4~ by doing $observer->getEvent()->getOrder()->getPayment->getMethodInstance().
In version 1.5+ however I can't seem to find any solutions.
I also tried with getData() but without any results.
Any help is appreciated. thanks
Calling me super desperate for an answer would be an understatement.
It looks like the only data passed in to the sales_order_invoice_pay event is $this, which will be the sales/order_invoice model. I found this by searching through the Magneto core code, it's fired off in Invoice.php like so:
Mage::dispatchEvent('sales_order_invoice_pay', array($this->_eventObject=>$this));
Looking at a similar event (sales_order_invoice_register) which has an observer in the core (of Enterprise, at least - increaseOrderGiftCardInvoicedAmount() in GiftCardAccount) you can access the Invoice object like this in your Observer method:
$invoice = $observer->getEvent()->getInvoice();
The invoice is all you will be able to get though, since it's the only thing passed to the Observers by dispatchEvent(). You cannot directly access the order, like you are trying to do.
Looking at the Invoice model, however, it appears to have a nice getOrder method, which should do the trick. I haven't tested it, but try this:
$observer->getEvent()->getInvoice()->getOrder()->getPayment->getMethodInstance();
Cheers and good luck!
i can get the payment method code using this
$observer->getEvent()->getInvoice()->getOrder()->getPayment()->getMethodInstance()->getCode()
user this code:$order->getPayment()->getMethodInstance()->getCode() ;

How do I get the shipping method the user has chosen during checkout?

I want to get the name of the shipping method the user has chosen during checkout. Does anyone know how to retrieve that info?
This will get it to some extent but it is cached:
Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingDescription();
When I am on the onestep checkout and I go back to the shipping tab and change the shipping, it is still holding the old shipping method. I need to figure out how to get the current one.
Foreword
Constructed from Magento app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method/Available.php and others:
app/design/frontend/base/default/template/checkout/onepage/shipping_method/available.phtml uses this code to determine which shipping method was selected:
$this->getAddressShippingMethod()
app/code/core/Mage/Checkout/Block/Onepage/Shipping/Method/Available.php expands that code to this:
return $this->getAddress()->getShippingMethod();
Let's research a bit and expand it even deeper:
$this->getQuote()->getShippingAddress()->getShippingMethod();
Parent block expands method getQuote():
return $this->getCheckout()->getQuote();
And deeper:
public function getChechout() {
return Mage::getSingleton('checkout/session');
}
Merging all that code gives us this:
Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingMethod()
That gives you the shipping method code. Giving that, you could manipulate it just as you wish. This data is stored within the database, so when you change shipping method, the code changes too.
Getting deeper and deeper!
If you've ever created your own shipping method, you'd know, that it has the method called collectRates().
It fills a set of shipping/rate_result_method models, stores it within the instance of shipping/rate_result model and returns it (you can get each model' instance using Mage::getModel(<model i've named>); ).
Yet, note: one could contain multiple rate_result_method instances, while the shipping method code is the same for all those instances!
Thus, in order to get the description, you need to get one of the rate_result_method instances and retrieve its methodTitle or carrierTitle.
After a small researching i've found how to retrieve all these rates:
Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingRatesCollection()
This will provide you with a collection of all rates for the selected shipping method. You can operate it with getItems() and get a hash. Or you could use getFirstItem() and use it as the template.
Anyway, let's assume u've retrieved some item of that collection and stored it within the $rate variable:
$rate->getCarrier(); // This will provide you with the carrier code
$rate->getCarrierTitle(); // This will give you the carrier title
$rate->getCode(); // This will give you **current shipping method** code
$rate->getMethod(); // This will provide you with the **shipping method** code
$rate->getMethodTitle(); // This will tell you current shipping method title
$rate->getMethodDescription(); // And this is the description of the current shipping method and **it could be NULL**
That's all, folks!
I am really sorry for my poor English and for my strange mind flow. Hope this will help you or someone else. Thanks!
Just in case you need it still. You can get shipping method from order by:
$order->getShippingMethod();
Of course how you get your $order depends on context.
Also you can get description by:
$order->getShippingDescription();
shipping method in magento
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$options = array();
foreach($methods as $_code => $_method)
{
if(!$_title = Mage::getStoreConfig("carriers/$_code/title"))
$_title = $_code;
$options[] = array('value' => $_code, 'label' => $_title . " ($_code)");
}
echo "<xmp>";
print_r($options);
echo "</xmp>";
In your checkout controller you need to add extra steps to save your quote if you want this information to be accessible to you.
I added a few '$quote->save();' entries to get this to work, however, I cannot definitively say which entry is the one that did the fix. I also cannot find the link on Magento forums, however, I hope I have given you a head start on what is going on.
You could override the saveShippingMethodAction() function in the Mage_Checkout_OnepageController, or extend upon it, and save the method into the registry by inserting:
Mage::register('blahShippingMethod', $this->getRequest()->getPost('shipping_method'));
and call upon it as you need it: Mage::registry('blahShippingMethod');
Don't forget to unset it when you no longer need it as you will run into an error if you try to reset when it's already been set.
Mage::unregister('blahShippingMethod');

What does Load mean in Magento Objects?

I m trying to learn coding a bit through Magento, and I have to admit that I'm a bit confused about this notion of object chaining in it.
In fact I don't understand when to do a load and when I can avoid it. For exemple:
$product = Mage::getModel('catalog/product')->load($item->getProductId());
I would like to get the info of product from a product ID in this case; why do I need to load it? ($item is the loop of all the products of an order)
And here I don't need to do any load:
$customer = $payment->getOrder()->getCustomer();
I'm sorry in advance for my stupid question: What does load do comparing to my second example? Thanks a lot and have a nice day,
Anselme
Behind the scenes a method like $payment->getOrder() is effectively (after checking to see if it's already loaded) doing this:
return Mage::getModel('sales/order')->load($this->getOrderId());
// $this in this context is $payment
So a load is still needed to retrieve the relevant data from the database, the getOrder() method is just a convenience. The load() method itself returns it's class instance, which is why you can assign it to $product in your first example. The getOrder() and getCustomer() methods don't return themselves, they return a different object, which is why $payment is not assigned to $customer in your second example.
The Mage::getModel() method is only responsible for determining the correct class and creating a blank instance of it. Instead of a load you could instead set it's data with a setData() call, passing a keyed array of values. All of the setters return their object, just like load() does.
$customer = $payment->getOrder()->getCustomer();
It means the id of the customer is already present in the session, so you don't need to explicitly tell magento to load the customer.
In the products case, you have to tell magento the product id of the product you want to get details of.

Magento View 'Company Name' Instead Of First/Last Name

Can Magento view/manage our customers by their business name in addition to their contact names to find them easily? It is being used for B2B, so when emails go out they are pulling the customer’s name, instead of the company name which is more appropriate.
Is this a global setting?
thanks in advance.
Magento stores business name on the customer's address by default, so it's a little harder to get to.
There's no reason you cannot add another customer field to put the company name on the customer record itself. That way you'll have no problem accessing it, and can change other screens in the system to reflect it.
If you don't want to go to those lengths, you could always implement a method that pulls the company name from the default address, and save it into the session by default, for easier retrieval.
EDIT: Better idea.
Looking through the sales email templates, there are two methods that are used to grab a customer's name:
$order->getCustomerName();
$order->getBillingAddress()->getName();
I don't see any separate references to the company name, so you should be able to substitute these two methods for your own and get the desired outcome. You'll need to create your own module and override the models for customer/address and sales/order (others have covered this in depth elsewhere). Then create methods that look something like this:
public function getCustomerName() {
if($this->getBillingAddress()->getCompany()) {
return $this->getBillingAddress()->getCompany();
}
return parent::getCustomerName();
}
That's the example for sales order, modify accordingly for customer. Now your company names will be used whenever available, and when they aren't the fallback will be to the original implementation (customer name).
Hope that helps!
Thanks,
Joe
You are correct about the universal application. If you did want just the emails, the concern is whether you have access to your custom function where you need it. If there's no object handy, I'm not positive that you will be able to call just any method that you need to.
An approach that would work in this case would be to override the two objects mentioned below, but to instead add a getCompanyName method to them. That way, you'll have the right objects to call, and you can edit the emails specifically to taste.

Resources