Magento Forum

   
Custom load by funtion in Custom module in Magento
 
pradeep_kumar67
Sr. Member
 
Avatar
Total Posts:  160
Joined:  2010-06-24
Bangalore
 

Hi,

if you need to load a object other then id in custom module that is if you need to load a custom model object from there field in magneto

we have to follow the steps

1st Create a Abstract class Abstract.php in side Model Folder (check attachment) and paste below code

<?php

abstract class MyCompany_MyModule_Model_Abstract extends Mage_Core_Model_Abstract
{
    

    
public function loadByAttribute($attribute$value$additionalAttributes='*')
    
{
        $collection 
$this->getResourceCollection()
            ->
addFieldToSelect($additionalAttributes)
            ->
addFieldToFilter($attribute$value);

        foreach (
$collection as $object{
            
return $object;
        
}
        
return false;
    
}

    

}

extend this abstract class to you module that is crate MyModule.php inside Model folder (check attachment)

I extend this class from Abstarct class which created 1st

<?php

class MyCompany_MyModule_Model_MyModule extends MyCompany_MyModule_Model_Abstract
{
    
protected function _construct(){

       $this
->_init("mymodule/mymodule");

    
}
    
    
public function loadByEmail($email)
    
{
        $data
$this->_getResource()->loadByEmail($email);
        
$this->setData($data);
         return 
$this;
    
}

}

and also in side Mysql4 folder create MyModule.php (check attachment)

<?php
    
class MyCompany_MyModule_Model_Mysql4_MyModule extends Mage_Core_Model_Mysql4_Abstract
    {
        
protected function _construct()
        
{
            $this
->_init("mymodule/mymodule""MyModule_id");
        
}
    
    
        
public function loadByEmail($email)
        
{
            $adapter 
$this->_getReadAdapter();

            
$select $adapter->select()
                ->
from('YOUTABLE''*')
                ->
where('email = :email');

            
$bind = array(':email' => (string)$email);

            return 
$adapter->fetchRow($select$bind);
        
}
    }

you can load a model like this

$email='pradeep.kumarrcs67@gmail.com';
$loadFromAnyField=Mage::getModel('mymodule/mymodule')->loadByAttribute('email',$email);
$loadByEmail=Mage::getModel('mymodule/mymodule')->loadByEmail($email);

print_r($loadFromAnyField->getId());
print_r($loadByEmail->getId());

File Attachments
Model.zip  (File Size: 2KB - Downloads: 48)
 
Magento Community Magento Community
Magento Community
Magento Community
 
pradeep_kumar67
Sr. Member
 
Avatar
Total Posts:  160
Joined:  2010-06-24
Bangalore
 

I used hear 2 types

1. Load by specific field (email)
2. Load By any value (you can load from any fields in table of custom module)

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
    Back to top