How to extend a model class and overrides its functions in Magento

The below example demonstrates how to extend the model class User, and overrides its function authenticate. The end result of this example will allow you to login to Magento admin panel with any existing Magento admin accounts without knowing the password. This is for demonstrating how to extend a model class and overrides its functions only,it might be helpful during development when testing with differnt amdin panel accounts, but NEVER ERVER put the below code in a production site.
1. Create the xml file app/etc/MyExtensions_Admin.xml

<?xml version="1.0"?>
<config>
    <modules>
        <MyExtensions_Admin>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Admin/>
            </depends>
        </MyExtensions_Admin>
    </modules>
</config>

2. Create the xml file app/code/local/MyExtensions/Admin/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
         <MyExtensions_Admin>
            <version>0.0.1</version>
        </MyExtensions_Admin>
    </modules>
    <global>
        <models>
            <admin>
                <rewrite>
                    <user>MyExtensions_Admin_Model_User</user>
                </rewrite>
            </admin>
        </models>
   </global>
</config>

3. Create the user class app/code/local/MyExtensions/Admin/Model/User.php

<?php

class MyExtensions_Admin_Model_User extends Mage_Admin_Model_User
{
     /**
     * Authenticate user name and password and save loaded record
     *
     * @param string $username
     * @param string $password
     * @return boolean
     * @throws Mage_Core_Exception
     */
    public function authenticate($username, $password)
    {
        $config = Mage::getStoreConfigFlag('admin/security/use_case_sensitive_login');
        $result = false;

        try {
            Mage::dispatchEvent('admin_user_authenticate_before', array(
                'username' => $username,
                'user'     => $this
            ));
            $this->loadByUsername($username);
            $sensitive = ($config) ? $username == $this->getUsername() : true;

            if ($sensitive && $this->getId() || Mage::helper('core')->validateHash($password, $this->getPassword())) {
                if ($this->getIsActive() != '1') {
                    Mage::throwException(Mage::helper('adminhtml')->__('This account is inactive.'));
                }
                if (!$this->hasAssigned2Role($this->getId())) {
                    Mage::throwException(Mage::helper('adminhtml')->__('Access denied.'));
                }
                $result = true;
            }

            Mage::dispatchEvent('admin_user_authenticate_after', array(
                'username' => $username,
                'password' => $password,
                'user'     => $this,
                'result'   => $result,
            ));
        }
        catch (Mage_Core_Exception $e) {
            $this->unsetData();
            throw $e;
        }

        if (!$result) {
            $this->unsetData();
        }
        return $result;
    }
}

Clear the cache and try to login to the admin panel. You now should be able to login to Magento admin panel with any existing admin panel account without knowing the password.

Once again, the above code modification is for convenience during development. Any of the above code modification should NEVER EVER show up in the production environment.




Here is another example which extends the Mage_SalesRule_Model_Rule_Condition_Address class.
It will add a Grandtotal condition in the shopping cart price rule.

1. Create the xml file app/etc/MyExtensions_SalesRule.xml

<?xml version="1.0"?>
<config>
    <modules>
        <MyExtensions_SalesRule>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_SalesRule/>
            </depends>
        </MyExtensions_SalesRule>
    </modules>
</config>

2. Create the xml file app/code/local/MyExtensions/SalesRule/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
         <MyExtensions_SalesRule>
            <version>0.0.1</version>
        </MyExtensions_SalesRule>
    </modules>
    <global>
        <models>
            <salesrule>
                <rewrite>
                    <rule_condition_address>MyExtensions_SalesRule_Model_Rule_Condition_Address</rule_condition_address>
                </rewrite>
            </salesrule>
        </models>
   </global>
</config>

3. Create the Address class app/code/local/MyExtensions/SalesRule/Model/Rule/Condition/Address.php

<?php
class MyExtensions_SalesRule_Model_Rule_Condition_Address extends Mage_SalesRule_Model_Rule_Condition_Address
{
    public function loadAttributeOptions()
    {
		//added the base_grandtotal
        $attributes = array(
            'base_subtotal' => Mage::helper('salesrule')->__('Subtotal'),
			'base_grandtotal' => Mage::helper('salesrule')->__('Grandtotal'),
            'total_qty' => Mage::helper('salesrule')->__('Total Items Quantity'),
            'weight' => Mage::helper('salesrule')->__('Total Weight'),
            'payment_method' => Mage::helper('salesrule')->__('Payment Method'),
            'shipping_method' => Mage::helper('salesrule')->__('Shipping Method'),
            'postcode' => Mage::helper('salesrule')->__('Shipping Postcode'),
            'region' => Mage::helper('salesrule')->__('Shipping Region'),
            'region_id' => Mage::helper('salesrule')->__('Shipping State/Province'),
            'country_id' => Mage::helper('salesrule')->__('Shipping Country'),
        );

        $this->setAttributeOption($attributes);

        return $this;
    }


	//added base_grantotal
    public function getInputType()
    {
        switch ($this->getAttribute()) {
            case 'base_subtotal': case 'base_grandtotal': case 'weight': case 'total_qty':
                return 'numeric';

            case 'shipping_method': case 'payment_method': case 'country_id': case 'region_id':
                return 'select';
        }
        return 'string';
    }

    /**
     * Validate Address Rule Condition
     *
     * @param Varien_Object $object
     * @return bool
     */
    public function validate(Varien_Object $object)
    {
        $address = $object;
        if (!$address instanceof Mage_Sales_Model_Quote_Address) {
            if ($object->getQuote()->isVirtual()) {
                $address = $object->getQuote()->getBillingAddress();
            }
            else {
                $address = $object->getQuote()->getShippingAddress();
            }
        }

        if ('payment_method' == $this->getAttribute() && ! $address->hasPaymentMethod()) {
            $address->setPaymentMethod($object->getQuote()->getPayment()->getMethod());
        }
		
		//The below is added for caculating the grandtotal
		$quote = Mage::getModel('checkout/session')->getQuote();
		$quoteData= $quote->getData();
		$basegrandTotal=$quoteData['base_grand_total'];
		if ('base_grandtotal' == $this->getAttribute() && ! $address->hasBaseGrandtotal()) {
                $address->setBaseGrandtotal($basegrandTotal);
        }
		
        return parent::validate($address);
    }
}

Now clear the cache and login to the admin panel. And then
Promotions->Shopping Cart Price Rules-> Add New Rule -> Conditions -> Click the plus button->Click the dropdown menu->The Grandtotal should be right after the Subtotal

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>