event observers examples

example#1
Making use of Observers in Magento
December 15, 2012 Permalink

When developing for Magento, often most peoples first action is to override a particular class or method from the core. They also usually use the same namespaces and copy into the local folder like: local/Mage/Sales/Model/Orders.php for example. While this is handy for a lot of things, often people don’t know, forget about, or don’t know how to make use of an Observer when that is 9 times out of 10 the better approach.

In this little tutorial I’ll teach you how to create an observer, and you’ll also be able to figure out for yourself when to use them too. Awesome stuff, let’s get started.
What is an Observer anyway?

In a nutshell: An Observer in Magento listens for when specific events fire, and then executes code we have defined to listen to that observer.

What this allows us to do is create more speration of our code. Especially if it’s something we don’t really want coded directly into other modules or having to override core functionality which could make it very difficult for you to upgrade in the future.
How do I find what events exist in Magento?

Figuring out how to find these events is relatively simple. We first need to know how Magento fires events and that is done like this:

Mage::dispatchEvent(‘event_name’, array(‘data’ => $data));

With that we can simply do a search in all of our files to return all the events. You can run this command on Linux/Mac:

grep -r “dispatchEvent(” /path/to/magento/install/

Alterntively if you’re using Sublime Text 2 or a similar IDE where you can search file contents across an entire project search for dispatchEvent and you’ll start to see the results pouring in.

This is fantastic, however it’s tricky to digest all this information. Luckily for you there is a fantastic little cheat sheet generated by Nick Jones over on his site. He maintains this and is generally up-to-date and is a fantastic reference. His cheatsheet will show you which file, line and what event is called.
Okay, now how do I create an observer?

By now you will have found the event you’re looking for. Now is the time to create our observer in order to execute our desired code! Let’s get started.

To do this we will be creating our own module. If you’re not familiar with creating your own module don’t worry, I’ll cover the basics but I won’t be going into too much detail.

Before we get started, my example below uses the sales_order_place_before event which is called just before the order is saved. We could do numerous things at this stage such as add additional meta data to the order. In my example, we’ll simply output to our log.
Step 1) Create main module xml file

We need to create a file called Meteorify_Observerexample.xml in app/etc/modules.

<?xml version=”1.0″?>
<config>
<modules>
<Meteorify_Observerexample>
<codePool>local</codePool>
<active>true</active>
</Meteorify_Observerexample>
</modules>
</config>

This file allows Magento to recongise the modules existence and is where we can deactivate it (by changing <active>true</active> to <active>false</active>)
Step 2) Create folder structure for our module

We need to create the folders where our modules code will live. To do this create the following directories:

mkdir app/code/local/Meteorify/
mkdir app/code/local/Meteorify/Observerexample/
mkdir app/code/local/Meteorify/Observerexample/etc
mkdir app/code/local/Meteorify/Observerexample/Model

Quick explaination of the module folder structure. Meteorify represents the company or group, then Observerexample is our actual module. etc will contain various configuration files which instructs Magento how to read/use our module. Model contains our various Model classes which our module might use (in this case we will have a Observer.php file in the Model folder).
Step 2) Create our module’s configuration file

Each module requires a file called config.xml this file lives in app/code/local/Meteorify/Observerexample/etc

<?xml version=”1.0″?>
<config>
<modules>
<Meteorify_Observerexample>
<version>0.0.1</version>
</Meteorify_Observerexample>
</modules>
<global>
<models>
<meteorifyobserverexample>
<class>Observerexample_Model</class>
</meteorifyobserverexample>
</models>
<events>
<sales_order_place_before>
<observers>
<meteorify_observerexample_model_observer>
<type>singleton</type>
<class>Meteorify_Observerexample_Model_Observer</class>
<method>example</method>
</meteorify_observerexample_model_observer>
</observers>
</sales_order_place_before>
</events>
</global>
</config>

The above code is our basic config for our model. If you stick to similar naming conventions you’ll get on by fine here.

The main code I’d like to highlight here is contained between the <events> tags. The first tag in represents our event we decided to use earlier on sales_order_place_before, so within here we are defining what to do when that event is fired. Within the <observers> tag we have the set up for our Observer. The value within <class> represents the class name of our Observer, and then the value in <method> is the method (or function) we will run when that event is fired.
Step 4) Creating our Observer.php

Now we can create our Observer and place our code inside our method we will create. To do this create a file named Observer.php in app/code/local/Meteorify/Observerexample/Model and place the following code:

<?php
class Meteorify_Observerexample_Model_Observer {

public function example($observer) {
//$observer contains data passed from when the event was triggered.
//You can use this data to manipulate the order data before it’s saved.
//Uncomment the line below to log what is contained here:
//Mage::log($observer);

Mage::log(‘We just made an Observer!’);
}

}
?>

Easy as that.

Now all you need to do is clear the cache, make sure log’s are enabled in System > Configuration > Advanced > Developer > Logging and then go through the checkout and then check the logs in var/log.

I’ve put the completed module onto my github profile, so go ahead and check it out: Observer Example Magento

============================================================================================
example#2

Magento observer examples

When it comes to customize the magento code, there are following 4 options:
1. Creating a observer should be the first to consider.
2. Extending and overriding the core modules should be the second to consider when option 1 cannot fails to accomplish the objectives.
3. Copy the core class to the local directory and put it in the same directory path it was in core directory, this is should be avoided.
4. Modify the core class directly, this should definitedly be avoided unless you are just trying to test a code snippet.

So, there are really only two recommended options which is to try to create an observer first,
if it doesn’t work out then write a module to extend and override the core module.

Here is an example of how to create an observer in Magento. This module has two observer:
First one: When observed a product is added to the cart, print some messages.
Second one: To observe when a product review is submitted.
The default Magento behavior is to save the product review with PENDING status,
this observer will auto approve the submitted product review instead.

1. Create a xml file app/etc/modules/MyExtensions_Observerdemo.xml

<?xml version=”1.0″?>
<config>
<modules>
<MyExtensions_Observerdemo>
<active>true</active>
<codePool>local</codePool>
</MyExtensions_Observerdemo>
</modules>
</config>

2. Create a xml file app/code/local/MyExtensions/Observerdemo/etc/config.xml

<?xml version=”1.0″?>
<config>
<modules>
<MyExtensions_Observerdemo>
<version>0.1.0</version>
</MyExtensions_Observerdemo>
</modules>
<global>
<models>
<myextensions_observerdemo>
<class>MyExtensions_Observerdemo_Model</class>
</myextensions_observerdemo>
</models>
<events>
<checkout_cart_product_add_after>
<observers>
<MyExtensions_Observerdemo_Model_Observer>
<type>singleton</type>
<class>MyExtensions_Observerdemo_Model_Observer</class>
<method>addtocartEvent</method>
</MyExtensions_Observerdemo_Model_Observer>
</observers>
</checkout_cart_product_add_after>

<review_save_before>
<observers>
<MyExtensions_Observerdemo_Model_Observer>
<type>singleton</type>
<class>MyExtensions_Observerdemo_Model_Observer</class>
<method>autoApproveReview</method>
</MyExtensions_Observerdemo_Model_Observer>
</observers>
</review_save_before>
</events>
</global>
</config>

In the above xml file, the tag global means any configuration inside this tag
applys to anything happening in frontend or backend (admin panel).
This tag can be changed to frontend because the events checkout_cart_product_add_after
and review_safe_before both happens on the frontend.
Using global is also fine because global applys to both frontend and backend.
There is another tag adminhtml, if we change the above global tag to adminhtml,
the observer will not fire on the
events checkout_cart_product_add_after and review_safe_before because
anything inside adminhtml only applys to events happening on the backend. In short:

<global> applys to both frontend and backend
<fronend> applys only applys to frontend
<adminhtml> applys only applys to backend

3. Create a php file app/code/local/MyExtensions/Observerdemo/Model/Observer.php

<?php

class MyExtensions_Observerdemo_Model_Observer {

public function addtocartEvent(Varien_Event_Observer $observer) {

$event = $observer->getEvent();  //Gets the event
$product = $event->getProduct();
$observermsg = “The event triggered>>> <B>” . $event->getName() . “</B><br/> The added product>>> <B> ” . $product->getName().”</B>”;
//Adds the message to the shopping cart
echo Mage::getSingleton(‘checkout/session’)->addSuccess($observermsg);
}

public function autoApproveReview(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$reviewObjData = $event->getData();
//print_r($reviewObjData);exit;

$reviewData=$reviewObjData[“data_object”];
$reviewData->setStatusId(Mage_Review_Model_Review::STATUS_APPROVED);

echo Mage::getSingleton(‘core/session’)->addSuccess(“Thank you for your input!!”);
}
}

4. Clear cache, go to the frontend, add a product and submit a review to see what happens.
Getting the website and store IDs and their names in Magento Solr installation under Tomcat

===================================================================================================================

<block type=”review/product_view_list” name=”product.info.product_additional_data” as=”product_review” template=”review/product/view/list.phtml”>
<block type=”review/form” name=”product.review.form” as=”review_form”/></block>

===================================================================================================================

example # 3
Im starting to understand how Magento Event Observers work and hoping someone could help me figure out what Event I would need to seek out to get my potential module to work. I have certain products that have an attribute called “child skus” which is an array of SKU numbers of other products in my inventory.

Example:

Name: Totally Awesome Product

SKU: TP-1212

Child SKUS: GP-3232,FD-4332,VC-5332

Every time someone purchases TP-1212 I also need Magento to deduct that
quantity from those child skus behind the scenes.
Does anyone know if there is an event dispatcher for after a purchase
has been completed that would handle something like that??

This is a little tricky and there are most likely some edge cases not covered
in the below code – Also the answer assumes the following:

You wish to reduce the stock level of all associated products of the parent just purchased
You wish to reduce by only 1
There are no further complications or other conditions that must be met/dealt with

Code:

So, you obviously need to create a module first. The config.xml needs
to declare the observer which will listen to checkout_type_onepage_save_order_after.
(Note: there are other events you can listen to in order to achieve your goal).

The config.xml will contain the following code at a minimum:

<?xml version=”1.0″?>
<config>
<modules>
<YourCmpany_YourModule>
<version>1.0.0</version>
</YourCmpany_YourModule>
</modules>
<frontend>
<events>
<checkout_type_onepage_save_order_after>
<observers>
<yourmodule_save_order_observer>
<class>YourCompany_YourModule_Model_Observer</class>
<method>checkout_type_onepage_save_order_after</method>
</yourmodule_save_order_observer>
</observers>
</checkout_type_onepage_save_order_after>
</events>
</frontend>
<global>
<models>
<yourmodule>
<class>YourCompany_YourModule_Model</class>
</yourmodule>
</models>
</global>
</config>

<?php

class YourCompany_YourModule_Model_Observer
{
public function checkout_type_onepage_save_order_after(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();

/**
* Grab all product ids from the order
*/
$productIds = array();
foreach ($order->getItemsCollection() as $item) {
$productIds[] = $item->getProductId();
}

foreach ($productIds as $productId) {

$product = Mage::getModel(‘catalog/product’)
->setStoreId(Mage::app()->getStore()->getId())
->load($productId);

if (! $product->isConfigurable()) {
continue;
}

/**
* Grab all of the associated simple products
*/
$childProducts = Mage::getModel(‘catalog/product_type_configurable’)
->getUsedProducts(null, $product);

foreach($childProducts as $childProduct) {

/**
* in_array check below, makes sure to exclude the simple product actually
* being sold as we dont want its stock level decreased twice 🙂
*/
if (! in_array($childProduct->getId(), $productIds)) {

/**
* Finally, load up the stock item and decrease its qty by 1
*/
$stockItem = Mage::getModel(‘cataloginventory/stock_item’)
->loadByProduct($childProduct)
->subtractQty(1)
->save()
;
}
}
}
}
}
===============================================================================================================
example # 4

In the previous article we studied about the basics of Magento Event observers.
Before moving further with this article, I am assuming that you are aware about the
basics of Magento Event Observers, if not then kindly click here to understand
the basics of Magento Event observers.

In this article we are going to understand event observers for customer registration
success in magento with simple implementation.

Note : We will add our custom logic to override core logic without changing any core
module code.

Lets create a sample module that triggers an event whenever new customer is registered
to the magento website. We will write our own observer (Event Observer) to handle
this event. Observer contains the method that invokes immediately after
customer registration success.

Implementation Steps :

Step 1 : Create Required folders.

Create below folders in app/code/local/Wli/Registrationdemo/etc,
app/code/local/Wli/Registrationdemo/Model.

Wli is company name & Registration demo is module name.
You can use your own company name & module name instead of above specified.

Step 2 : Activate Module through module xml file.

Magento requires xml file that tells to magento to look into it and
call your custom module based on the xml.
So lets create module xml file Wli_Registrationdemo.xml
and place the file into the app/etc/modules directory.

<?xml version=”1.0″?>
<config>
<modules>
<Wli_Registrationdemo>
<active>true</active>
<codePool>local</codePool>
</Wli_Registrationdemo>
</modules>
</config>

Step 3 : Create Configuration XML file.

Next step is to create module configuration file config.xml and
place it in app/code/local/Wli/Registrationdemo/etc folder which we have created earlier.

<config>
<modules>
<Wli_Registrationdemo>
<version>0.1.0</version>
</Wli_Registrationdemo>
</modules>
<global>
<events>
<customer_register_success>
<observers>
<Wli_Registrationdemo_customer_register_success>
<type>singleton</type>
<class>Wli_Registrationdemo_Model_Observer</class>
<method>customerRegisterSuccess</method>
</Wli_Registrationdemo_customer_register_success>
</observers>
</customer_register_success>
</events>
</global>
</config>

Step 4 : Create Model Class (Observer) file.

<?php
class Wli_Registrationdemo_Model_Observer {
public function customerRegisterSuccess(Varien_Event_Observer $observer) {
$event = $observer->getEvent();
$customer = $event->getCustomer();
$email = $customer->getEmail();
if($email) {
//Create custom code over here as per your requirements !
}
}
}
?>

multiple customer attribute & increment login count

config.xml


<?xml version=”1.0″?>
<config>
<modules>
<Shailendra_CustomField>
<version>0.1.0</version>
</Shailendra_CustomField>
</modules>
<frontend>
<routers>
<customfield>
<use>standard</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
<layout>
<updates>
<customfield>
<file>customfield.xml</file>
</customfield>
</updates>
</layout>
</frontend>
<admin>
<routers>
<customfield>
<use>admin</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
</admin>
<global>
<fieldsets>
<customer_account>
<occupation>
<to_quote>occupation</to_quote>
<to_quote>logincount</to_quote>
</occupation>
</customer_account>
</fieldsets>
</global>
<global>
<fieldsets>
<customer_account>
<occupation><create>1</create><update>1</update><name>1</name></occupation>
<logincount><create>1</create><update>1</update><name>1</name></logincount>
</customer_account>
</fieldsets>
</global>
<global>
<models>
<customfield>
<class>Shailendra_Customfield_Model</class>
</customfield>
</models>
<events>
<sales_quote_save_before>
<observers>
<customfield_sales_order_observer>
<type>singleton</type>
<class>Shailendra_Customfield_Model_Observer</class><!– I’ve also tried Feed_Sales_Model_Order_Observer here –>
<method>export_new_order</method>
</customfield_sales_order_observer>
</observers>
</sales_quote_save_before>
<customer_login>
<observers>
<shailendra_customfield_customer_login>
<type>singleton</type>
<class>Shailendra_Customfield_Model_Observer</class>
<method>CustomerLogin</method>
</shailendra_customfield_customer_login>
</observers>
</customer_login>
</events>
<resources>
<customfield_setup>
<setup>
<module>Shailendra_CustomField</module>
<class>Mage_Customer_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</customfield_setup>
<customfield_write>
<connection>
<use>core_write</use>
</connection>
</customfield_write>
<customfield_read>
<connection>
<use>core_read</use>
</connection>
</customfield_read>
</resources>
</global>
</config>

mysql4-install-0.1.0.php


<?php
$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup(‘core_setup’);

$entityTypeId     = $setup->getEntityTypeId(‘customer’);
$attributeSetId   = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);

$setup->addAttribute(‘customer’, ‘occupation’, array(
‘input’         => ‘text’, //or select or whatever you like
‘type’          => ‘int’, //or varchar or anything you want it
‘label’         => ‘occupation’,
‘visible’       => 1,
‘required’      => 0, //mandatory? then 1
‘user_defined’ => 1,
));

$setup->addAttribute(‘customer’, ‘logincount’, array(
‘input’         => ‘text’, //or select or whatever you like
‘type’          => ‘int’, //or varchar or anything you want it
‘label’         => ‘logincount’,
‘visible’       => 1,
‘required’      => 0, //mandatory? then 1
‘user_defined’ => 1,
));

$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
‘occupation’,
‘100’
);

$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
‘logincount’,
‘100’
);

$oAttribute = Mage::getSingleton(‘eav/config’)->getAttribute(‘customer’, ‘occupation’);
$oAttribute->setData(‘used_in_forms’, array(‘adminhtml_customer’));
$oAttribute->save();
$oAttribute = Mage::getSingleton(‘eav/config’)->getAttribute(‘customer’, ‘logincount’);
$oAttribute->setData(‘used_in_forms’, array(‘adminhtml_customer’));
$oAttribute->save();

$setup->endSetup();


observer.php


<?php
class Shailendra_Customfield_Model_Observer
{
public function export_new_order($observer)
{
Mage::log(“hello”);
$orderLimit = Mage::getSingleton(‘customer/session’)->getCustomer()->getOccupation();
$custId = Mage::getSingleton(‘customer/session’)->getCustomer()->getId();
$customername = Mage::getSingleton(‘customer/session’)->getCustomer()->getName();
if($orderLimit > 0)
{
$orderLimit = $orderLimit – 1;
$customer = Mage::getModel(‘customer/customer’)->load($custId);
$customer->setOccupation($orderLimit);
try
{
$customer->save();
}
catch (Exception $ex)
{
Mage::log($ex);
}
}
else
{
Mage::getSingleton(‘checkout/session’)->addError(‘reached to Orderlimit’);
}
}
public function CustomerLogin($observer)
{
$customer = $observer->getCustomer();
$logincount = $customer->getLogincount();

$logincount = $logincount + 1;
$custId = $customer->getId();
$customer1 = Mage::getModel(‘customer/customer’)->load($custId);
$customer1->setLogincount($logincount);
try
{
$customer1->save();
}
catch (Exception $ex)
{
Mage::log($ex);
}
}
}

restrict order for customer

config.xml


 

<?xml version=”1.0″?>
<config>
<modules>
<Shailendra_CustomField>
<version>0.1.0</version>
</Shailendra_CustomField>
</modules>
<frontend>
<routers>
<customfield>
<use>standard</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
<layout>
<updates>
<customfield>
<file>customfield.xml</file>
</customfield>
</updates>
</layout>
</frontend>
<admin>
<routers>
<customfield>
<use>admin</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
</admin>
<global>
<fieldsets>
<customer_account>
<occupation>
<to_quote>occupation</to_quote>
</occupation>
</customer_account>
</fieldsets>
</global>
<global>
<fieldsets>
<customer_account>
<occupation><create>1</create><update>1</update><name>1</name></occupation>
</customer_account>
</fieldsets>
</global>
<global>
<models>
<customfield>
<class>Shailendra_Customfield_Model</class>
</customfield>
</models>
<events>
<sales_quote_save_before>
<observers>
<customfield_sales_order_observer>
<type>singleton</type>
<class>Shailendra_Customfield_Model_Observer</class><!– I’ve also tried Feed_Sales_Model_Order_Observer here –>
<method>export_new_order</method>
</customfield_sales_order_observer>
</observers>
</sales_quote_save_before>
</events>
<resources>
<customfield_setup>
<setup>
<module>Shailendra_CustomField</module>
<class>Mage_Customer_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</customfield_setup>
<customfield_write>
<connection>
<use>core_write</use>
</connection>
</customfield_write>
<customfield_read>
<connection>
<use>core_read</use>
</connection>
</customfield_read>
</resources>
</global>
</config>

observer.php


<?php
class Shailendra_Customfield_Model_Observer
{
public function export_new_order($observer)
{
Mage::log(“hello”);
$orderLimit = Mage::getSingleton(‘customer/session’)->getCustomer()->getOccupation();
$custId = Mage::getSingleton(‘customer/session’)->getCustomer()->getId();
$customername = Mage::getSingleton(‘customer/session’)->getCustomer()->getName();
if($orderLimit > 0)
{
$orderLimit = $orderLimit – 1;
$customer = Mage::getModel(‘customer/customer’)->load($custId);
$customer->setOccupation($orderLimit);
try
{
$customer->save();
}
catch (Exception $ex)
{
Mage::log($ex);
}
}
else
{
Mage::getSingleton(‘checkout/session’)->addError(‘reached to Orderlimit’);
}
}
}

add customer attribute in backend

Shailendra_CustomField.xml at app/etc
<?xml version=”1.0″?>
<config>
<modules>
<Shailendra_CustomField>
<active>true</active>
<codePool>local</codePool>
</Shailendra_CustomField>
</modules>
</config>
===
etc => config.xml
<?xml version=”1.0″?>
<config>
<modules>
<Shailendra_CustomField>
<version>0.1.0</version>
</Shailendra_CustomField>
</modules>
<frontend>
<routers>
<customfield>
<use>standard</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
<layout>
<updates>
<customfield>
<file>customfield.xml</file>
</customfield>
</updates>
</layout>
</frontend>
<admin>
<routers>
<customfield>
<use>admin</use>
<args>
<module>Shailendra_CustomField</module>
<frontName>customfield</frontName>
</args>
</customfield>
</routers>
</admin>
<global>
<fieldsets>
<customer_account>
<occupation>
<to_quote>occupation</to_quote>
</occupation>
</customer_account>
</fieldsets>
</global>
<global>
<fieldsets>
<customer_account>
<occupation><create>1</create><update>1</update><name>1</name></occupation>
</customer_account>
</fieldsets>
</global>
<global>
<resources>
<customfield_setup>
<setup>
<module>Shailendra_CustomField</module>
<class>Mage_Customer_Model_Entity_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</customfield_setup>
<customfield_write>
<connection>
<use>core_write</use>
</connection>
</customfield_write>
<customfield_read>
<connection>
<use>core_read</use>
</connection>
</customfield_read>
</resources>
</global>
</config>
===
sql => customfield_setup => mysql4-install-0.1.0.php
<?php
$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup(‘core_setup’);

$entityTypeId     = $setup->getEntityTypeId(‘customer’);
$attributeSetId   = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);

$setup->addAttribute(‘customer’, ‘occupation’, array(
‘input’         => ‘text’, //or select or whatever you like
‘type’          => ‘int’, //or varchar or anything you want it
‘label’         => ‘occupation’,
‘visible’       => 1,
‘required’      => 0, //mandatory? then 1
‘user_defined’ => 1,
));

$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
‘occupation’,
‘100’
);

$oAttribute = Mage::getSingleton(‘eav/config’)->getAttribute(‘customer’, ‘occupation’);
$oAttribute->setData(‘used_in_forms’, array(‘adminhtml_customer’));
$oAttribute->save();

$setup->endSetup();

===

Call to a member function getBackend() on a non-object in app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php on line 514

ANSWER:

if($attributeInstance = $this->getAttribute($attributeItem)){

if ($attributeInstance->getBackend()->isStatic()) {
$attrField = ‘e.’ . $attributeItem;
} else {
$this->_addAttributeJoin($attributeItem, ‘left’);
$attrField = $this->_getAttributeFieldName($attributeItem);
}
}

http://codemagento.blogspot.in/2012/05/add-new-custom-field-to-customer.html

 

 

How to create Mouseover Shopping Cart Icon in right header?

Step1: Create local.xml at

app/design/frontend/yourpackage/yourTemplate/layout/

add this code at this file:

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="header">
            <block type="checkout/cart_sidebar" name="cart_sidebar_header" template="checkout/cart/sidebar.phtml" before="-">
                <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/sidebar/default.phtml</template></action>
                <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/sidebar/default.phtml</template></action>
                <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/sidebar/default.phtml</template></action>
                <block type="core/text_list" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="checkout">
                    <label>Shopping Cart Sidebar Extra Actions</label>
                </block>
            </block>
        </reference>
    </default>
</layout>

This code is call cart side bar to header section.

Step2: on header.phtml call this cart sidebar using below code :

<?php echo $this->getChildHtml('cart_sidebar_header');?>

then rest of you need to put your logic

[Update] I have update code for sidebar

<?php 
$count=0;
if (Mage::helper('core')->isModuleOutputEnabled('Mage_Checkout')) {
    $count = $this->helper('checkout/cart')->getSummaryCount();
    if ($count >= 1) { $text = $this->__('Cart (%s)', $count); } 
    elseif ($count > 0) {$text = $this->__('Cart (%s)', $count); }
    else { $text = $this->__('Cart (0)'); }

}?>

MY CART

 

function show_sidebar() { document.getElementById(‘headsidebar’).style.display=”block”; } function hide_sidebar() { document.getElementById(‘headsidebar’).style.display=”noone”; } <?php if ($this->getIsNeedToDisplaySideBar()):?>

    getSummaryCount() ?>

        __(‘My Cart’) ?>

 

    0): ?>

__(‘There is 1 item in your cart.’, $this->getUrl(‘checkout/cart’)) ?>

 

__(‘There are %s items in your cart.’, $this->getUrl(‘checkout/cart’), $_cartQty) ?>

 

                canApplyMsrp()): ?>                     __(‘ORDER TOTAL WILL BE DISPLAYED BEFORE YOU SUBMIT THE ORDER’); ?>                                     __(‘Cart Subtotal:’) ?> formatPrice($this->getSubtotal()) ?>                     getSubtotalInclTax()): ?>
(formatPrice($_subtotalInclTax) ?> getIncExcText(true) ?>)

 

<?php endif ?>     <?php if($_cartQty && $this->isPossibleOnepageCheckout()): ?>

        getChildHtml(‘extra_actions’) ?>         __(‘Checkout’) ?>” class=”button” onclick=”setLocation(‘getCheckoutUrl() ?>’)”>__(‘Checkout’) ?>

<?php endif ?>     <?php $_items = $this->getRecentItems() ?>     <?php if(count($_items)): ?>         <p class=”block-subtitle”><?php echo $this->__(‘Recently added item(s)’) ?></p>         <ol id=”cart-sidebar” class=”mini-products-list”>         <?php foreach($_items as $_item): ?>             <?php echo $this->getItemHtml($_item) ?>         <?php endforeach; ?>         </ol>         decorateList(‘cart-sidebar’, ‘none-recursive’)     <?php else: ?>         <p class=”empty”><?php echo $this->__(‘You have no items in your shopping cart.’) ?></p>     <?php endif ?>     </div> </div> <?php endif;?>

file upload and attache in email with simple php captcha

<?php
session_start();
$_SESSION = array();
include(“simple-php-captcha.php”);
$_SESSION[‘captcha’] = simple_php_captcha();

echo ‘<img src=”‘ . $_SESSION[‘captcha’][‘image_src’] . ‘” alt=”CAPTCHA code”>’;
?>
<button name=”submit” type=’submit’ onclick=”return ValidCaptcha(‘<?php echo $_SESSION[‘captcha’][‘code’] ?>’)” class=’buttonA red small noborder hoverblue’ >Submit</button>

function ValidCaptcha(captchaval)
{
//alert(captchaval);
//alert(document.getElementById(‘captcha-750’).value);
if(document.getElementById(‘captcha-750’).value != “”)
{
if(captchaval != document.getElementById(‘captcha-750’).value)
{
document.getElementById(“captcha_msg”).innerHTML = “Please enter correct captcha value(case-sensitive)”;
return false;
}
else
{
document.getElementById(“captcha_msg”).innerHTML = “”;
return true;
}
}
}

$uploaddir = ‘upload/’;
$uploadfile = $uploaddir . basename($_FILES[‘photo’][‘name’]);
$filename = basename($_FILES[‘photo’][‘name’]);

echo ‘<pre>’;
if (move_uploaded_file($_FILES[‘photo’][‘tmp_name’], $uploadfile)) {
echo “File is valid, and was successfully uploaded.\n”;
}
else
{
echo “Possible file upload attack!\n”;
}

$htmlbody = ” Your Mail Contant Here…. You can use html tags here…”;
//$to = “vikenshah01@gmail.com”; //Recipient Email Address
$to = “miteshprajapati@gmail.com”; //Recipient Email Address

$subject = “Test email with attachment”; //Email Subject
$headers = “From: info@example.com\r\nReply-To: info@example.com”;
$random_hash = md5(date(‘r’, time()));
$headers .= “\r\nContent-Type: multipart/mixed;
boundary=\”PHP-mixed-“.$random_hash.”\””;
// Set your file path here
$attachment = chunk_split(base64_encode(file_get_contents($uploadfile)));

//define the body of the message.
$message = “–PHP-mixed-$random_hash\r\n”.”Content-Type: multipart/alternative;
boundary=\”PHP-alt-$random_hash\”\r\n\r\n”;
$message .= “–PHP-alt-$random_hash\r\n”.”Content-Type: text/plain;
charset=\”iso-8859-1\”\r\n”.”Content-Transfer-Encoding: 7bit\r\n\r\n”;

//Insert the html message.html_entity_decode.htmlentities
$message .= $mailmessage;
$message .=”\r\n\r\n–PHP-alt-$random_hash–\r\n\r\n”;

//include attachment
//$message .= “–PHP-mixed-$random_hash\r\n”.”Content-Type: application/zip;
//name=\”logo.png\”\r\n”.”Content-Transfer-Encoding:
//base64\r\n”.”Content-Disposition: attachment\r\n\r\n”;

$message .= “–PHP-mixed-$random_hash\r\n Content-Type: application/zip;
name=\””.$filename.”\r\n”.”Content-Transfer-Encoding:
base64\r\n”.”Content-Disposition: attachment\r\n\r\n”;

$message .= $attachment;
$message .= “/r/n–PHP-mixed-$random_hash–“;

//send the email
$mail = mail( $to, $subject , $message, $headers );

echo $mail ? “Mail sent” : “Mail failed”;

how to show category with subcategory in search sidebar

step1: go to /web/app/code/core/Mage/Catalog/Model/category.php
copy into local folder
step2: protected function _getItemsData()
{
$key = $this->getLayer()->getStateKey().’_SUBCATEGORIES’;
$data = $this->getLayer()->getAggregator()->getCacheData($key);

if ($data === null) {
$categoty   = $this->getCategory();
//print_r($categoty->getName());
//echo “<br>”;
//echo $this->getLayer()->getStateKey();

$categories = $categoty->getChildrenCategories();
/*foreach ($categories1 as $category1)
{
echo $category->getName();
echo “<br>”;
}
exit;*/

$this->getLayer()->getProductCollection()
->addCountToCategories($categories);

$data = array();
foreach ($categories as $category)
{
if ($category->getIsActive() && $category->getProductCount())
{
$data[] = array(
‘label’ => Mage::helper(‘core’)->htmlEscape($category->getName()),
‘value’ => $category->getId(),
‘count’ => $category->getProductCount(),
‘subcat’=>count($categoty->getChildrenCategories())
);
}
if($categoty->getName() == ‘Default Category’)
{
if($category->hasChildren())
{
$categoryCollection = $category->getChildrenCategories();
$this->getLayer()->getProductCollection()->addCountToCategories($categoryCollection);

foreach ($categoryCollection as $cat)
{
if ($cat->getIsActive() && $cat->getProductCount())
{
$data[] = array(
‘label’ => Mage::helper(‘core’)->htmlEscape($cat->getName()),
‘value’ => $cat->getId(),
‘count’ => $cat->getProductCount(),
);
}
}
}
}
}
$tags = $this->getLayer()->getStateTags();
$this->getLayer()->getAggregator()->saveCacheData($data, $key, $tags);
}
return $data;
}
step3: add code to $data[] for subcategory as defined in step-2 & also as below, as search
criteria would be only for ‘default category’.
if($categoty->getName() == ‘Default Category’)
{
if($category->hasChildren())
{
$categoryCollection = $category->getChildrenCategories();
$this->getLayer()->getProductCollection()->addCountToCategories($categoryCollection);

foreach ($categoryCollection as $cat)
{
if ($cat->getIsActive() && $cat->getProductCount())
{
$data[] = array(
‘label’ => Mage::helper(‘core’)->htmlEscape($cat->getName()),
‘value’ => $cat->getId(),
‘count’ => $cat->getProductCount(),
);
}
}
}
}
step4 : that’s it.

what are parameters to show related products

1)Go to System -> Index Management
Select All checkboxes
Select ‘Reindex Data’ from Actions selection list.

2)Check related product status is enabled.
Check visibility status set “Catalog” or “Catalog Search”
If everything is fine, check the inventory of related products.Stock should be greater than 0.
Last thing, related products must be include a category. Click “categories” link to check and see if the product added in a category.

3) If any of this are not working, go to catalog.xml and find this:

1
2
3
<reference name="right">
          <block type="catalog/product_list_related" name="catalog.product.related"  template="catalog/product/list/related.phtml"/>
</reference>

if is commented, uncomment it. If you want to display the related products in the product view page you have to change the reference name=”right” with reference name=”content”, becouse the related products are showed by default in right column layout and you have to move it to content.

If your layout is changed to 2 columns left the related products will not be visible.

4) If nothing worked by now you have tot do it by your self using this code as sample:

1
2
3
4
5
6
$related_prods = $_product->getRelatedProductIds();
foreach($related_prods as $related)
{
    $_rel = Mage::getModel('catalog/product')->load($related);
    echo $_rel->getName() . " " . $_rel->getSku();
}

Insert the code above in app/design/frontend/default/your_theme/template/catalog/product/view.phtml

Let us know what step helped you.

Magento – Show Quantity Box in Products List

Find the following line on list.phtml file

<?php if($_product->isSaleable()): ?>
<button onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?<')">>span>
<?php echo $this->__('Add to Cart') ?></span></button>

Replace with:

<form action="
<?php echo $this->getAddToCartUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId(); ?>">
<input name="qty" type="text" id="qty" maxlength="12" value="
<?php echo $this->getMinimalQty($_product) ?>" />
<button" onclick="productAddToCartForm_
<?php echo $_product->getId(); ?>.submit()"><span>
<?php echo $this->__('Add to Cart') ?></span></button>
</form>
<script type="text/javascript">
var productAddToCartForm_
<?php echo $_product->getId(); ?> = new VarienForm('product_addtocart_form_
<?php echo $_product->getId(); ?>');
productAddToCartForm_
<?php echo $_product->getId(); ?>.submit = function(){
if (this.validator.validate()) {
this.form.submit();
}
}.bind(productAddToCartForm_<?php echo $_product->getId(); ?>);
</script>