<?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>El Blog del Antonio &#187; How To</title>
	<atom:link href="http://www.ramirezcobos.com/category/how-to/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ramirezcobos.com</link>
	<description>Programming Web with PHP, CSS, Javascript and ∞</description>
	<lastBuildDate>Wed, 28 Dec 2011 18:26:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using events with CAction classes</title>
		<link>http://www.ramirezcobos.com/2011/10/13/using-events-with-caction-classes/</link>
		<comments>http://www.ramirezcobos.com/2011/10/13/using-events-with-caction-classes/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 13:26:35 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=982</guid>
		<description><![CDATA[
Introduction
There are some good guides out there explaining how to work with events and the ways to attach them to your components, but none (that I know) explain the following way to configure your events with CAction classes on your controllers.
As you know, events are used by:
Declaring an  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img class="alignright size-full wp-image-612" title="Yii Framework" src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" width="160" height="160" /></a></p>
<h2>Introduction</h2>
<p>There are some good guides out there explaining how to work with events and the ways to attach them to your components, but none (that I know) explain the following way to configure your events with CAction classes on your controllers.</p>
<p>As you know, events are used by:</p>
<ul>
<li>Declaring an event in your component adding its method (ie. function onClick($event))</li>
<li>Attach it to event handlers (ie. $object-&gt;onClick=array($handlerObject,&#8217;staticmethod&#8217;);)</li>
<li>Raising it from your component to call all subscribed handlers (ie. $this-&gt;raiseEvent(&#8216;onClick&#8217;,$event)). Remember, that for a handler, you can write an object with static methods, an object with a method, create a function (create_function) and even attach a function directly (since PHP 5.3)</li>
</ul>
<h3>Tip</h3>
<p>If we look at the magic method __set of CComponent, we will see that event handlers are actually set like properties.<br />
Having that into account, the following is my quick tip to set your event handlers when working with CAction classes, which I think is far much better to organize your code in your controllers.</p>
<h4>The CAction class</h4>
<p>Lets write a simple CAction class for the example and save it as EMyAction.php:</p>
<pre class="brush: php; title: ; notranslate">
class EMyAction extends CAction{
	public function onTest($event){
		$this-&gt;raiseEvent('onTest', $event);
	}
	public function run() {
		$event = new CEvent($this);
		$this-&gt;onTest($event);
	}
}
</pre>
<h4>The Controller</h4>
<p>Now in our controller, for the sake of the example, lets write a method handler and configure the action (assumed to be on actions folder under, which is in controllers folder).</p>
<pre class="brush: php; title: ; notranslate">
// our event handler method, that, for simplicity,
// we set it in our controller
public function eventHandlerMethod($event)
{
	echo 'TESTING Handler';
}
// declaring actions and its event handlers
public function actions()
{
	return array(
		// test is the action name &lt;controller/action&gt;
		'test'=&gt;array(
			'class'=&gt;'actions.EMyAction',
			'onTest'=&gt;array($this,'eventHandlerMethod')
		)
    );
}
</pre>
<p>And that&#8217;s it, call the controller&#8217;s action as you would with any other in your preferred browser to test the results.</p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Using%20events%20with%20CAction%20classes%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F10%2F13%2Fusing-events-with-caction-classes%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/10/13/using-events-with-caction-classes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Avoiding duplicate script download when using CActiveForm on Ajax calls</title>
		<link>http://www.ramirezcobos.com/2011/09/11/avoiding-duplicate-script-download-when-using-cactiveform-on-ajax-calls/</link>
		<comments>http://www.ramirezcobos.com/2011/09/11/avoiding-duplicate-script-download-when-using-cactiveform-on-ajax-calls/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 08:23:49 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[CActiveForm]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=895</guid>
		<description><![CDATA[
Introduction
Sometimes the active form we wish to use to edit/add a new element on our database is too small and we believe that is much better to use an AJAX&#8217;ed dialog/slide form rather than reloading the page to just display one or two fields.
The only thing required is simple, we just need to  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" title="Yii Framework" width="160" height="160" class="alignright size-full wp-image-612" /></a><br />
<h3>Introduction</h3>
<p>Sometimes the active form we wish to use to edit/add a new element on our database is too small and we believe that is much better to use an AJAX&#8217;ed dialog/slide form rather than reloading the page to just display one or two fields.</p>
<p>The only thing required is simple, we just need to create a view that will be partially rendered by a call to a controller (using renderPartial) and make sure that we process output -setting to true the parameter on the function. Everything will work as expected but&#8230;</p>
<h3>The issue</h3>
<p>If we open firebug (firefox), or developer tools (chrome), or whatever the tool you use in order to see the XmlHttpRequest object calls and resources downloaded, you will see that every time we do call the controller to display the active form, different Yii &#8220;core JS&#8221; files keeps being downloaded to the client. The JS files downloaded depends on your code but there are at least jquery.js, jquery-ui.js and jquery.yiiactiveform.js.</p>
<h3>The solution</h3>
<p>The solution is a bit tricky but simple. We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality (the button that opens the modal dialog or slides/shows a layer with AJAX&#8217;ed form contents). For example, on index.php view file:</p>
<pre class="brush: php; title: ; notranslate">
cs()-&gt;registerCoreScript('yiiactiveform');
</pre>
<p>Now, I assume that you have created your function to display the AJAX&#8217;ed active form and its contents are returned by a call to a controller&#8217;s action that will partially render a view. This is what we have to do in our action:</p>
<pre class="brush: php; title: ; notranslate">
// Just before rendering the view that
// has our activeform
Yii::app()-&gt;clientScript-&gt;corePackages = array();
</pre>
<p>It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won&#8217;t stop the duplication of the script.</p>
<p>And that&#8217;s it, everything is working as it should.</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Avoiding%20duplicate%20script%20download%20when%20using%20CActiveForm%20on%20Ajax%20calls%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F09%2F11%2Favoiding-duplicate-script-download-when-using-cactiveform-on-ajax-calls%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/09/11/avoiding-duplicate-script-download-when-using-cactiveform-on-ajax-calls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Autocomplete Display and Value Submission</title>
		<link>http://www.ramirezcobos.com/2011/07/14/custom-autocomplete-display-and-value-submission/</link>
		<comments>http://www.ramirezcobos.com/2011/07/14/custom-autocomplete-display-and-value-submission/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 22:03:23 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=879</guid>
		<description><![CDATA[
Introduction
How many of us has wondered how to create an autocomplete that will display the names of a related models but do require the id of that selected name to be submitted for model creation/update?
I was looking around wiki and found that was no approach as the one I did so I guessed this  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" title="Yii Framework" width="160" height="160" class="alignright size-full wp-image-612" /></a><br />
<h2>Introduction</h2>
<p>How many of us has wondered how to create an autocomplete that will display the names of a related models but do require the id of that selected name to be submitted for model creation/update?</p>
<p>I was looking around wiki and found that was no approach as the one I did so I guessed this is worth to write.</p>
<h2>Requirements</h2>
<p>For our example, I want to be able to:</p>
<ul>
<li>Have an autocomplete field in our form</li>
<li>Once user selects an item in the dropdown list and fill a hidden box with the id of the selected item for submission</li>
</ul>
<h2>Making the right choice</h2>
<p>To setup the autocomplete was a very straight forward operation, but I couldn&#8217;t figure out how to get values from a custom JSON response and then fill the correspondent hidden fields.</p>
<p><a title="CAutoComplete" href="http://www.yiiframework.com/doc/api/1.1/CAutoComplete" target="_blank">CAutoComplete</a> does has a way to do it, but I wanted to use <a title="CJuiAutoComplete" href="http://www.yiiframework.com/doc/api/1.1/CJuiAutoComplete" target="_blank">CJuiAutoComplete</a> to get all the cool features of its JQuery Ui and by looking at his code there was no method chain, something that is required to work with custom JSON responses as we need to override some methods.</p>
<h2>My Solution</h2>
<p>After doing some research I decided to:</p>
<ol>
<li>extend from <a title="CJuiAutocomplete" href="http://www.yiiframework.com/doc/api/1.1/CJuiAutoComplete" target="_blank">CJuiAutoComplete</a></li>
<li>include the required property for method chain and modify its &#8216;run&#8217; function</li>
<li>then initialize the newly created property with the javascript functions that handle my custom JSON</li>
</ol>
<h3>Extending from CJuiAutoComplete and make required modifications</h3>
<p>Very simple, we are going to add a methodChain property and modify the run function to include it (zii is not a major concern to Yii, but main developers should think about this minor change).</p>
<pre class="brush: php; title: ; notranslate">
class myAutoComplete extends CJuiAutoComplete
{
    /**
     * @var string the chain of method calls that would be appended at the end of the autocomplete constructor.
     * For example, &quot;.result(function(...){})&quot; would cause the specified js function to execute
     * when the user selects an option.
     */
    public $methodChain;
    /**
     * Run this widget.
     * This method registers necessary javascript and renders the needed HTML code.
     */
    public function run()
    {
        list($name,$id)=$this-&gt;resolveNameID();
        if(isset($this-&gt;htmlOptions['id']))
            $id=$this-&gt;htmlOptions['id'];
        else
            $this-&gt;htmlOptions['id']=$id;
        if(isset($this-&gt;htmlOptions['name']))
            $name=$this-&gt;htmlOptions['name'];
        if($this-&gt;hasModel())
            echo CHtml::activeTextField($this-&gt;model,$this-&gt;attribute,$this-&gt;htmlOptions);
        else
            echo CHtml::textField($name,$this-&gt;value,$this-&gt;htmlOptions);
        if($this-&gt;sourceUrl!==null)
            $this-&gt;options['source']=CHtml::normalizeUrl($this-&gt;sourceUrl);
        else
            $this-&gt;options['source']=$this-&gt;source;
        $options=CJavaScript::encode($this-&gt;options);
        $js = &quot;jQuery('#{$id}').autocomplete($options){$this-&gt;methodChain};&quot;;
        $cs = Yii::app()-&gt;getClientScript();
        $cs-&gt;registerScript(__CLASS__.'#'.$id, $js);
    }
}
</pre>
<h2>Using our widget</h2>
<p>Now that we have our beautiful widget that handles method chain in our Autocomplete, let&#8217;s assume a couple of things:</p>
<ul>
<li>We saved our class onto a folder in our application -ie protected/extensions</li>
<li>We have a hidden INPUT HTML element with model&#8217;s attribute_id</li>
<li>We have created an action on our testController named autocomplete that returns a JSON object on the following format:</li>
</ul>
<pre class="brush: php; title: ; notranslate">
// This function will echo a JSON object
// on this format:
// [{id:id, name: 'name'}]
public function actionAutocomplete(){
      $res = array();
      $term = Yii::app()-&gt;getRequest()-&gt;getParam('term', false);
      if ($term)
      {
         // test table is for the sake of this example
         $sql = 'SELECT id, name FROM {{test}} where LCASE(name) LIKE :name';
         $cmd = Yii::app()-&gt;db-&gt;createCommand($sql);
         $cmd-&gt;bindValue(&quot;:name&quot;,&quot;%&quot;.strtolower($term).&quot;%&quot;, PDO::PARAM_STR);
         $res = $cmd-&gt;queryAll();
      }
      echo CJSON::encode($res);
      Yii::app()-&gt;end();
}
</pre>
<p>We have everything, let&#8217;s use our widget in our view:</p>
<pre class="brush: php; title: ; notranslate">
// REMEMBER, we have a hidden
// input HTML element with model's attribute_id
&lt;?php echo $form-&gt;hiddenField($model, 'attribute_id'); ?&gt;
&lt;?php
// ext is a shortcut for application.extensions
$this-&gt;widget('ext.myAutoComplete', array(
    'name' =&gt; 'test_autocomplete',
    'source' =&gt; $this-&gt;createUrl('test/autocomplete'),
// attribute_value is a custom property that returns the
// name of our related object -ie return $model-&gt;related_model-&gt;name
    'value' =&gt; $model-&gt;isNewRecord ? '': $model-&gt;attribute_value,
    'options' =&gt; array(
        'minChars'=&gt;3,
        'autoFill'=&gt;false,
        'focus'=&gt; 'js:function( event, ui ) {
            $( &quot;#test_autocomplete&quot; ).val( ui.item.name );
            return false;
        }',
        'select'=&gt;'js:function( event, ui ) {
            $(&quot;#'.CHtml::activeId($model,'attribute_id').'&quot;)
            .val(ui.item.id);
            return false;
        }'
     ),
    'htmlOptions'=&gt;array('class'=&gt;'input-1', 'autocomplete'=&gt;'off'),
    'methodChain'=&gt;'.data( &quot;autocomplete&quot; )._renderItem = function( ul, item ) {
        return $( &quot;&lt;li&gt;&lt;/li&gt;&quot; )
            .data( &quot;item.autocomplete&quot;, item )
            .append( &quot;&lt;a&gt;&quot; + item.name +  &quot;&lt;/a&gt;&quot; )
            .appendTo( ul );
    };'
));
?&gt;
</pre>
<p>Done! Just make sure that when you do submit your form, you get the value from the hidden field instead of the autocomplete element <img src='http://www.ramirezcobos.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Final Notes</h2>
<p>I do not know if there are other ways of doing the same thing (apart from pure Javascript) to have the same results. If you know, with CJuiAutoComplete widget, let us know here.</p>
<p>Hope you find this useful.</p>
<p>Cheers</p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Custom%20Autocomplete%20Display%20and%20Value%20Submission%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F07%2F14%2Fcustom-autocomplete-display-and-value-submission%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/07/14/custom-autocomplete-display-and-value-submission/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Implementing a User Level Access System</title>
		<link>http://www.ramirezcobos.com/2011/04/20/implementing-a-user-level-access-system/</link>
		<comments>http://www.ramirezcobos.com/2011/04/20/implementing-a-user-level-access-system/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 19:23:35 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=853</guid>
		<description><![CDATA[
I would like to explain this time how easy is to implement a level access system with Yii framework.
Please note that this article is a simple example and good security should be taken into account when we play with authentication systems.
Step 1: Setting Up
a. Include a field on your user&#8217;s table  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" title="Yii Framework" width="160" height="160" class="alignright size-full wp-image-612" /></a></p>
<p>I would like to explain this time how easy is to implement a level access system with Yii framework.</p>
<p>Please note that this article is a simple example and good security should be taken into account when we play with authentication systems.</p>
<h3>Step 1: Setting Up</h3>
<p>a. <strong>Include a field on your user&#8217;s table named, </strong>yep you guessed<strong>, level</strong><br />
b. <strong>Create an object &#8216;LevelLookUp&#8217; </strong>that will tell us who is who on this system</p>
<pre class="brush: php; title: ; notranslate">
class LevelLookUp{
      const MEMBER = 0;
      const ADMIN  = 2;
      // For CGridView, CListView Purposes
      public static function getLabel( $level ){
          if($level == self::MEMBER)
             return 'Member';
          if($level == self::ADMIN)
             return 'Administrator';
          return false;
      }
      // for dropdown lists purposes
      public static function getLevelList(){
          return array(
                 self::MEMBER=&gt;'Member',
                 self::ADMIN=&gt;'Administrator');
	}
}
</pre>
<p>c.<strong>Modifying UserIdentity</strong> so we can store the user Model id on authentication, as CWebUser&#8217;s default id is set to the user Model&#8217;s username:</p>
<pre class="brush: php; title: ; notranslate">
class UserIdentity extends CUserIdentity
{
	private $_id;
	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$username = strtolower($this-&gt;username);
                // from database... change to suite your authentication criteria
		$user = User::model()-&gt;find('LOWER(username)=?', array($username));
		if($user===null)
			$this-&gt;errorCode=self::ERROR_USERNAME_INVALID;
		else if(!$user-&gt;validatePassword($this-&gt;password))
			$this-&gt;errorCode = self::ERROR_PASSWORD_INVALID;
		else{
			$this-&gt;_id = $user-&gt;id;
			$this-&gt;username = $user-&gt;username;
			$this-&gt;errorCode = self::ERROR_NONE;
		}
		return $this-&gt;errorCode == self::ERROR_NONE;
	}
	public function getId()
	{
		return $this-&gt;_id;
	}
}
</pre>
<p>d. <strong>Modify CWebUser&#8217;s application</strong> in order to hold the &#8216;level&#8217; property. We are going to call it EWebUser and will extend from CWebUser, and save it on protected/components to be loaded automatically by our default&#8217;s configuration file.</p>
<pre class="brush: php; title: ; notranslate">
class EWebUser extends CWebUser{
    protected $_model;
    function isAdmin(){
        $user = $this-&gt;loadUser();
        if ($user)
           return $user-&gt;level==LevelLookUp::ADMIN;
        return false;
    }
    // Load user model.
    protected function loadUser()
    {
        if ( $this-&gt;_model === null ) {
                $this-&gt;_model = User::model()-&gt;findByPk( $this-&gt;id );
        }
        return $this-&gt;_model;
    }
}
</pre>
<p>e. <strong>Modify our main.php</strong> config file (this file is in protected/config folder)</p>
<pre class="brush: php; title: ; notranslate">
// go to the 'user' section
// application components
	'components'=&gt;array(
		'user'=&gt;array(
                        // There you go, use our 'extended' version
			'class'=&gt;'application.components.EWebUser',
			// enable cookie-based authentication
			'allowAutoLogin'=&gt;true,
		),
</pre>
<h3>Step 2: Putting everything together</h3>
<p>Now that we know, who logged, we could easily find out if it is just a member or an administrator and render the elements by checking the level as simple as this:</p>
<pre class="brush: php; title: ; notranslate">
// for normal content
if(Yii::app()-&gt;user-&gt;isAdmin())
     echo 'Is administrator';
// for CMenus
$this-&gt;widget('zii.widgets.CMenu',array(
    array('label'=&gt;'Categories',
           'url'=&gt;array('/category/index'),
           'visible'=&gt;(Yii::app()-&gt;user-&gt;isAdmin()),
     //... More stuff
     //...
// for data chuncks
&lt;?php if(Yii::app()-&gt;user-&gt;isAdmin():?&gt;
&lt;b&gt;My HTML&lt;/b&gt;
&lt;?php endif;?&gt;
// for access rules
return array(
      array('allow',
        'actions'=&gt;array('create','delete','update'),
        'expression'=&gt;'$user-&gt;isAdmin()'
      ),
// ...
</pre>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Implementing%20a%20User%20Level%20Access%20System%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F04%2F20%2Fimplementing-a-user-level-access-system%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/04/20/implementing-a-user-level-access-system/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Actions code reuse with CAction</title>
		<link>http://www.ramirezcobos.com/2011/04/07/actions-code-reuse-with-caction/</link>
		<comments>http://www.ramirezcobos.com/2011/04/07/actions-code-reuse-with-caction/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 08:15:13 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=839</guid>
		<description><![CDATA[Introduction
We all know how good &#8216;gii&#8217; automates the code for us and we normally tend to be happy with what that tool offers at the beginning of our Yii learning curve. But as soon as you start working in larger and larger projects, you realize that its code is too repetitive to maintain and  [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" title="Yii Framework" width="160" height="160" class="alignright size-full wp-image-612" /></a>We all know how good &#8216;gii&#8217; automates the code for us and we normally tend to be happy with what that tool offers at the beginning of our Yii learning curve. But as soon as you start working in larger and larger projects, you realize that its code is too repetitive to maintain and having a small pitfall in general actions means to go over and over through them to fix the issues.</p>
<h2>CAction to the Rescue</h2>
<p>I have already explained how to use widgets as action providers to encapsulate the actions. What I am going to explain here is how can we easily create an action to work throughout different controllers.</p>
<p>Gii provides us normally with the following code on the &#8216;actionCreate&#8217;:</p>
<pre class="brush: php; title: ; notranslate">
public function actionCreate()
{
   $model=new ModelName;
   // Uncomment the following line if AJAX validation is needed
   // $this-&gt;performAjaxValidation($model);
   if(isset($_POST['ModelName']))
   {
       $model-&gt;attributes=$_POST['ModelName'];
       if($model-&gt;save())
         $this-&gt;redirect(array('view','id'=&gt;$model-&gt;id));
   }
   $this-&gt;render('create',array(
       'model'=&gt;$model,
   ));
}
</pre>
<p>For a normal project and with the default CMS layout of Yii, does suit our regular needs and we tend to leave it as it is. But, as I said before, imagine that we need to include a new parameter in our redirection for example? In order to avoid that we can tweak a bit the code and develop a general action.</p>
<h3>Step 1 &#8211; Creating the Action</h3>
<p>For the sake of the example, create the following action and save it on your protected/components/actions folder</p>
<pre class="brush: php; title: ; notranslate">
class Create extends CAction {
    public function run() {
    $controller = $this-&gt;getController();
    // get the Model Name
    $model_class = ucfirst($controller-&gt;getId());
    // create the Model
    $model = new $model_class();
    // Uncomment the following line if AJAX validation is needed
    // $this-&gt;performAjaxValidation($model);
    if (isset($_POST[$model_class])) {
        $model-&gt;attributes = $_POST[$model_class];
        if ($model-&gt;save())
        $controller-&gt;redirect(array('view', 'id' =&gt; $model-&gt;id));
    }
    $controller-&gt;render('create', array(
        'model' =&gt; $model,
    ));
    }
}
</pre>
<h3>Step 2 &#8211; Declare the action on the Controller</h3>
<p>Once we have the action class created, the only thing we need to do is declare it in our controller&#8217;s actions function in order to use it.</p>
<pre class="brush: php; title: ; notranslate">
public function actions(){
   return array(
      'create'=&gt;'application.components.actions.create',
   );
}
</pre>
<p>After declaring the action we can call it: http://myhost/index.php?r=controller/create, just like any other.</p>
<h3>Final Notes</h3>
<p>In the example above I have used &#8216;getController()&#8217; and &#8216;getId()&#8217; in order to access the model, but we can actually use properties as CAction is a class. This could be the declaration of an action passing the model name to load:</p>
<pre class="brush: php; title: ; notranslate">
// Assuming the action class has the
// following public properties:
// public model_name
// -----------------
// ModelClass is a test model class name
// -----------------
// On the controller:
public function actions(){
   return array(
      'create'=&gt;array(
          'class'=&gt;'application.components.actions.create',
          'model_name'=&gt;'ModelClass',
   );
}
</pre>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Actions%20code%20reuse%20with%20CAction%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F04%2F07%2Factions-code-reuse-with-caction%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/04/07/actions-code-reuse-with-caction/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>EGMaps 2.0 News: Layers, Polygons and Rectangles</title>
		<link>http://www.ramirezcobos.com/2011/03/24/egmaps-2-0-news-layers-polygons-and-rectangles/</link>
		<comments>http://www.ramirezcobos.com/2011/03/24/egmaps-2-0-news-layers-polygons-and-rectangles/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 08:45:08 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[EGMap]]></category>
		<category><![CDATA[News]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=831</guid>
		<description><![CDATA[The new version of EGMaps 2.0 is about to see the light. In the meantime new features have been included and are available through the SVN source at google&#8217;s code. Even though we are planning many more features, the following  are the list of the newly inserted features of the Yii extension till  [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_834" class="wp-caption alignright" style="width: 310px"><a rel="attachment wp-att-834" href="http://www.ramirezcobos.com/2011/03/24/egmaps-2-0-news-layers-polygons-and-rectangles/captura-de-pantalla-2011-03-24-a-las-09-41-48/"><img class="size-medium wp-image-834" title="Circles and Rectangles" src="http://www.ramirezcobos.com/wp-content/uploads/2011/03/Captura-de-pantalla-2011-03-24-a-las-09.41.48-300x177.png" alt="" width="300" height="177" /></a><p class="wp-caption-text">Overlays</p></div>
<p>The new version of EGMaps 2.0 is about to see the light. In the meantime new features have been included and are available <a href="http://code.google.com/p/egmap/source/checkout">through the SVN source at google&#8217;s code</a>. Even though we are planning many more features, the following  are the list of the newly inserted features of the Yii extension till date:</p>
<ul>
<li>Polygons (committer <a href="http://www.yiiframework.com/forum/index.php?/user/14177-matt-kay/">Matthias Kay</a>)</li>
<li>Rectangles</li>
<li>Circles</li>
<li>Bicycling Layer</li>
<li>Traffic Layer</li>
<li>Panoramio Layer</li>
</ul>
<h3>Polygon Example</h3>
<pre class="brush: php; title: ; notranslate">
Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap-&gt;setWidth(588);
$gMap-&gt;setHeight(345);
$gMap-&gt;zoom = 3;
$gMap-&gt;mapTypeControlOptions = array(
 'position'=&gt; EGMapControlPosition::RIGHT_TOP,
 'style'=&gt;EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap-&gt;setCenter(34.04924594193164, -118.24104309082031);
$coords = array();
$coords[] = new EGMapCoord(25.774252, -80.190262);
$coords[] = new EGMapCoord(18.466465, -66.118292);
$coords[] = new EGMapCoord(32.321384, -64.75737);
$coords[] = new EGMapCoord(25.774252, -80.190262);
$polygon = new EGMapPolygon($coords);
$gMap-&gt;addPolygon($polygon);
$gMap-&gt;centerOnPolygons();
$gMap-&gt;zoomOnPolygons(0.1);
$gMap-&gt;renderMap(array(),'en','ES');
</pre>
<h3>Circle and Rectangle Example</h3>
<pre class="brush: php; title: ; notranslate">
Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap-&gt;setWidth(588);
$gMap-&gt;setHeight(345);
$gMap-&gt;zoom = 3;
$gMap-&gt;mapTypeControlOptions = array(
 'position'=&gt; EGMapControlPosition::RIGHT_TOP,
 'style'=&gt;EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap-&gt;setCenter(34.04924594193164, -118.24104309082031);
$circle = new EGMapCircle(new EGMapCoord(34.04924594193164, -118.24104309082031));
$circle-&gt;radius = 300000;
// we can even attach info windows to the overlay!
$circle-&gt;addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a circlel!'));
$gMap-&gt;addCircle($circle);
$bounds = new EGMapBounds(new EGMapCoord(25.774252, -80.190262),new EGMapCoord(32.321384, -64.75737) );
$rec = new EGMapRectangle($bounds);
$rec-&gt;addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a rectangle!'));
$gMap-&gt;addRectangle($rec);
$gMap-&gt;renderMap(array(),'en','ES');
</pre>
<h3>Panoramio Layer Example</h3>
<pre class="brush: php; title: ; notranslate">
$gMap = new EGMap();
$gMap-&gt;setWidth(588);
$gMap-&gt;setHeight(345);
$gMap-&gt;zoom = 3;
$gMap-&gt;mapTypeControlOptions = array(
 'position'=&gt; EGMapControlPosition::RIGHT_TOP,
 'style'=&gt;EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap-&gt;setCenter(34.04924594193164, -118.24104309082031);
// we can also use the same way TRAFFIC and BICYCLING layers
$gMap-&gt;setLayer(new EGMapLayer(EGMapLayer::PANORAMIO));
$gMap-&gt;renderMap(array(),'en','ES');
</pre>
<p>The extension has also been updated its reverse geocoding (committer <a href="http://www.yiiframework.com/forum/index.php?/user/6867-say-ten/">Say_Ten</a>).</p>
<p>Please, remember that in order to work with the above examples you require to download the svn source from the google code, not the zipped package on Yii&#8217;s repository. The extension will be updated when we reach the following goals:</p>
<ul>
<li>Elevation Paths</li>
<li>Polylines</li>
<li>Ground Overlays</li>
<li>Animations</li>
<li>Map Styling</li>
</ul>
<p>&nbsp;<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>&nbsp;</p>
<a href="http://twitter.com/?status=RT%20%40%3A%20EGMaps%202.0%20News%3A%20Layers%2C%20Polygons%20and%20Rectangles%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F03%2F24%2Fegmaps-2-0-news-layers-polygons-and-rectangles%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/03/24/egmaps-2-0-news-layers-polygons-and-rectangles/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to use a Widget as an Action Provider</title>
		<link>http://www.ramirezcobos.com/2011/02/17/how-to-use-a-widget-as-an-action-provider/</link>
		<comments>http://www.ramirezcobos.com/2011/02/17/how-to-use-a-widget-as-an-action-provider/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 20:20:38 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=818</guid>
		<description><![CDATA[At the Yii forum there a good question about this matter, and most of us where curious on how this feature actually works.
As usual in the API docs it was clearly written but sometimes the text just sounds like a test for a car driver license. Nevertheless, after creating a test scenario, I found  [...]]]></description>
			<content:encoded><![CDATA[<p><a rel="attachment wp-att-612" href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/"><img class="alignright size-full wp-image-612" title="Yii Framework" src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" width="160" height="160" /></a>At the <a href="http://www.yiiframework.com/forum/index.php?/topic/16357-how-to-use-widget-as-action-provider/page__pid__81325#entry81325">Yii forum there a good question</a> about this matter, and most of us where curious on how this feature actually works.</p>
<p>As usual in the API docs it was clearly written but sometimes the text just sounds like a test for a car driver license. Nevertheless, after creating a test scenario, I found the solution and this is article is to show you exactly how this is done.</p>
<h3>Why would I need an action provider?</h3>
<p>Well, imagine you have lots of general actions that could be shared among controllers. It is true that by setting the actions() function to point to the external CAction classes files but just imagine that those functions are encapsulated by just a class (a widget in this case) and<a href="http://www.yiiframework.com/doc/api/1.1/CController#actions-detail"> you just need a line of code</a> to import all of its actions.</p>
<h3>First Step: Create your Action</h3>
<p>For the sake of the article we creating an action named getData that supposed to be shared among the whole project and saved with the name <strong>getData.php</strong> on our <strong>protected/components/actions</strong> folder.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class getData extends CAction{
	public function run(){
		echo 'HELLO WORLD';
	}
}
</pre>
<h3>Second Step: configure the Widget</h3>
<p>To transform a Widget into an action provider is quite easy (once you know of course). The only thing we need to do is to set the <strong>static method actions()</strong>. As you will see on the following code, we name the action as <strong>GetData</strong> and that is the action that will be called in our route. We are going to save the following widget in our <strong>protected/components/</strong> folder with the name <strong>testProvider.php.</strong></p>
<pre class="brush: php; title: ; notranslate">
class testProvider extends CWidget{
	public static function actions(){
		return array(
                   // naming the action and pointing to the location
                   // where the external action class is
		   'GetData'=&gt;'application.components.actions.getData',
		);
	}
}
</pre>
<h3>Step 3: Configure our Controller</h3>
<p>Finally we set our controller&#8217;s <strong>actions()</strong> function to point to our actions provider.</p>
<pre class="brush: php; title: ; notranslate">
// This function is in this example
// on SiteController
public function actions()
{
        return array(
        // test. is the prefix we are going to use
        // for all action within the actionProvider class
        // we point to the location where the provider
        // is
	'test.'=&gt;'application.components.testProvider',
	);
}
</pre>
<p>Now we can call the action as controllerID/actionPrefix.actionID</p>
<pre class="brush: php; title: ; notranslate">
index.php?site/test.GetData
</pre>
<p><center><br />
<a href="http://www.amazon.com/gp/product/1847199585/ref=as_li_tf_tl?ie=UTF8&#038;tag=ibizapirates-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=1847199585">Agile Web Application Development with Yii 1.1 and PHP5</a><img src="http://www.assoc-amazon.com/e/ir?t=ibizapirates-20&#038;l=as2&#038;o=1&#038;a=1847199585" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /><br />
</center></p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20How%20to%20use%20a%20Widget%20as%20an%20Action%20Provider%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F02%2F17%2Fhow-to-use-a-widget-as-an-action-provider%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/02/17/how-to-use-a-widget-as-an-action-provider/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A sidebar marker trigger with EGMap 2.0</title>
		<link>http://www.ramirezcobos.com/2011/02/11/a-sidebar-marker-trigger-with-egmap-2-0/</link>
		<comments>http://www.ramirezcobos.com/2011/02/11/a-sidebar-marker-trigger-with-egmap-2-0/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 10:08:29 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[EGMap]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=806</guid>
		<description><![CDATA[
Introduction
This is another article from a feature requested by a EGMap Yii Extension User. He proposed me when the following will be incorporated to the library: http://gmaps-samples-v3.googlecode.com/svn/trunk/sidebar/random-markers.html.
I am going to demonstrate that the extension is already  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2011/02/11/a-sidebar-marker-trigger-with-egmap-2-0/captura-de-pantalla-2011-02-11-a-las-10-59-28/" rel="attachment wp-att-807"><img src="http://www.ramirezcobos.com/wp-content/uploads/2011/02/Captura-de-pantalla-2011-02-11-a-las-10.59.28-300x244.png" alt="" title="Sidebar marker event trigger" width="300" height="244" class="alignright size-medium wp-image-807" /></a><br />
<h3>Introduction</h3>
<p>This is another article from a feature requested by a EGMap Yii Extension User. He proposed me when the following will be incorporated to the library: <a href="http://gmaps-samples-v3.googlecode.com/svn/trunk/sidebar/random-markers.html">http://gmaps-samples-v3.googlecode.com/svn/trunk/sidebar/random-markers.html</a>.</p>
<p>I am going to demonstrate that the extension is already capable of creating that without the need of more &#8216;library tweaking&#8217;. </p>
<h3>HTML and Styling</h3>
<p>First of all we are going to write the CSS and the HTML that will &#8216;mimic&#8217; the example provided in the previous link. As you are going to see, there is also a JavaScript helper function that will handle the creation of LI elements (as in the example).</p>
<pre class="brush: xml; title: ; notranslate">
&lt;style&gt;
#sideContainer {
    list-style-type: none;
    padding: 0;
    margin: 0 10px 0 0;
    float: left;
    border: 1px solid #676767;
    background-color: #eee;
    overflow: auto;
  }
  #sideContainer li {
    font-size: 0.9em;
    border-bottom: 1px solid #aaa;
    padding: 5px;
  }
  #mapContainer {
    float: left;
    width: 500px;
    height: 400px;
  }
 &lt;/style&gt;
&lt;/head&gt;
&lt;script&gt;
// global marker counter
var n = 1;
function generateListElement( marker ){
    var ul = document.getElementById('sideContainer');
    var li = document.createElement('li');
    var aSel = document.createElement('a');
    aSel.href = 'javascript:void(0);';
    aSel.innerHTML = 'Open Marker #' + n++;
    aSel.onclick = function(){ google.maps.event.trigger(marker, 'click')};
    li.appendChild(aSel);
    ul.appendChild(li);
}
&lt;/script&gt;
&lt;body&gt;
&lt;!-- the side menu container --&gt;
&lt;ul id=&quot;sideContainer&quot; style&gt;&lt;/ul&gt;
&lt;!-- we are going to render the map here --&gt;
&lt;div id=&quot;mapContainer&quot;&gt;&lt;/div&gt;
</pre>
<h3>Creating the Map</h3>
<p>For the sake of this example, we are going to create just one EGMapInfoWindow object and two markers. The most important thing is to demonstrate how to use callbackTriggers with EGMap 2.0. As you will now see, it is pretty easy to do.</p>
<pre class="brush: php; title: ; notranslate">
// array holding a reference to all the markers
// that will be rendered to the Map
$markers = array();
$gMap = new EGMap();
$gMap-&gt;zoom = 10;
$gMap-&gt;setCenter('39.721089311812094', '2.91165944519042');
// Create GMapInfoWindow
$info_window_b = new EGMapInfoWindow('Hey! I am a marker with label!');
// Create 1st marker
$marker = new EGMapMarker(39.721089311812094, 2.91165944519042, array('title' =&gt; 'Marker With Label'));
// attach info window
$marker-&gt;addHtmlInfoWindow($info_window_b);
// add to map
$gMap-&gt;addMarker($marker);
// add to array
$markers[] = $marker;
// repeat process with second
$marker = new EGMapMarker(39.721089311812094, 2.81165944519042, array('title' =&gt; 'Marker With Label'));
$marker-&gt;addHtmlInfoWindow($info_window_b);
$gMap-&gt;addMarker($marker);
$markers[] = $marker;
// tell the map we want to render it
// to a specific layer
$gMap-&gt;appendMapTo('#mapContainer');
// initialize the afterInit array that
// will hold after map initialization
// script code
$afterInit = array();
//
// loop through markers and
// call global function to generate
// the element that will hold the
// callback trigger event
foreach($markers as $marker){
	$afterInit[] = 'generateListElement('.$marker-&gt;getJsName().');'.PHP_EOL;
}
// now render map and pass the afterInit code
$gMap-&gt;renderMap($afterInit);
</pre>
<h3>Final Words</h3>
<p>The above code is very simplistic, if we were to render lots of markers to the map, a better approach would be to make that on a loop and even more, create a couple of functions to simplify the creation of the markers.</p>
<p>Hope this example helps you guys to better understand the flexibility of this extension. Thanks all for using it. </p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20A%20sidebar%20marker%20trigger%20with%20EGMap%202.0%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F02%2F11%2Fa-sidebar-marker-trigger-with-egmap-2-0%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/02/11/a-sidebar-marker-trigger-with-egmap-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Reverse Geolocator Tool with EGMap 2.0 Extension</title>
		<link>http://www.ramirezcobos.com/2011/02/05/a-reverse-geolocator-tool-with-egmap-2-0-extension/</link>
		<comments>http://www.ramirezcobos.com/2011/02/05/a-reverse-geolocator-tool-with-egmap-2-0-extension/#comments</comments>
		<pubDate>Sat, 05 Feb 2011 17:12:04 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[EGMap]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=797</guid>
		<description><![CDATA[I have been requested to create an article about a reverse geolocator tool, that is a tool to find out the latitude and longitude of a location, to include on our CMS, and here it is.
Styling, Javascript and HTML
First of all, we are going to write the HTML that will work with this example, it  [...]]]></description>
			<content:encoded><![CDATA[<p><a rel="attachment wp-att-800" href="http://www.ramirezcobos.com/2011/02/05/a-reverse-geolocator-tool-with-egmap-2-0-extension/reverse-geolocator-egmap-yii/"><img class="alignright size-medium wp-image-800" title="Reverse-geolocator-EGMap-Yii" src="http://www.ramirezcobos.com/wp-content/uploads/2011/02/Reverse-geolocator-EGMap-Yii-300x280.png" alt="" width="300" height="280" /></a>I have been requested to create an article about a reverse geolocator tool, that is a tool to find out the latitude and longitude of a location, to include on our CMS, and here it is.</p>
<h3>Styling, Javascript and HTML</h3>
<p>First of all, we are going to write the HTML that will work with this example, it won&#8217;t styled as the example picture displayed, which is the tool I created for a project I am working now, but don&#8217;t you worry as this article will provide you with the scripts and routines to create your own.</p>
<p>Write the following style on the HEAD section of your HTML page:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;style&gt;
  div#map {
    position: relative;
  }
  div#crosshair {
    position: absolute;
/*
     the top will be half of the width of the map
     less 50% of its size more or less
     to center the image correctly on the map
*/
    top: 192px;
    height: 19px;
    width: 19px;
    left: 50%;
    margin-left: -8px;
    display: block;
/* we are going to borrow a crosshair gif from google */
    background: url(http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/crosshair.gif);
    background-position: center center;
    background-repeat: no-repeat;
}
&lt;/style&gt;
</pre>
<p>Now, some Javascript functions that will allow us to get the information from the map</p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;&gt;
  //
  // function to get the latitude and longitude
  // and place them on the test fields
  function setLatLngToClass(){
	if(document.getElementById('test_latitude'))
	 	document.getElementById('test_latitude').value = map.getCenter().lat();
	if(document.getElementById('test_longitude'))
		document.getElementById('test_longitude').value = map.getCenter().lng();
  }
  //
  // function to get Centered Latitude and Longitude points
  function getCenterLatLngText() {
    return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
  }
  //
  // function to call when the center of the map
  // has changed. Center information will be
  // collected and displayed on the document
  // elements
  function centerChanged() {
    centerChangedLast = new Date();
    var latlng = getCenterLatLngText();
    document.getElementById('latlng').innerHTML = latlng;
    document.getElementById('formatedAddress').innerHTML = '';
    currentReverseGeocodeResponse = null;
  }
  //
  // Collects reverse center location
  function reverseGeocode() {
    reverseGeocodedLast = new Date();
    geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
  }
  //
  // Displays collected reverse geocoded results
  // and displays them on document elements
  function reverseGeocodeResult(results, status) {
    currentReverseGeocodeResponse = results;
    if(status == 'OK') {
      if(results.length == 0) {
        document.getElementById('formatedAddress').innerHTML = 'None';
      } else {
        document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
      }
    } else {
      document.getElementById('formatedAddress').innerHTML = 'Error';
    }
  }
  //
  // geocodes the address inserted
  function geocode() {
    var address = document.getElementById(&quot;address&quot;).value;
    geocoder.geocode({
      'address': address,
      'partialmatch': true}, geocodeResult);
  }
  function geocodeResult(results, status) {
    if (status == 'OK' &amp;&amp; results.length &gt; 0) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert(&quot;Geocode was not successful for the following reason: &quot; + status);
    }
  }
 //
 // adds marker to the center of the map
  function addMarkerAtCenter() {
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map
    });
    var text = 'Lat/Lng: ' + getCenterLatLngText();
    if(currentReverseGeocodeResponse) {
      var addr = '';
      if(currentReverseGeocodeResponse.size == 0) {
        addr = 'None';
      } else {
        addr = currentReverseGeocodeResponse[0].formatted_address;
      }
      text = text + '&lt;br&gt;' + 'address: &lt;br&gt;' + addr;
    }
    var infowindow = new google.maps.InfoWindow({ content: text });
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
  }
&lt;/script&gt;
</pre>
<p>Our HTML on this example will be the following one:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;body style=&quot;background:white&quot;&gt;
&lt;div class=&quot;form&quot;&gt;
Find by address:
 &lt;input type=&quot;text&quot; id=&quot;address&quot; style=&quot;width:300px&quot;/&gt;
 &lt;button type=&quot;button&quot; class=&quot;small&quot;onclick=&quot;geocode()&quot;&gt;Go to Address&lt;/button&gt;
  &lt;ul&gt;
     &lt;li&gt;Lat/Lng:&amp;nbsp;&lt;span id=&quot;latlng&quot;&gt;&lt;/span&gt;&lt;/li&gt;
     &lt;li&gt;Address:&amp;nbsp;&lt;span id=&quot;formatedAddress&quot;&gt;&lt;/span&gt;&lt;/li&gt;
     &lt;li&gt;Zoom Level:&amp;nbsp;&lt;span id=&quot;zoom_level&quot;&gt;&lt;?php echo $zoom;?&gt;&lt;/span&gt;&lt;/li&gt;
 &lt;/ul&gt;
&lt;/div&gt;
&lt;div id=&quot;map&quot;&gt;
    &lt;div id=&quot;map_canvas&quot; style=&quot;width:100%; height:400px&quot;&gt;&lt;/div&gt;
    &lt;div id=&quot;crosshair&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;overflow:hidden;width:100%;text-align:right&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;small&quot; onclick=&quot;setLatLngToClass()&quot;&gt;Set Latitude &amp; Longitude&lt;/button&gt;
&lt;button type=&quot;button&quot; class=&quot;small&quot; onclick=&quot;addMarkerAtCenter()&quot;&gt;Add Marker at Center&lt;/button&gt;
&lt;/div&gt;
&lt;hr&gt;
Latitude: &lt;input id=&quot;test_latitude&quot; value=&quot;&quot;/&gt; Longitude: &lt;input id=&quot;test_longitude&quot; value=&quot;&quot;/&gt;
&lt;/hr&gt;
&lt;/body&gt;
</pre>
<h3>Using EGMap 2.0 Extension</h3>
<p>Finally, we are going to use EGMap 2.0 extension to automate the rest of the tasks to render our map.</p>
<pre class="brush: php; title: ; notranslate">
Yii::import('ext.gmaps.*');
// center the map
// wherever you want
$latitude = 39.72098197183251;
$longitude = 2.9115524999999964;
$zoom = 8;
$gMap = new EGMap();
$gMap-&gt;setJsName('map');
$gMap-&gt;width = '100%';
$gMap-&gt;height = '400';
$gMap-&gt;setCenter($latitude, $longitude);
$gMap-&gt;zoom = 8;
$gMap-&gt;addGlobalVariable('geocoder');
$gMap-&gt;addGlobalVariable('centerChangedLast');
$gMap-&gt;addGlobalVariable('reverseGeocodedLast');
$gMap-&gt;addGlobalVariable('currentReversGeocodeResponse');
$gMap-&gt;addEvent(
     new EGMapEvent(
             'zoom_changed',
             'document.getElementById(&quot;zoom_level&quot;).innerHTML = map.getZoom();'));
$gMap-&gt;addEvent(new EGMapEvent('center_changed','centerChanged',false));
$gEvent = new EGMapEvent('dblclick','map.setZoom(map.getZoom() +1)');
$gMap-&gt;appendMapTo('#map_canvas');
$gMap-&gt;renderMap(array(
    'geocoder = new google.maps.Geocoder();',
    $gEvent-&gt;getDomEventJs('crosshair'),
    'reverseGeocodedLast= new Date();',
    'centerChagedLast = new Date();',
    'setInterval(function(){
        if((new Date()).getSeconds() - centerChangedLast.getSeconds() &gt; 1) {
        if(reverseGeocodedLast.getTime() &lt; centerChangedLast.getTime())
          reverseGeocode();
      }
    },1000);',
    'centerChanged();'
));
</pre>
<h3>Important</h3>
<p>If you are going to run this example, please be aware that in order to display it properly in a controller, all of the above have to be the content of a layout, otherwise, if you are using renderPartial (that you can), make sure you force to true the parameter &#8216;processOutput&#8217; of the mentioned function (ie $this-&gt;renderPartial(&#8216;view&#8217;,null,false,true) )</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20A%20Reverse%20Geolocator%20Tool%20with%20EGMap%202.0%20Extension%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F02%2F05%2Fa-reverse-geolocator-tool-with-egmap-2-0-extension%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/02/05/a-reverse-geolocator-tool-with-egmap-2-0-extension/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Paths, Paths, Yii Paths!</title>
		<link>http://www.ramirezcobos.com/2011/01/15/paths-paths-yii-paths/</link>
		<comments>http://www.ramirezcobos.com/2011/01/15/paths-paths-yii-paths/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 12:52:40 +0000</pubDate>
		<dc:creator>Antonio Ramirez</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Yii]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">http://www.ramirezcobos.com/?p=760</guid>
		<description><![CDATA[
Introduction
When we start learning something and we go through some parts, we completely forget about what was a small issue in our way to get where we are. I started talking about things that can be hard to understand if the initial concepts are not well understood. For this reason, even though  [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ramirezcobos.com/2010/10/28/how-to-use-jqueryslidemenu-with-yii%e2%80%99s-cmenu/yii/" rel="attachment wp-att-612"><img src="http://www.ramirezcobos.com/wp-content/uploads/2010/10/Yii.png" alt="Yii Framework" title="Yii Framework" width="160" height="160" class="alignright size-full wp-image-612" /></a><br />
<h3>Introduction</h3>
<p>When we start learning something and we go through some parts, we completely forget about what was a small issue in our way to get where we are. I started talking about things that can be hard to understand if the initial concepts are not well understood. For this reason, even though for some this small tutorials are too basic, I would like to post them every now and then  to help newcomers to better understand the basic concepts of the articles.</p>
<h3>Paths</h3>
<blockquote><p>Before, you continue with this article, I assume that you have read the fundamentals of <a href="http://www.yiiframework.com/doc/guide/1.1/en/basics.namespace" target="_blank">Path Aliasing and Namespaces</a> from the <a href="http://www.yiiframework.com/doc/guide/1.1/en" target="_self">Definitive Guide of Yii</a></p></blockquote>
<p>We are going to talk about paths and before we start, we should first explain how Yii creates its folder structure after you use its <a href="http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app">yiic tool</a>. This is how it looks and the definitions of the folders (assuming you have created an application called testweb):</p>
<pre>testweb/             containing your web
   assets/           containing published resource files
   css/              containing CSS files
   images/           containing image files
   themes/           containing application themes
   protected/        containing protected application files
      commands/      containing customized 'yiic' commands
         shell/      containing customized 'yiic shell' commands
      components/    containing reusable user components authentication
      config/        containing configuration files
      controllers/   containing controller class files
      data/          containing the sample database
      extensions/    containing third-party extensions
      messages/      containing translated messages
      models/        containing model class files
      runtime/       containing temporarily generated files
      tests/         containing test scripts
      views/         containing controller view and layout files
         layouts/    containing layout view files
         site/       containing view files for the 'site' controller
            pages/   containing "static" pages</pre>
<p>Quite impressive, Yii MVC folder structure is very well created and for simple projects, we probably don&#8217;t need to change it, but if we wish to do it, or we create some widgets or portlets or components or whatever, and those need to access different folder locations in our application, Yii <strong>paths</strong> related functions come to resue:</p>
<ol>
<li><a href="http://www.yiiframework.com/doc/api/1.1/YiiBase#getPathOfAlias-detail" target="_blank">getPathOfAlias</a></li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/YiiBase#setPathOfAlias-detail" target="_blank">setPathOfAlias</a></li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/YiiBase#import-detail" target="_blank">import</a></li>
</ol>
<h3><strong>So, tell me, how do they work</strong></h3>
<p>A path alias is &#8216;nickname&#8217; that we give to a folder in our Web project. Yii comes with five of them already established.</p>
<ul>
<li><code>system</code>: refers to the Yii framework directory;</li>
<li><code>zii</code>: refers to the <a href="http://www.yiiframework.com/doc/guide/1.1/en/extension.use#zii-extensions">Zii library</a> directory;</li>
<li><code>application</code>: refers to the application&#8217;s <a href="http://www.yiiframework.com/doc/guide/1.1/en/basics.application#application-base-directory">base directory</a>;</li>
<li><code>webroot</code>: refers to the directory containing the <a href="http://www.yiiframework.com/doc/guide/1.1/en/basics.entry">entry script</a> file. This alias has been available since version 1.0.3.</li>
<li><code>ext</code>: refers to the directory containing all third-party <a href="http://www.yiiframework.com/doc/guide/1.1/en/extension.overview">extensions</a>. This alias has been available since version 1.0.8.</li>
</ul>
<p>So, in our example above, these are the correspondent translations:</p>
<p><strong>Yii::getPathOfAlias(&#8216;webroot.images&#8217;)</strong> is equal to the translated images folder path on your computer or server (ie. windows: C:\mywebserverpath\testweb\images, linux: /usr/web/www/testweb/images). I do use this feature to save images or folders on a folder  when I develop CMS for my clients. Here is an example:</p>
<pre class="brush: php; title: ; notranslate">
$picture_file = CUploadedFile::getInstanceByName('Filedata');
//...
//... some validation code here
//...
// create a picture name
$picture_name = Picture::createPictureName($picture_file-&gt;name);
// saving file
// 'othersubfolder' is just an imaginary subfolder under images
$picture_file-&gt;saveAs(
          Yii::getPathOfAlias('webroot.images.othersubfolder') .
          DIRECTORY_SEPARATOR .
         $picture_name );
</pre>
<p>Now, lets imagine that I wish to create a new folder <strong>2010</strong> for my application and it is located very far down on the folder structure and I wish to access it in order to save documents there. Here is the example:</p>
<pre>testweb/
   assets/
   css/
   docs/
      clients/
         2010/
           January/</pre>
<p>To make our life easier, we are going to use <strong>Yii::setPathOfAlias</strong> to provide an alias to the <strong>2010</strong> folder. For the sake of the example we are going to configure it in our index.php file after the creation of our Application:</p>
<pre class="brush: php; title: ; notranslate">
defined('DS') or define('DS',DIRECTORY_SEPARATOR);
Yii::createWebApplication($config)-&amp;gt;run();
Yii::setPathOfAlias('2010',
           dirname($_SERVER['SCRIPT_FILENAME']).DS.
           'docs'.DS.
           'clients'.DS.'2010');
// Now we can access the folder to read and/or write like this:
$pathToDocs = Yii::getPathOfAlias('2010');
</pre>
<p>Remember, than setPathOfAlias doesn&#8217;t normalizes the path and getPathOfAlias do not check for the existence of the folder just check if the alias exist. We need to put special attention to them.</p>
<h3>And what about import?</h3>
<p>I wouldn&#8217;t explain it better than Yii:</p>
<p><em>Using aliases, it is very convenient to include the definition of a class. For example, if we want to include the<a href="http://www.yiiframework.com/doc/api/1.1/CController">CController</a> class, we can call the following:</em></p>
<div>
<pre>Yii::import('system.web.CController');</pre>
</div>
<p><em>The import method differs from include and require in that it is more efficient. The class definition being imported is actually not included until it is referenced for the first time (implemented via PHP autoloading mechanism). Importing the same namespace multiple times is also much faster than include_once and require_once.</em></p>
<p><em>We can also use the following syntax to import a whole directory so that the class files under the directory can be automatically included when needed.</em></p>
<div>
<pre>Yii::import('system.web.*');</pre>
<p><em>Besides <a href="http://www.yiiframework.com/doc/api/1.1/YiiBase#import">import</a>, aliases are also used in many other places to refer to classes. For example, an alias can be passed to <a href="http://www.yiiframework.com/doc/api/1.1/Yii#createComponent">Yii::createComponent()</a> to create an instance of the corresponding class, even if the class file was not included previously.</em></p>
</div>
<h3>Further Reading</h3>
<p>We have covered just a small portion of the great funcionality of Yii. I highly recommend you to also look at the following path related functions:</p>
<ul>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#getBasePath-detail" target="_blank">getBasePath</a> -Returns the root path of the application. Your root URL.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#setBasePath-detail" target="_blank">setBasePath</a> -Sets the root directory of the application. This method can only be invoked at the begin of the constructor.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#getExtensionPath-detail" target="_blank">getExtensionPath</a> &#8211; Returns the root directory that holds all third-party extensions.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#setExtensionPath-detail">setExtensionPath</a> &#8211; Sets the root directory that holds all third-party extensions.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#setRuntimePath-detail" target="_blank">setRuntimePath</a> &#8211; Sets the directory that stores runtime files.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#getRuntimePath-detail" target="_blank">getRuntimePath</a> &#8211; Returns the root directory that stores runtime files</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#getLocaleDataPath-detail" target="_blank">getLocaleDataPath</a> &#8211; Returns the directory that contains the locale data. It defaults to &#8216;framework/i18n/data&#8217;.</li>
<li><a href="http://www.yiiframework.com/doc/api/1.1/CApplication#setLocaleDataPath-detail" target="_blank">setLocaleDataPath</a> &#8211; Sets the directory that contains the locale data.</li>
</ul>
<p>Hope this helps new comers to better understand the concepts working with path Yii way.</p>
<p><center><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7060132287364604";
/* 468x60, creado 16/03/10 */
google_ad_slot = "9029910384";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
</center></p>
<a href="http://twitter.com/?status=RT%20%40%3A%20Paths%2C%20Paths%2C%20Yii%20Paths%21%20-%20El%20Blog%20del%20Antonio%20http%3A%2F%2Fwww.ramirezcobos.com%2F2011%2F01%2F15%2Fpaths-paths-yii-paths%2F" class="tweet-this" ><img src="http://www.ramirezcobos.com/wp-content/plugins/simple-tweet/img/tweet.gif" title="Tweet this!" alt="Tweet this!" />Tweet this!</a>]]></content:encoded>
			<wfw:commentRss>http://www.ramirezcobos.com/2011/01/15/paths-paths-yii-paths/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

<!-- Served from: www.ramirezcobos.com @ 2012-02-06 17:43:12 by W3 Total Cache -->
