<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Subesh Pokhrel&#039;s Blog - Magento Development Tips,PHP,Google Maps</title>
	<atom:link href="http://subesh.com.np/feed/" rel="self" type="application/rss+xml" />
	<link>http://subesh.com.np</link>
	<description>PHP &#38; Magento Tips &#38; Tutorials</description>
	<lastBuildDate>Thu, 12 Aug 2010 12:22:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Working with Ajax and JSON Objects in Magento [Case: Ajax Powered Login Functionality]</title>
		<link>http://subesh.com.np/2010/08/working-ajax-json-objects-magento-case-ajax-powered-login-functionality/</link>
		<comments>http://subesh.com.np/2010/08/working-ajax-json-objects-magento-case-ajax-powered-login-functionality/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 12:22:48 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Block]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=264</guid>
		<description><![CDATA[Previously I have written about Working With Ajax in Magento. And after a huge response I received from that post I was compelled to write more on implementing Ajax in Magento. And this time I want to say additionally about handling JSON (JavaScript Object Notation) along with Ajax, within the Magento enviornment. JSON Objects and [...]]]></description>
			<content:encoded><![CDATA[<p>Previously I have written about <a href="http://subesh.com.np/2009/11/working-with-ajax-in-magento/">Working With Ajax in Magento</a>. And after a huge response I received from that post I was compelled to write more on implementing Ajax in Magento. And this time I want to say additionally about handling JSON (<strong>JavaScript Object Notation</strong>) along with Ajax, within the Magento enviornment. JSON Objects and Ajax can be very helpful technique to get the work done. You can learn about JSON from <a href="http://www.json.org/">Here</a>.</p>
<p><span id="more-264"></span></p>
<p>I will try to describe this issue by taking a case of changing the Magento&#8217;s login functionality to a Ajax powered login functionality. So after this you will be able to implement a login function in a pop-up div in any page, unlike the default Magento&#8217;s seperate login page. I will leave the pop-up div part to you and get started with the real business (AJAX and JSON).</p>
<p>Presuming that you will use <strong>Mini-Login</strong> form. Here is how you proceed.</p>
<ol>
<li>Change Submit type button to Button type button.</li>
<li>Register OnClick Javascript event of that button and its Handler</li>
<li>In the Handler function call Ajax Request for login</li>
<li>Show Error Message or redirect to customer Dashboard</li>
</ol>
<p>Your mini.login.phtml should be like this</p>
<pre class="brush: xml;">
&lt;form action=&quot;&lt;?php //echo $this-&gt;getPostActionUrl() ?&gt;&quot; id=&quot;mini-login-form&quot; method=&quot;post&quot;&gt;
    &lt;fieldset&gt;
        &lt;p&gt;&lt;label&gt;&lt;?php echo $this-&gt;__('Email') ?&gt;:&lt;/label&gt; &lt;input name=&quot;login[username]&quot; class=&quot;input-text&quot; /&gt;&lt;/p&gt;
        &lt;p&gt;&lt;label&gt;&lt;?php echo $this-&gt;__('Password') ?&gt;:&lt;/label&gt; &lt;input name=&quot;login[password]&quot; class=&quot;input-text&quot; /&gt;&lt;/p&gt;
        &lt;p&gt;&lt;input type=&quot;button&quot; onClick=&quot;handlerFunction()&quot; value=&quot;&lt;?php echo $this-&gt;__('Login') ?&gt;&quot; /&gt;&lt;/p&gt;
    &lt;/fieldset&gt;
&lt;/form&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
&lt;!--
function handlerFunction(){

// Write These codes only after form Validation

// Making Ajax Request
		var request = new Ajax.Request(
			//Defining Ajax Request URL, We are calling custom Controller Ns_Mylogin_AccountController Class (Defined Below)
        	'&lt;?php echo $this-&gt;getUrl(&quot;mylogin/account/loginPost&quot;) ?&gt;',
           	{
            	method: 'post',
                onComplete: function(transport){ // Defining Complete Callback Function

                	// Getting Ajax Response Text Which is JSON Object
                	var jsonResponse=transport.responseText;
                	//Checking JSON Objects property and performing related action
                	// You will understand the response Text format after going through the controller description (Below)
                	if(jsonResponse.error){
                		alert(&quot;Error Occured&quot;);
						return false;
                	}
                	else{
                		window.location.href=jsonResponse.url;
                	}
                },
                parameters: Form.serialize($(&quot;mini-login-form&quot;))	// Seriallizing the form input values
        	}
        );
}
//--&gt;
&lt;/script&gt;
</pre>
<p>Please see inline comments for better understanding. Now our next set should be setting up our custom controller. I&#8217;ll not get into details of setting up modules and all but directly to our controller class <strong>Ns_Mylogin_AccountController</strong>. What I&#8217;ve done is just taken the core&#8217;s  <strong>loginPostAction </strong>function of <strong>Mage_Customer_AccountController</strong> and added some codes there. Please see there is a comment on each line added apart from the default Magento&#8217;s core code. </p>
<pre class="brush: php;">
&lt;?php
require_once(&quot;Mage/Customer/controllers/AccountController.php&quot;);
class Ns_Mylogin_AccountController extends Mage_Customer_AccountController{
	/**
	 * Login post action
	 * @return JSON Object
	 */
	public function loginPostAction()
	{
		// Added Line #1
		$result[&quot;error&quot;]=0;

		$session = $this-&gt;_getSession();

		if ($this-&gt;getRequest()-&gt;isPost()) {
			$login = $this-&gt;getRequest()-&gt;getPost('login');
			if (!empty($login['username']) &amp;&amp; !empty($login['password'])) {
				try {
					$session-&gt;login($login['username'], $login['password']);
					if ($session-&gt;getCustomer()-&gt;getIsJustConfirmed()) {
						$this-&gt;_welcomeCustomer($session-&gt;getCustomer(), true);
					}
				} catch (Mage_Core_Exception $e) {
					switch ($e-&gt;getCode()) {
						case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
							//Added Line #2
							$result[&quot;error&quot;]=1;
							$message = Mage::helper('customer')-&gt;__('This account is not confirmed. &lt;a href=&quot;%s&quot;&gt;Click here&lt;/a&gt; to resend confirmation email.', 						Mage::helper('customer')-&gt;getEmailConfirmationUrl($login['username']));
							break;
						case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
							//Added Line #3
							$result[&quot;error&quot;]=1;
							$message = $e-&gt;getMessage();
							break;
						default:
							//Added Line #4
							$result[&quot;error&quot;]=1;
							$message = $e-&gt;getMessage();
					}
					$session-&gt;addError($message);
					$session-&gt;setUsername($login['username']);
				} catch (Exception $e) {
					// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
				}
			} else {
				//Added Line #5
				$result[&quot;error&quot;]=1;
				$session-&gt;addError($this-&gt;__('Login and password are required'));
				//Added Line #6
				$this-&gt;getResponse()-&gt;setBody(Mage::helper('core')-&gt;jsonEncode($result));
			}
		}
		//Added Line #7
		$result[&quot;url&quot;]=$this-&gt;_loginPostRedirect();
		//Added Line #8
		$this-&gt;getResponse()-&gt;setBody(Mage::helper('core')-&gt;jsonEncode($result));
	}
</pre>
<p>What I&#8217;ve done is added an array <strong>$result</strong> that will hold value if there is error or not while processing the user&#8217;s request. If there is error that array will hold $result['error']=1 else it will be as initiallized in <em>Added Line #1</em>. From <em>Added Line #2</em> through <em>Added Line #5</em>, we have various condition to check for error and set our <strong>$result</strong> variable.</p>
<p>On <em>Added Line #7</em> we have called another function (which we we rewrite as well) that will give us the url location identifying which location should be redirect after successful login. The implementation of function is given below. Finally in <em>Added Line #8</em> and <em>Line #6</em> we have encoded our $result array into <strong>JSON</strong> format and send as the response.</p>
<p>For visuallization our $result array will be one of the following.</p>
<ol>
<li> Case (No Error) : $result["error"]=0; $result["url"]=&#8221;SOME Redirect URL&#8221; </li>
<li> Case (Error) 	 :	$result["error"]=1; </li>
</ol>
<p>This JSON encoded response will be then used by the ajax call back function defined and perform related action.</p>
<p>Here&#8217;s the <strong>_loginPostRedirect()</strong> function which I mentioned (Added Line #7).</p>
<pre class="brush: php;">
/**
	 * Define target URL and redirect customer after logging in
	 */
	protected function _loginPostRedirect()
	{
		$session = $this-&gt;_getSession();

		if (!$session-&gt;getBeforeAuthUrl() || $session-&gt;getBeforeAuthUrl() == Mage::getBaseUrl() ) {

			// Set default URL to redirect customer to
			$session-&gt;setBeforeAuthUrl(Mage::helper('customer')-&gt;getAccountUrl());

			// Redirect customer to the last page visited after logging in
			if ($session-&gt;isLoggedIn())
			{
				if (!Mage::getStoreConfigFlag('customer/startup/redirect_dashboard')) {
					if ($referer = $this-&gt;getRequest()-&gt;getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME)) {
						$referer = Mage::helper('core')-&gt;urlDecode($referer);
						if ($this-&gt;_isUrlInternal($referer)) {
							$session-&gt;setBeforeAuthUrl($referer);
						}
					}
				}
				else if ($session-&gt;getAfterAuthUrl()) {
					$session-&gt;setBeforeAuthUrl($session-&gt;getAfterAuthUrl(true));
				}
			} else {
				$session-&gt;setBeforeAuthUrl(Mage::helper('customer')-&gt;getLoginUrl());
			}
		} else if ($session-&gt;getBeforeAuthUrl() == Mage::helper('customer')-&gt;getLogoutUrl()) {
			$session-&gt;setBeforeAuthUrl(Mage::helper('customer')-&gt;getDashboardUrl());
		}
		else {
			if (!$session-&gt;getAfterAuthUrl()) {
				$session-&gt;setAfterAuthUrl($session-&gt;getBeforeAuthUrl());
			}
			if ($session-&gt;isLoggedIn()) {
				$session-&gt;setBeforeAuthUrl($session-&gt;getAfterAuthUrl(true));
			}
		}
		// Changed Here
		return $session-&gt;getBeforeAuthUrl(true);
	}
</pre>
<p>You can download the code From <a href="http://code.google.com/p/subeshexamples/downloads/detail?name=Ajax_Json_Magento_subesh.com.np.zip#makechanges">Here</a>.</p>
<p>Hope it helps! Happy Coding.	</p>
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/08/working-ajax-json-objects-magento-case-ajax-powered-login-functionality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Displaying Currency code after the price value in Magento</title>
		<link>http://subesh.com.np/2010/08/displaying-currency-code-price-magento/</link>
		<comments>http://subesh.com.np/2010/08/displaying-currency-code-price-magento/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 11:33:38 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=261</guid>
		<description><![CDATA[I had a time to research on Magento&#8217;s currency format and its display on Magento webshop. I then came across a block where I could change the format of currency display, in this case I am talking about moving the currency symbol to the right of the price value. In other words I found a [...]]]></description>
			<content:encoded><![CDATA[<p>I had a time to research on Magento&#8217;s currency format and its display on Magento webshop. I then came across a block where I could change the format of currency display, in this case I am talking about moving the currency symbol to the right of the price value. In other words I found a way to show $10.00 as 10.00$. Notice the <strong>$</strong> (Dollar) sign moving at the right of the price value.<br />
Here&#8217;s a description of how this can be achievable. The basic idea is to rewrite <strong>Mage_Core_Model_Locale</strong> class&#8217;s currency function and add additional code. First you must write a rewrite code in your module&#8217;s<strong> config.xml</strong>.</p>
<p><span id="more-261"></span></p>
<pre class="brush: xml;">
&lt;core&gt;
	&lt;rewrite&gt;
		&lt;locale&gt;Namespace_Module_Model_Locale&lt;/locale&gt;
	&lt;/rewrite&gt;
&lt;/core&gt;
</pre>
<p>Then in <strong>Namespace_Module_Model_Locale</strong> class you can add the following code.</p>
<pre class="brush: php;">
class Namespace_Module_Model_Locale extends Mage_Core_Model_Locale{
	/*
	* Code: subesh.com.np
	*/

    public function currency($currency)
    {
    	Varien_Profiler::start('locale/currency');
        if (!isset(self::$_currencyCache[$this-&gt;getLocaleCode()][$currency])) {
            try {
                $currencyObject = new Zend_Currency($currency, $this-&gt;getLocale());

				// Additionally Added Code
				// The options array's position key has other values as well.

				// 	Zend_Currency::STANDARD
				// 	Zend_Currency::RIGHT
				//	Zend_Currency::LEFT     

				$options = array(
                       'position'	=&gt; Zend_Currency::RIGHT
                );

				$currencyObject-&gt;setFormat($options);

				// END Additionally Added Code

            } catch (Exception $e) {
                $currencyObject = new Zend_Currency($this-&gt;getCurrency(), $this-&gt;getLocale());
                $options = array(
                        'name'      =&gt; $currency,
                        'currency'  =&gt; $currency,
                        'symbol'    =&gt; $currency
                );
                $currencyObject-&gt;setFormat($options);
            }

            self::$_currencyCache[$this-&gt;getLocaleCode()][$currency] = $currencyObject;
        }
        Varien_Profiler::stop('locale/currency');
        return self::$_currencyCache[$this-&gt;getLocaleCode()][$currency];
	}	

}
</pre>
<p>You can see the comment of the code above for more detail understanding.</p>
<p><strong><em>P.S: Be informed that you need to change the Class Name you are about to create on the basis of your Namespace and Module name.</em></strong>
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/08/displaying-currency-code-price-magento/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magento: Setting Up a Default Shipping Method on Cart Page</title>
		<link>http://subesh.com.np/2010/08/magento-setting-default-shipping-method-cart-page/</link>
		<comments>http://subesh.com.np/2010/08/magento-setting-default-shipping-method-cart-page/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 08:14:44 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=258</guid>
		<description><![CDATA[I recently came to a situation where I need to show a shipping price amount on cart before selecting the shipping address from the checkout page. Basically shipping price is shown after the user has added the shipping address and selected the shipping method. So to show shipping price on cart page load, I needed [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came to a situation where I need to show a shipping price amount on cart before selecting the shipping address from the checkout page. Basically shipping price is shown after the user has added the shipping address and selected the shipping method. So to show shipping price on cart page load, I needed to find out the following.</p>
<ol>
<li> Shipping Address (Actually only <b>country_id </b>will work)</li>
<li> Shipping Method (Set to Flatrate in the code below) </li>
</ol>
<p>So what I did was first check if the user has already specified the shipping address (<b>when user have added the shipping address in the checkout page and navigated back to cart page</b>). If the shipping address is not present then I checked if the user is logged in  and checked for default shipping address of the customer and used its country_id (<b>if present</b>), but if the user is not logged in or default shipping address is not present then I set the shipping address (<b>country_id</b>) to some country (<b>NL</b>).<br />
After setting the country I then set the shipping method and then saved the quote so that the prices are calculated.<br />
<span id="more-258"></span><br />
Here&#8217;s the snippet.</p>
<pre class="brush:php">/**
* Setting Default Shipping Method
* Checking If Quote Already Has Address Or Not
* - If Yes then leave as it is
* - Else check if Customer has default Shipping Address or Not
*  -- Yes then get Default Shipping Address and set Shipping Method
*  -- No Set Default Shipping address to NL
*/

if(!Mage::getSingleton('checkout/type_onepage')-&gt;getQuote()-&gt;getShippingAddress()-&gt;getCountryId()){
$customerSession=Mage::getSingleton("customer/session");
if($customerSession-&gt;isLoggedIn()){
$customerAddress=$customerSession-&gt;getCustomer()-&gt;getDefaultShippingAddress();
if($customerAddress-&gt;getId()){
$customerCountry=$customerAddress-&gt;getCountryId();
$shipping = Mage::getSingleton('checkout/type_onepage')-&gt;getQuote()-&gt;getShippingAddress()-&gt;setCountryId($customerCountry)-&gt;setShippingMethod('flatrate_flatrate')-&gt;save();
}
else{
$shipping = Mage::getSingleton('checkout/type_onepage')-&gt;getQuote()-&gt;getShippingAddress()-&gt;setCountryId('NL')-&gt;setShippingMethod('flatrate_flatrate')-&gt;save();
}
}
}
</pre>
<p>Cheers!
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/08/magento-setting-default-shipping-method-cart-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Worldcup: German Coach to file a case against Spanish in FIFA</title>
		<link>http://subesh.com.np/2010/07/worldcup-german-coach-to-file-a-case-against-spanish-in-fifa/</link>
		<comments>http://subesh.com.np/2010/07/worldcup-german-coach-to-file-a-case-against-spanish-in-fifa/#comments</comments>
		<pubDate>Fri, 09 Jul 2010 05:03:27 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Monologue]]></category>

		<guid isPermaLink="false">http://subesh.com.np/2010/07/worldcup-german-coach-to-file-a-case-against-spanish-in-fifa/</guid>
		<description><![CDATA[Normally, I post tech stuff in my blog, but can&#8217;t get away from football world cup fever. And my friend broke a news that German coach will file a case against Spanish, claiming that Germans should have also got the ball during the play at semis, because they were also playing the same game.

LOL!
Can&#8217;t wait [...]]]></description>
			<content:encoded><![CDATA[<p>Normally, I post tech stuff in my blog, but can&#8217;t get away from football world cup fever. And my friend broke a news that German coach will file a case against Spanish, claiming that Germans should have also got the ball during the play at semis, because they were also playing the same game.</p>
<p><span id="more-257"></span></p>
<p>LOL!</p>
<p>Can&#8217;t wait for the trial sessions.. HAHAHAHAHAHA</p>
<p>Go SPAIN!
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/07/worldcup-german-coach-to-file-a-case-against-spanish-in-fifa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magento: Creating Ajax Updated Tabs In Frontend, Like Product Management Tabs of Backend</title>
		<link>http://subesh.com.np/2010/06/magento-creating-ajax-updated-tabs-frontend-product-management-tabs-backend/</link>
		<comments>http://subesh.com.np/2010/06/magento-creating-ajax-updated-tabs-frontend-product-management-tabs-backend/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 13:00:42 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=254</guid>
		<description><![CDATA[Magento&#8217;s Product Management GUI in back-end has Tabbed Navigation. There are two types of Tabs implemented there. One type of Tab is normal tab, loading content on page load while other type of tab has its content loaded by &#8220;Ajax&#8221;. Another interesting thing to note is that once the Ajax loaded tab&#8217;s content is loaded [...]]]></description>
			<content:encoded><![CDATA[<p>Magento&#8217;s Product Management GUI in back-end has Tabbed Navigation. There are two types of Tabs implemented there. One type of Tab is normal tab, loading content on page load while other type of tab has its content loaded by &#8220;Ajax&#8221;. Another interesting thing to note is that once the Ajax loaded tab&#8217;s content is loaded it will not &#8220;recall&#8221; Ajax to load its content, rather earlier loaded tab content is show. If are &#8220;confused&#8221; then just see how the &#8220;Categories&#8221; tab of the Product Management works.</p>
<p><span id="more-254"></span></p>
<p>I successfully used the same &#8220;behavior&#8221; of tabbed navigation in &#8220;front-end&#8221;, was easy at the end (always with Magento, when you get it), but I was struggling at the start. So, like my other posts, to share here&#8217;s how I used the same type of tab in Magento&#8217;s Front-end.</p>
<p>First thing is add the Tab&#8217;s Java-script file. You can either include by layout or in PHTML file. If you want to do from layout then,</p>
<pre class="brush: xml;">
&lt;reference name=&quot;head&quot;&gt;
        	 &lt;action method=&quot;addJs&quot;&gt;&lt;script&gt;mage/adminhtml/tabs.js&lt;/script&gt;&lt;/action&gt;
&lt;/reference&gt;
</pre>
<p>Next thing is to create Tab&#8217;s Menu inside UL &#038; LI. Here&#8217;s the structure. (Self Explanatory)</p>
<pre class="brush: xml;">
&lt;!-- TAB MENU STRUCTURE --&gt;

&lt;ul id=&quot;page_tabs&quot;&gt;
	&lt;!-- NORMAL TAB --&gt;
	&lt;li&gt;
		&lt;a id=&quot;normaltab&quot; name=&quot;normaltab&quot; class=&quot;tab-item-link&quot; href=&quot;#&quot;&gt; NORMAL TAB &lt;/a&gt;
		&lt;!-- NOTE: class has to be tab-item-link--&gt;

		&lt;div id=&quot;normaltab_content&quot;&gt; Normal Tab HTML&lt;/div&gt;
		&lt;!-- NOTE: See the id of this div content it has id equal to its anchor's (&lt;a&gt;) id + Underscore + content --&gt;
	&lt;/li&gt;
	&lt;!-- NORMAL TAB END--&gt;

	&lt;!-- AJAX LOADED TAB --&gt;
	&lt;li&gt;
		&lt;a id=&quot;ajaxtab&quot; name=&quot;ajaxtab&quot; class=&quot;tab-item-link ajax notloaded&quot; href=&quot;http://example.com/magento/module/controller/action&quot;&gt; AJAX TAB &lt;/a&gt;
		&lt;!-- NOTE 1: class has to be tab-item-link ajax notloaded --&gt;
		&lt;!-- NOTE 2: Since this is Ajax Loaded Tab its Anchor should have href value = SOME URL --&gt;

		&lt;div id=&quot;ajaxtab_content&quot;&gt;&lt;/div&gt;
		&lt;!-- NOTE 1: See the id of this div content it has id equal to its anchor's (&lt;a&gt;) id + Underscore + content --&gt;
		&lt;!-- NOTE 2: Since its innerHTML will be loaded by by Ajax you can set its innerHTML &quot;blank&quot; --&gt;

	&lt;/li&gt;
	&lt;!-- AJAX LOADED TAB END --&gt;
&lt;/ul&gt;
&lt;!-- TAB MENU STRUCTURE END --&gt;

&lt;!-- TAB CONTENT CONTAINER DIV--&gt;
&lt;div id=&quot;tabcontainer&quot;&gt;&lt;/div&gt;
&lt;!-- TAB CONTENT CONTAINER DIV--&gt;
</pre>
<p>Now its the time to use the Tabs JS included, like below.</p>
<pre class="brush: jscript;">
&lt;script&gt;
	// Form Key Required for POST AJAX Method
	var FORM_KEY=&quot;&lt;?php echo Mage::getSingleton('core/session')-&gt;getFormKey() ?&gt;&quot;; 

	// Set this to false, Guess used for some other purpose in backend, not really required in frontend.
	var varienGlobalEvents=false;

	// Initiallizing Varien Tabs
	/**
	* @param 1 : UL Menu ID
	* @param 2 : Target Tab Content ID
	* @param 3 : Initially Loading Tab's Id
	* @param 4 : Don't know yet, just use as it is (LOL)
	*/

	frontend_tabsJsTabs = new varienTabs('page_tabs', 'tabcontainer', 'normaltab',[]);

&lt;/script&gt;
</pre>
<p>Done! You must now have a functioning Tab loading by Ajax and Normal, but yes tab would look good if you add CSS to your Tabs. <img src='http://subesh.com.np/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  Here is how it works.</p>
<ol>
<li>
On load it first copies the tab_content div inside the Target Tab Content ID div.
</li>
<li>
On tabbed menu clicked it checks its class name and if it class name does not have &#8220;ajax&#8221; it simply shows the its_content div.
</li>
<li>
If the menu clicked has &#8220;ajax&#8221; then it checks for another class name &#8220;notloaded&#8221;. So if its ajax and notloaded it then makes an Ajax request and updates the responseText to itsid_content div and then removes the &#8220;notloaded&#8221; class name for the menu. After that it then displays the itsid_content div, hiding previous ones.
</li>
<li>
If you re-click the &#8220;Ajax&#8221; typed menu, it will not find &#8220;notloaded&#8221; class in its menu, then it just shows its_content div.
</li>
</ol>
<p>A good trick, I thought while doing this, using class name to restrict the Ajax call.
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/06/magento-creating-ajax-updated-tabs-frontend-product-management-tabs-backend/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Analysis &amp; Usage of Collections in Magento</title>
		<link>http://subesh.com.np/2010/05/analysis-usage-collections-magento/</link>
		<comments>http://subesh.com.np/2010/05/analysis-usage-collections-magento/#comments</comments>
		<pubDate>Thu, 13 May 2010 12:20:25 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=246</guid>
		<description><![CDATA[As a Magento Programmer I am fascinated by the use &#38; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we [...]]]></description>
			<content:encoded><![CDATA[<p>As a Magento Programmer I am fascinated by the use &amp; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we are actually trying to get from database. Here is what I found drilling down into the Magento&#8217;s Core. I may be &#8220;not quite right&#8221; with the analysis, you can always comment.</p>
<p><span id="more-246"></span></p>
<p>Almost all the collections found inside  <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model/Collection.php</strong> are the child of parent Class <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong>. Primary thing done in the class constructor is initializing its resource and Model. If you look into one of the Collection class you can see in its constructor.</p>
<pre class="brush: php;">
/**
	 * @class Mage_Checkout_Model_Mysql4_Agreement_Collection
     * Initialize resource
     *
     */
    protected function _construct()
    {
        $this-&gt;_init('checkout/agreement');
    }
</pre>
<p>And this _init function has been implemented in its parent class as</p>
<pre class="brush: php;">
/**
     * Standard resource collection initalization
     *
     * @param string $model
     * @return Mage_Core_Model_Mysql4_Collection_Abstract
     */
    protected function _init($model, $resourceModel=null)
    {
        $this-&gt;setModel($model);
        if (is_null($resourceModel)) {
            $resourceModel = $model;
        }
        $this-&gt;setResourceModel($resourceModel);
        return $this;
    }
</pre>
<p>The resource class can be found in <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model.php</strong>. And this resource class in turn initializes the database table to be used in the Module along with the table&#8217;s primary key.</p>
<pre class="brush: php;">
class Mage_Checkout_Model_Mysql4_Agreement extends Mage_Core_Model_Mysql4_Abstract
	{

	protected function _construct()
    {
        $this-&gt;_init('checkout/agreement', 'agreement_id');
    }
	......
	}
</pre>
<p>It is this resource class that actually works out the database connections, read/write adapters and performs transactions. So this is the basic deduction about the link of collection with the database and its tables. But how are those collection formed still remains a mystery, not anymore! In this section of the post I will try to explain how are the collections really formed.</p>
<p>If I can, &#8220;<strong>collection</strong>&#8221; can be defined as collection or array of its resource. And in Magento case, most of the resources are database&#8217;s query results. Simply you can visualize &#8220;<strong>collection</strong>&#8221; to be array of your model&#8217;s resource. If a &#8220;<strong>query</strong>&#8221; in Magento returns a collection of all the products then it would mean that the very collection is an array of all the individual product&#8217;s object. But one question still remains how will the database query&#8217;s result transform into a Magento &#8220;<strong>collection</strong>&#8220;. To understand that we need to understand the collection class and its parents.</p>
<p>The class Structure for <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong> is like this.</p>
<p>Mage_Core_Model_Mysql4_Collection_Abstract</p>
<p style="padding-left: 30px;">|__ Varien_Data_Collection_Db (C)</p>
<p style="padding-left: 60px;">|__	Varien_Data_Collection (C)</p>
<p style="padding-left: 90px;">|__ IteratorAggregate (I)</p>
<p style="padding-left: 90px;">|__ Countable (I)</p>
<p>You can see that all collection implements two Interfaces <strong>IteratorAggregate </strong>&amp; <strong>Countable</strong>.</p>
<p><a href="http://goo.gl/MjAT" target="_blank">IteratorAggregate </a> is predefined in Standard PHP Library that extends Abstract Base Class <a href="http://goo.gl/rzXS" target="_blank">Traversable </a>. On using this Interface you can then <a href="http://goo.gl/hgtI" target="_blank">Iterate Through Object</a> using &#8220;<strong>foreach</strong>&#8221; construct. Countable returns the size of the Collection Object.</p>
<p>Among the two Interfaces, <strong>IteratorAggregate </strong>is particularly important. As you can see in Class Hierarchy both the interfaces are implemented by<strong> Varien_Data_Collection</strong> concrete class. <strong>IteratorAggregate</strong> has abstract public method <strong>getIterator()</strong> which returns the Iterator interface and the concrete Class has to implement the method on its own. It is this Iterator that provides the real iteration functionality. You can get a detailed description about Iterator <a href="http://goo.gl/C9Nx" target="_blank">Here</a>.</p>
<p>So if you look into the <strong>Varien_Data_Collection</strong> you will find the <strong>getIterator()</strong> implemented like this.</p>
<pre class="brush: php;">
/**
	 * @class Varien_Data_Collection
     * Implementation of IteratorAggregate::getIterator()
     */
    public function getIterator()
    {
        $this-&gt;load();
        return new ArrayIterator($this-&gt;_items);
    }
</pre>
<p>As you can see that it first loads the &#8220;<strong>items</strong>&#8221; (I will get back to this Items) and instanciates the value to an internal Class <a href="http://goo.gl/8LAi" target="_blank">ArrayIterator </a>. And the Iterator returned by this function can then be iterated using <strong>foreach </strong>construct.</p>
<p>Looks like it is going to be a looonnnnng post, let be summarize what I&#8217;ve tried to point out until now. I&#8217;ve tried to show the link between the collection class or rather object with the database table and explain the iteration behavior of the collection object. But one question still remains how will the database query&#8217;s result transform into a Magento&#8217;s &#8220;<strong>collection</strong>&#8220;. This is where the &#8220;<strong>items</strong>&#8221; explanation need to be done.</p>
<p>&#8220;<strong>Items</strong>&#8221; are actually array if individual object (item) of the collection which represents the array of tuple of the database query result. As you see in the snippet above the <strong>ArrayIterator </strong>takes <strong>$this-&gt;_items</strong> are parameter. But <strong>$this-&gt;_items</strong> are not populated here on <strong>Varien_Data_Collection</strong> but rather on is child class <strong>Varien_Data_Collection_Db</strong>. Here&#8217;s the snippet from Varien_Data_Collection_Db.</p>
<pre class="brush: php;">
/**
     * Load data
     * @class Varien_Data_Collection_Db
     * @return  Varien_Data_Collection_Db
     */
    public function load($printQuery = false, $logQuery = false)
    {
        if ($this-&gt;isLoaded()) {
            return $this;
        }

        $this-&gt;_renderFilters()
             -&gt;_renderOrders()
             -&gt;_renderLimit();

        $this-&gt;printLogQuery($printQuery, $logQuery);

		// Getting Data from DB
        $data = $this-&gt;getData();

        $this-&gt;resetData();

        if (is_array($data)) {

		    // Looping on each result row
            foreach ($data as $row) {
			    // Creating Empty &quot;item&quot; Varien_Object's object
                $item = $this-&gt;getNewEmptyItem();

                if ($this-&gt;getIdFieldName()) {
                    $item-&gt;setIdFieldName($this-&gt;getIdFieldName());
                }

				// Setting Varien_Object's values to that of the row
                $item-&gt;addData($row);

				/**
				* Adding the &quot;item&quot; to the collection @class Varien_Data_Collection
				* So while referring to $this-&gt;_items @class Varien_Data_Collection it will return array of this &quot;item&quot;
				*/
                $this-&gt;addItem($item);
            }

        }

        $this-&gt;_setIsLoaded();
        $this-&gt;_afterLoad();
        return $this;
    }

    /**
     * Get all data array for collection
     * @class Varien_Data_Collection_Db
     * @return array
     */
    public function getData()
    {
        if ($this-&gt;_data === null) {
            $this-&gt;_renderFilters()
                 -&gt;_renderOrders()
                 -&gt;_renderLimit();

			// Fetching all the row with the Select query set
            $this-&gt;_data = $this-&gt;_fetchAll($this-&gt;_select);
            $this-&gt;_afterLoadData();
        }
        return $this-&gt;_data;
    }
</pre>
<p>You can go through the inline comments I&#8217;ve added. This is it, I&#8217;ve finally worked out the explanation of structure &amp; creation of Magento&#8217;s Collection and its iterative behavior. I&#8217;ve tried to show pictorially (below) what I have just described. Confused! Plz comment and of course please do comment if I am wrong, because there are &#8220;times&#8221; when you try to understand things even though they actually aren&#8217;t just like you think. I&#8217;d like to quote <strong>Paulo </strong> :<strong><em>&#8220;I see the world in terms of what I would like to see happen, not what actually does&#8221;</em></strong>!</p>
<p><img class="alignnone size-full wp-image-249" title="hierarchy" src="http://subesh.com.np/wp-content/uploads/2010/05/hierarchy.jpg" alt="hierarchy" width="505" height="604" />
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/05/analysis-usage-collections-magento/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Magento eCommerce: How To Reset All Test Order Information and Set Unique Prefix For Orders, Invoices, Shipments, and Credit Memos</title>
		<link>http://subesh.com.np/2010/05/magento-ecommerce-how-to-reset-all-test-order-information-and-set-unique-prefix-for-orders-invoices-shipments-and-credit-memos/</link>
		<comments>http://subesh.com.np/2010/05/magento-ecommerce-how-to-reset-all-test-order-information-and-set-unique-prefix-for-orders-invoices-shipments-and-credit-memos/#comments</comments>
		<pubDate>Thu, 06 May 2010 09:54:02 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=242</guid>
		<description><![CDATA[Nice Post I stumbled upon.. from www.eliasinteractive.com. This is a very helpful hack Lee has posted to reset order information while moving from development stage to production stage. I&#8217;d tried this in Enterprise Edition as well and it worked!

Just a Re-Post  
Magento eCommerce: How To Reset All Test Order Information and Set Unique Prefix [...]]]></description>
			<content:encoded><![CDATA[<p>Nice Post I stumbled upon.. from www.eliasinteractive.com. This is a very helpful hack Lee has posted to reset order information while moving from development stage to production stage. I&#8217;d tried this in Enterprise Edition as well and it worked!</p>
<p><span id="more-242"></span></p>
<p>Just a Re-Post <img src='http://subesh.com.np/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><a href="http://www.eliasinteractive.com/blog/magento-ecommerce-how-to-reset-all-test-order-information-and-set-unique-prefix-for-orders-invoices-shipments-and-credit-memos">Magento eCommerce: How To Reset All Test Order Information and Set Unique Prefix For Orders, Invoices, Shipments, and Credit Memos</a>.
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/05/magento-ecommerce-how-to-reset-all-test-order-information-and-set-unique-prefix-for-orders-invoices-shipments-and-credit-memos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solution: Error Message Not Showing up in Frontend in Magento</title>
		<link>http://subesh.com.np/2010/05/solution-error-message-showing-frontends-magento/</link>
		<comments>http://subesh.com.np/2010/05/solution-error-message-showing-frontends-magento/#comments</comments>
		<pubDate>Tue, 04 May 2010 12:22:40 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Block]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=238</guid>
		<description><![CDATA[I recently got to a situation where I needed to add a new frontend template for some module and after some action show the error or success message. Not the first time though  . Interesting thing was even if I added this code in the PHTML file.



&#60;?php echo $this-&#62;getMessagesBlock()-&#62;getGroupedHtml() ?&#62;

It did not work. Yes, [...]]]></description>
			<content:encoded><![CDATA[<p>I recently got to a situation where I needed to add a new frontend template for some module and after some action show the error or success message. Not the first time though <img src='http://subesh.com.np/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . Interesting thing was even if I added this code in the PHTML file.</p>
<p><span id="more-238"></span></p>
<pre class="brush: php;">

&lt;?php echo $this-&gt;getMessagesBlock()-&gt;getGroupedHtml() ?&gt;
</pre>
<p>It did not work. Yes, after adding this block it had worked before. In my case, the probable case might be that I had called the module&#8217;s template from CMS page. In other case it should work. So, I looked for work around and the following did the trick.</p>
<pre class="brush: php;">
// Getting Messages from Session
$messages=Mage::getSingleton(&quot;customer/session&quot;)-&gt;getMessages();

// Creating Block Mage_Core_Block_Messages
// Setting Message
// echoing the Message's HTML
echo $this-&gt;getLayout()-&gt;createBlock(&quot;core/messages&quot;)-&gt;setMessages($messages)-&gt;getGroupedHtml();
</pre>
<p>The Error/Success or Notice messages are set on session. So what I did was take those message/s from the session and create a new block, same as what <strong>$this->getMessagesBlock()</strong> might have called, and set those message to the created block and echoed its HTML.</p>
<p>Clever? or not?</p>
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/05/solution-error-message-showing-frontends-magento/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Redirect to some other location from Model or Observer in Magento</title>
		<link>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/</link>
		<comments>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 12:45:02 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Controllers]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=236</guid>
		<description><![CDATA[Redirection in Magento&#8217;s controller is simple. You just need to call a _redirect() or _forward() function and provide appropriate router/controller/action parameter. But if you want to redirect to some other page from Model or from Observer, then this can be tricky. Lets take an example, for explaining what I am referring to, Suppose you are [...]]]></description>
			<content:encoded><![CDATA[<p>Redirection in Magento&#8217;s controller is simple. You just need to call a <strong>_redirect() </strong>or <strong>_forward() </strong>function and provide appropriate router/controller/action parameter. But if you want to redirect to some other page from Model or from Observer, then this can be tricky. Lets take an example, for explaining what I am referring to, Suppose you are building a module that will only allow user of certain group to view a product in frontend. Then, you will have options like:</p>
<p><span id="more-236"></span></p>
<ul>
<ol>
Rewrite you catalog/product/view controller and add that logic.
</ol>
<ol>
Rewrite Block of that page and show error message accordingly.
</ol>
<ol>
Any other..?
</ol>
</ul>
<p>Yeha, I do have another option as well. The Event-Observer Method. You can observe an event <strong>controller_action_predispatch_catalog_product_view</strong> and set up an observer where you can write your own logic there and redirect accordingly.</p>
<p>You can observe that event by setting up your config something like this.</p>
<pre class="brush: xml;">
&lt;controller_action_predispatch_catalog_product_view&gt;
	&lt;observers&gt;
		&lt;mymodel&gt;
			&lt;type&gt;singleton&lt;/type&gt;
			&lt;class&gt;mymodel/controller_observer&lt;/class&gt;
			&lt;method&gt;controller_action_predispatch_catalog_product_view&lt;/method&gt;
		&lt;/mymodel&gt;
	&lt;/observers&gt;
&lt;/controller_action_predispatch_catalog_product_view&gt;
</pre>
<p>And on the observer&#8217;s <strong>controller_action_predispatch_catalog_product_view</strong> method, you can check your logic for visibiliy of that product to the logged in user group and redirect if not visible.</p>
<p>Here&#8217;s the main point of this post (Did I take a lot of your time ?), in that same method you can directly redirect using the following snippet of code.</p>
<pre class="brush: php;">

Mage::app()-&gt;getResponse()-&gt;setRedirect(Mage::getUrl(&quot;myrouter/mycontroller/noview&quot;));
</pre>
<p>Adding an error message to the session would be a good idea, for user to understand what is happening. Else you can directly call a template in the redirected controller&#8217;s action with appropriate message.</p>
<p>I think this sums up the post for now..and as always hoping it helps somebody and waiting for the response.</p>
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating Backend-Admin URL with Key and Parameters in Magento</title>
		<link>http://subesh.com.np/2010/03/generating-backend-admin-url-key-parameters-magento/</link>
		<comments>http://subesh.com.np/2010/03/generating-backend-admin-url-key-parameters-magento/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 12:52:57 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[url]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=228</guid>
		<description><![CDATA[When you log into adminstrator part of the Magento webshop, and look into the url you may see something like this.

The part in &#8220;RED&#8221; are module controller(router)/action. And the part in &#8220;GREEN&#8221; is what we call as &#8220;Paramerters&#8221; and the &#8220;BLUE&#8221; part is the &#8220;Key&#8220;. The Key (which is also a URL parameter) in the [...]]]></description>
			<content:encoded><![CDATA[<p>When you log into adminstrator part of the Magento webshop, and look into the url you may see something like this.<br />
<div id="attachment_230" class="wp-caption alignnone" style="width: 429px"><img src="http://subesh.com.np/wp-content/uploads/2010/03/adminurl.png" alt="Admin URL with Keys and Parameters" title="Admin URL with Keys and Parameters" width="419" height="42" class="size-full wp-image-230" /><p class="wp-caption-text">Admin URL with Keys and Parameters</p></div></p>
<p><span id="more-228"></span></p>
<p>The part in &#8220;RED&#8221; are module controller(router)/action. And the part in &#8220;GREEN&#8221; is what we call as &#8220;<strong>Paramerters</strong>&#8221; and the &#8220;BLUE&#8221; part is the &#8220;<strong>Key</strong>&#8220;. The Key (which is also a URL parameter) in the URL has been added for security reasons and is checked against the session&#8217;s values for every action. If store owner does not want to use the key in admin url, then it can be set off from administrator settings.</p>
<p>My point in this post is, if you are a developer and creating a module that has Admin controller and you are simply calling some action of your controller lets say,<strong> <em>mymodule/adminhtml_mycontroller/myaction/param1/1/param2/2</em> </strong>the it does not redirect you to your intended page, but will redirect to dashboard, IF key is enabled. You will have to add the key parameter to the URL to go to your page. So here is a simple snippet of code that will help you to build your URL with valid keys.</p>
<pre class="brush: php;">
echo Mage::helper(&quot;adminhtml&quot;)-&gt;getUrl(&quot;mymodule/adminhtml_mycontroller/myaction/&quot;,array(&quot;param1&quot;=&gt;1,&quot;param2&quot;=&gt;2));
</pre>
<p>The &#8220;adminhtml&#8221; helper will automatically create url with keys attached to the URL.</p>
<p>Next thing, if you see the key of various pages in admin you will see that those keys are not same, there is a different logic behind creating those key values. The keys generated depends upon the controller and action you are about to execute. Keys can be seperatly generated as follows.</p>
<pre class="brush: php;">
Mage::getSingleton('adminhtml/url')-&gt;getSecretKey(&quot;adminhtml_mycontroller&quot;,&quot;myaction&quot;);
</pre>
<p>Hope this helps, and this can be particularly helpful when you are using templates in admin modules and adding buttons to redirect to some other location. At least that was my case!</p>
<div style="margin-top: 15px; font-style: italic">
<p><strong>&copy;</strong> <a href="http://subesh.com.np/">Subesh Pokhrel&#039;s Blog &#8211; Magento Development Tips,PHP,Google Maps</a></p>
</div>
<hr /><small>Copyright &copy; 2010<br /> This feed is for personal, non-commercial use only. <br /> The use of this feed on other websites breaches copyright. If this content is not in your news reader, it makes the page you are viewing an infringement of the copyright. </small>]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/generating-backend-admin-url-key-parameters-magento/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
