Playing with Magento’s Entity Backend Model

piaoling  2011-08-05 14:15:44

Here I come to know about an awesome feature of Magento. When we add any eav attribute to an entity we can give a backend model name. Whenever Entity will be loaded magento initiates Mage_Eav_Model_Entity_Attribute model for each attribut. If it finds any backend model name for a eav attribut, it loads the corresponding model and based on what it is doing it will call different method from that model.

Here I am giving a complete example how you can use this feature. We will add an attribue to address model as “address_verified” , use a backend model to set this value whenever the any address will be save.

Step 1.Create a custom model “Mymodule”

Step 2.Write an sql setup for this module. It will add an “address_verified” attribute to address entity

01 <?php $installer = $this; $installer->startSetup();
02  
03 $installer->run("
04 INSERT INTO {$this->getTable('eav_attribute')}  (
05 `entity_type_id` ,
06 `attribute_code` ,
07 `attribute_model` ,
08 `backend_model` ,
09 `backend_type` ,
10 `backend_table` ,
11 `frontend_model` ,
12 `frontend_input` ,
13 `frontend_input_renderer` ,
14 `frontend_label` ,
15 `frontend_class` ,
16 `source_model` ,
17 `is_global` ,
18 `is_visible` ,
19 `is_required` ,
20 `is_user_defined` ,
21 `default_value` ,
22 `is_searchable` ,
23 `is_filterable` ,
24 `is_comparable` ,
25 `is_visible_on_front` ,
26 `is_html_allowed_on_front` ,
27 `is_unique` ,
28 `is_used_for_price_rules` ,
29 `is_filterable_in_search` ,
30 `used_in_product_listing` ,
31 `used_for_sort_by` ,
32 `is_configurable` ,
33 `apply_to` ,
34 `position` ,
35 `note` ,
36 `is_visible_in_advanced_search`
37 )
38 VALUES (
39 '2', 'is_validated', NULL , 'customer_entity/address_attribute_backend_validate', 'int', NULL , NULL , 'text', NULL , NULL , NULL , NULL , '1', '1', '0', '0', NULL , '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '', '', '', '0'
40 );
41  
42 ");
43  
44 $installer->endSetup();

Step3.Write the back end model in your local code pool

01 <?php
02  
03 class Mypackage_Customer_Model_Entity_Address_Attribute_Backend_Validate
04     extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
05 {
06     public function beforeSave($object)
07     {
08         //Write your code to validate address
09         $object->setIsValidated($satoriStatus);
10         return $this;
11     }
12 }

Step 4. Override the backend model so that it runs from your local pool

1 </config>
2  <models>
3  <customer_entity>
4  <rewrite>
5  <address_attribute_backend_satori>Mypackage_Customer_Model_Entity_Address_Attribute_Backend_Satori</address_attribute_backend_satori>
6  </rewrite>
7  </customer_entity>
8  </models>
9 <config>

 

类别 :  magento(258)  |  浏览(3622)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: