Posts tagged How To

Yii Framework

Using events with CAction classes

2

Yii Framework

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 event in your component adding its method (ie. function onClick($event))
  • Attach it to event handlers (ie. $object->onClick=array($handlerObject,’staticmethod’);)
  • Raising it from your component to call all subscribed handlers (ie. $this->raiseEvent(‘onClick’,$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)

Tip

If we look at the magic method __set of CComponent, we will see that event handlers are actually set like properties.
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.

The CAction class

Lets write a simple CAction class for the example and save it as EMyAction.php:

class EMyAction extends CAction{
	public function onTest($event){
		$this->raiseEvent('onTest', $event);
	}
	public function run() {
		$event = new CEvent($this);
		$this->onTest($event);
	}
}

The Controller

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).

// 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 <controller/action>
		'test'=>array(
			'class'=>'actions.EMyAction',
			'onTest'=>array($this,'eventHandlerMethod')
		)
    );
}

And that’s it, call the controller’s action as you would with any other in your preferred browser to test the results.

Tweet this!Tweet this!
Yii Framework

Avoiding duplicate script download when using CActiveForm on Ajax calls

0

Yii Framework

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’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 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…

The issue

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 “core JS” 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.

The solution

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’ed form contents). For example, on index.php view file:

cs()->registerCoreScript('yiiactiveform');

Now, I assume that you have created your function to display the AJAX’ed active form and its contents are returned by a call to a controller’s action that will partially render a view. This is what we have to do in our action:

// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();

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’t stop the duplication of the script.

And that’s it, everything is working as it should.



Tweet this!Tweet this!
Yii Framework

Custom Autocomplete Display and Value Submission

4

Yii Framework

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 is worth to write.

Requirements

For our example, I want to be able to:

  • Have an autocomplete field in our form
  • Once user selects an item in the dropdown list and fill a hidden box with the id of the selected item for submission

Making the right choice

To setup the autocomplete was a very straight forward operation, but I couldn’t figure out how to get values from a custom JSON response and then fill the correspondent hidden fields.

CAutoComplete does has a way to do it, but I wanted to use CJuiAutoComplete 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.

My Solution

After doing some research I decided to:

  1. extend from CJuiAutoComplete
  2. include the required property for method chain and modify its ‘run’ function
  3. then initialize the newly created property with the javascript functions that handle my custom JSON

Extending from CJuiAutoComplete and make required modifications

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).

class myAutoComplete extends CJuiAutoComplete
{
    /**
     * @var string the chain of method calls that would be appended at the end of the autocomplete constructor.
     * For example, ".result(function(...){})" 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->resolveNameID();
        if(isset($this->htmlOptions['id']))
            $id=$this->htmlOptions['id'];
        else
            $this->htmlOptions['id']=$id;
        if(isset($this->htmlOptions['name']))
            $name=$this->htmlOptions['name'];
        if($this->hasModel())
            echo CHtml::activeTextField($this->model,$this->attribute,$this->htmlOptions);
        else
            echo CHtml::textField($name,$this->value,$this->htmlOptions);
        if($this->sourceUrl!==null)
            $this->options['source']=CHtml::normalizeUrl($this->sourceUrl);
        else
            $this->options['source']=$this->source;
        $options=CJavaScript::encode($this->options);
        $js = "jQuery('#{$id}').autocomplete($options){$this->methodChain};";
        $cs = Yii::app()->getClientScript();
        $cs->registerScript(__CLASS__.'#'.$id, $js);
    }
}

Using our widget

Now that we have our beautiful widget that handles method chain in our Autocomplete, let’s assume a couple of things:

  • We saved our class onto a folder in our application -ie protected/extensions
  • We have a hidden INPUT HTML element with model’s attribute_id
  • We have created an action on our testController named autocomplete that returns a JSON object on the following format:
// This function will echo a JSON object
// on this format:
// [{id:id, name: 'name'}]
public function actionAutocomplete(){
      $res = array();
      $term = Yii::app()->getRequest()->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()->db->createCommand($sql);
         $cmd->bindValue(":name","%".strtolower($term)."%", PDO::PARAM_STR);
         $res = $cmd->queryAll();
      }
      echo CJSON::encode($res);
      Yii::app()->end();
}

We have everything, let’s use our widget in our view:

// REMEMBER, we have a hidden
// input HTML element with model's attribute_id
<?php echo $form->hiddenField($model, 'attribute_id'); ?>
<?php
// ext is a shortcut for application.extensions
$this->widget('ext.myAutoComplete', array(
    'name' => 'test_autocomplete',
    'source' => $this->createUrl('test/autocomplete'),
// attribute_value is a custom property that returns the
// name of our related object -ie return $model->related_model->name
    'value' => $model->isNewRecord ? '': $model->attribute_value,
    'options' => array(
        'minChars'=>3,
        'autoFill'=>false,
        'focus'=> 'js:function( event, ui ) {
            $( "#test_autocomplete" ).val( ui.item.name );
            return false;
        }',
        'select'=>'js:function( event, ui ) {
            $("#'.CHtml::activeId($model,'attribute_id').'")
            .val(ui.item.id);
            return false;
        }'
     ),
    'htmlOptions'=>array('class'=>'input-1', 'autocomplete'=>'off'),
    'methodChain'=>'.data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.name +  "</a>" )
            .appendTo( ul );
    };'
));
?>

Done! Just make sure that when you do submit your form, you get the value from the hidden field instead of the autocomplete element :)

Final Notes

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.

Hope you find this useful.

Cheers

Tweet this!Tweet this!
Yii Framework

Actions code reuse with CAction

3

Introduction

Yii FrameworkWe all know how good ‘gii’ 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.

CAction to the Rescue

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.

Gii provides us normally with the following code on the ‘actionCreate’:

public function actionCreate()
{
   $model=new ModelName;
   // Uncomment the following line if AJAX validation is needed
   // $this->performAjaxValidation($model);
   if(isset($_POST['ModelName']))
   {
       $model->attributes=$_POST['ModelName'];
       if($model->save())
         $this->redirect(array('view','id'=>$model->id));
   }
   $this->render('create',array(
       'model'=>$model,
   ));
}

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.

Step 1 – Creating the Action

For the sake of the example, create the following action and save it on your protected/components/actions folder

class Create extends CAction {
    public function run() {
    $controller = $this->getController();
    // get the Model Name
    $model_class = ucfirst($controller->getId());
    // create the Model
    $model = new $model_class();
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    if (isset($_POST[$model_class])) {
        $model->attributes = $_POST[$model_class];
        if ($model->save())
        $controller->redirect(array('view', 'id' => $model->id));
    }
    $controller->render('create', array(
        'model' => $model,
    ));
    }
}

Step 2 – Declare the action on the Controller

Once we have the action class created, the only thing we need to do is declare it in our controller’s actions function in order to use it.

public function actions(){
   return array(
      'create'=>'application.components.actions.create',
   );
}

After declaring the action we can call it: http://myhost/index.php?r=controller/create, just like any other.

Final Notes

In the example above I have used ‘getController()’ and ‘getId()’ 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:

// 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'=>array(
          'class'=>'application.components.actions.create',
          'model_name'=>'ModelClass',
   );
}



Tweet this!Tweet this!
Overlays

EGMaps 2.0 News: Layers, Polygons and Rectangles

3

Overlays

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’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 date:

  • Polygons (committer Matthias Kay)
  • Rectangles
  • Circles
  • Bicycling Layer
  • Traffic Layer
  • Panoramio Layer

Polygon Example

Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->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->addPolygon($polygon);
$gMap->centerOnPolygons();
$gMap->zoomOnPolygons(0.1);
$gMap->renderMap(array(),'en','ES');

Circle and Rectangle Example

Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->setCenter(34.04924594193164, -118.24104309082031);
$circle = new EGMapCircle(new EGMapCoord(34.04924594193164, -118.24104309082031));
$circle->radius = 300000;
// we can even attach info windows to the overlay!
$circle->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a circlel!'));
$gMap->addCircle($circle);
$bounds = new EGMapBounds(new EGMapCoord(25.774252, -80.190262),new EGMapCoord(32.321384, -64.75737) );
$rec = new EGMapRectangle($bounds);
$rec->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a rectangle!'));
$gMap->addRectangle($rec);
$gMap->renderMap(array(),'en','ES');

Panoramio Layer Example

$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->setCenter(34.04924594193164, -118.24104309082031);
// we can also use the same way TRAFFIC and BICYCLING layers
$gMap->setLayer(new EGMapLayer(EGMapLayer::PANORAMIO));
$gMap->renderMap(array(),'en','ES');

The extension has also been updated its reverse geocoding (committer Say_Ten).

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’s repository. The extension will be updated when we reach the following goals:

  • Elevation Paths
  • Polylines
  • Ground Overlays
  • Animations
  • Map Styling

 

 

Tweet this!Tweet this!
Yii Framework

How to use a Widget as an Action Provider

2

Yii FrameworkAt 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 the solution and this is article is to show you exactly how this is done.

Why would I need an action provider?

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 you just need a line of code to import all of its actions.

First Step: Create your Action

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 getData.php on our protected/components/actions folder.

<?php
class getData extends CAction{
	public function run(){
		echo 'HELLO WORLD';
	}
}

Second Step: configure the Widget

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 static method actions(). As you will see on the following code, we name the action as GetData and that is the action that will be called in our route. We are going to save the following widget in our protected/components/ folder with the name testProvider.php.

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'=>'application.components.actions.getData',
		);
	}
}

Step 3: Configure our Controller

Finally we set our controller’s actions() function to point to our actions provider.

// 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.'=>'application.components.testProvider',
	);
}

Now we can call the action as controllerID/actionPrefix.actionID

index.php?site/test.GetData


Agile Web Application Development with Yii 1.1 and PHP5



Tweet this!Tweet this!
Sidebar marker event trigger

A sidebar marker trigger with EGMap 2.0

0


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 capable of creating that without the need of more ‘library tweaking’.

HTML and Styling

First of all we are going to write the CSS and the HTML that will ‘mimic’ 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).

<style>
#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;
  }
 </style>
</head>
<script>
// 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);
}
</script>
<body>
<!-- the side menu container -->
<ul id="sideContainer" style></ul>
<!-- we are going to render the map here -->
<div id="mapContainer"></div>

Creating the Map

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.

// array holding a reference to all the markers
// that will be rendered to the Map
$markers = array();
$gMap = new EGMap();
$gMap->zoom = 10;
$gMap->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' => 'Marker With Label'));
// attach info window
$marker->addHtmlInfoWindow($info_window_b);
// add to map
$gMap->addMarker($marker);
// add to array
$markers[] = $marker;
// repeat process with second
$marker = new EGMapMarker(39.721089311812094, 2.81165944519042, array('title' => 'Marker With Label'));
$marker->addHtmlInfoWindow($info_window_b);
$gMap->addMarker($marker);
$markers[] = $marker;
// tell the map we want to render it
// to a specific layer
$gMap->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->getJsName().');'.PHP_EOL;
}
// now render map and pass the afterInit code
$gMap->renderMap($afterInit);

Final Words

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.

Hope this example helps you guys to better understand the flexibility of this extension. Thanks all for using it.



Tweet this!Tweet this!
Reverse-geolocator-EGMap-Yii

A Reverse Geolocator Tool with EGMap 2.0 Extension

1

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 won’t styled as the example picture displayed, which is the tool I created for a project I am working now, but don’t you worry as this article will provide you with the scripts and routines to create your own.

Write the following style on the HEAD section of your HTML page:

<style>
  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;
}
</style>

Now, some Javascript functions that will allow us to get the information from the map

<script type="text/javascript">
  //
  // 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("address").value;
    geocoder.geocode({
      'address': address,
      'partialmatch': true}, geocodeResult);
  }
  function geocodeResult(results, status) {
    if (status == 'OK' && results.length > 0) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert("Geocode was not successful for the following reason: " + 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 + '<br>' + 'address: <br>' + addr;
    }
    var infowindow = new google.maps.InfoWindow({ content: text });
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
  }
</script>

Our HTML on this example will be the following one:

<body style="background:white">
<div class="form">
Find by address:
 <input type="text" id="address" style="width:300px"/>
 <button type="button" class="small"onclick="geocode()">Go to Address</button>
  <ul>
     <li>Lat/Lng:&nbsp;<span id="latlng"></span></li>
     <li>Address:&nbsp;<span id="formatedAddress"></span></li>
     <li>Zoom Level:&nbsp;<span id="zoom_level"><?php echo $zoom;?></span></li>
 </ul>
</div>
<div id="map">
    <div id="map_canvas" style="width:100%; height:400px"></div>
    <div id="crosshair"></div>
</div>
<div style="overflow:hidden;width:100%;text-align:right">
<button type="button" class="small" onclick="setLatLngToClass()">Set Latitude & Longitude</button>
<button type="button" class="small" onclick="addMarkerAtCenter()">Add Marker at Center</button>
</div>
<hr>
Latitude: <input id="test_latitude" value=""/> Longitude: <input id="test_longitude" value=""/>
</hr>
</body>

Using EGMap 2.0 Extension

Finally, we are going to use EGMap 2.0 extension to automate the rest of the tasks to render our map.

Yii::import('ext.gmaps.*');
// center the map
// wherever you want
$latitude = 39.72098197183251;
$longitude = 2.9115524999999964;
$zoom = 8;
$gMap = new EGMap();
$gMap->setJsName('map');
$gMap->width = '100%';
$gMap->height = '400';
$gMap->setCenter($latitude, $longitude);
$gMap->zoom = 8;
$gMap->addGlobalVariable('geocoder');
$gMap->addGlobalVariable('centerChangedLast');
$gMap->addGlobalVariable('reverseGeocodedLast');
$gMap->addGlobalVariable('currentReversGeocodeResponse');
$gMap->addEvent(
     new EGMapEvent(
             'zoom_changed',
             'document.getElementById("zoom_level").innerHTML = map.getZoom();'));
$gMap->addEvent(new EGMapEvent('center_changed','centerChanged',false));
$gEvent = new EGMapEvent('dblclick','map.setZoom(map.getZoom() +1)');
$gMap->appendMapTo('#map_canvas');
$gMap->renderMap(array(
    'geocoder = new google.maps.Geocoder();',
    $gEvent->getDomEventJs('crosshair'),
    'reverseGeocodedLast= new Date();',
    'centerChagedLast = new Date();',
    'setInterval(function(){
        if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
        if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
          reverseGeocode();
      }
    },1000);',
    'centerChanged();'
));

Important

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 ‘processOutput’ of the mentioned function (ie $this->renderPartial(‘view’,null,false,true) )



Tweet this!Tweet this!
Yii Framework

EFeed Universal RSS Feed Writer For Yii

0

Yii Framework

Introduction

Required for one of my projects, I decided to develop my own Yii extension to create RSS Feeds. I knew there is already one but I wanted something easier to use than that. This is why I came up with EFeed Extension. This extension supports RSS 1.0, RSS 2.0, and ATOM 1.0 standards.

How to Use

I assume that you have downloaded the extension and place it on your protected/extensions folder.

RSS 1.0 Example

Yii::import('ext.feed.*');
// specify feed type
$feed = new EFeed(EFeed::RSS1);
$feed->title = 'Testing the RSS 1 EFeed class';
$feed->link = 'http://www.ramirezcobos.com';
$feed->description = 'This is test of creating a RSS 1.0 feed by Universal Feed Writer';
$feed->RSS1ChannelAbout = 'http://www.ramirezcobos.com/about';
// create our item
$item = $feed->createNewItem();
$item->title = 'The first feed';
$item->link = 'http://www.yiiframework.com';
$item->date = time();
$item->description = 'Amaz-ii-ng <b>Yii Framework</b>';
$item->addTag('dc:subject', 'Subject Testing');
 // add it to the feed
$feed->addItem($item);
$feed->generateFeed();

As you can see in the example above, we just need to create items and add them to the feed. The example could be easily modified to add items extracted from a database and add them to the Feed in a loop.

RSS 2.0 Example

Yii::import('ext.feed.*');
// RSS 2.0 is the default type
$feed = new EFeed();
$feed->title= 'Testing RSS 2.0 EFeed class';
$feed->description = 'This is test of creating a RSS 2.0 Feed';
$feed->setImage(
'Testing the EFeed class',
'http://www.ramirezcobos.com',
'http://www.yiiframework.com/forum/uploads/profile/photo-7106.jpg');
$feed->addChannelTag('language', 'en-us');
$feed->addChannelTag('pubDate', date(DATE_RSS, time()));
$item = $feed->createNewItem();
$item->title = "first Feed";
$item->link = "http://www.yahoo.com";
$item->date = time();
$item->description = 'This is test of adding ' .
          'CDATA Encoded description <b>EFeed Extension</b>';
// this is just a test!!
$item->setEncloser(
      'http://www.tester.com',
     '1283629', 'audio/mpeg');
$item->addTag(
     'author',
     'thisisnot@myemail.com (Antonio Ramirez)');
$item->addTag(
     'guid',
     'http://www.ramirezcobos.com',
     array('isPermaLink'=>'true'));
$feed->addItem($item);
$feed->generateFeed();

ATOM 1.0 Example

Yii::import('ext.feed.*');
$feed = new EFeed(EFeed::ATOM);
// IMPORTANT : No need to add id for feed or channel.
// It will be automatically created from link.
$feed->title = 'Testing the ATOM RSS EFeed class';
$feed->link = 'http://www.ramirezcobos.com';
$feed->addChannelTag('updated', date(DATE_ATOM, time()));
$feed->addChannelTag('author', array('name'=>'Antonio Ramirez Cobos'));
$item = $feed->createNewItem();
$item->title = 'The first Feed';
$item->link  = 'http://www.ramirezcobos.com';
// we can also insert well formatted date strings
$item->date ='2010/24/12';
$item->description = 'Test of CDATA Encoded description <b>EFeed Extension</b>';
$feed->addItem($item);
$feed->generateFeed();

Download

To download the extension go to Yii’s extension repository. Hope this little piece of code can help your project needs somehow.

Tweet this!Tweet this!
Yii Framework

How to maintain pages on CGridView

2

Yii Framework

Introduction

Lots of Yii forum members have ask how to return to current navigated page on a CGridView after a user has clicked the update or create button. Meaning that if I am in page number 4 of our Grid and we have clicked on the ‘edit’ button, how, and after I clicked the submit button return to the page number 4 as our Grid was?

Through this small tutorial on how to get current page parameter, you will learn how to do exactly that. At least I hope so.

Bit of analysis

If you check at the parameters of the Yii pagination classes you will see that the parameter name of the pagination is on the format of: Modelname_page. So, if we are at our NewsController admin page, we will surely see the pagination as URL?&News_page=2 for example.  Now that we know that we are going to tweak a bit our code to accomplish what we want.

Modifying CButtonColumn

CButtonColumn is the class that takes care of the rendering of our edition buttons (view, update, delete), we are going to modify its buttons URL. How to do it? Well, as I always said, it is really good to look at the guts of Yii framework; if we check the CButtonColumn class code we will see that this class has three properties that we can set: viewButtonUrl, updateButtonUrl and deleteButtonUrl. A closer look to these variables we see:

public $viewButtonUrl='Yii::app()->controller->createUrl("view",array("id"=>$data->primaryKey))';
public $updateButtonUrl='Yii::app()->controller->createUrl("update",array("id"=>$data->primaryKey))';
public $deleteButtonUrl='Yii::app()->controller->createUrl("delete",array("id"=>$data->primaryKey))';

These variables have PHP code that is afterwards evaluated in a very smart way. So, as you probably know by now, we need to modify that code in the view where we render the grid to include our new links, the ones that will include the current page parameter for our Grid.

// setting up the class
$buttons = array('class'=>'CButtonColumn');
// do we have a News_page parameter?
$page = Yii::app()->getRequest()->getParam('News_page',false);
// if yes, modify the link
// IMPORTANT
// for this example I assume that you have
// and update, view and delete actions!
if( $page ){
	foreach(array('view','update','delete') as $id){
		$buttons[$id.'ButtonUrl'] = 'Yii::app()->controller->createUrl("'.$id.'",array("id"=>$data->primaryKey,"News_page"=>'.$page.'));';
	}
}
$this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'news-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		array(
		'name'=>'id',
		'filter'=>false
		),
		'title',
		'sender',
		array(
			'name'=>'datetime_sent',
			'type'=>'datetime',
			'filter'=>false,
		),
		// HERE WE PLACE OUR NEW BUTTONS
		$buttons,
	),
));

Exercise

Now our edition buttons will hold also the current page parameter of our News model. That means that when we render the corresponding views for viewing, editing or even calling actionDelete of our controller, we will also render that parameter.

I think that it could be a good exercise for you to find out how deal with that parameter to return to the page you were after editing your model. I will give you two quick tips:

On my _Form.php view

if(getParam('Brand_page')){
	echo CHtml::hiddenField('Brand_page',getParam('Brand_page'));
}

On my actionUpdate in NewsController

public function actionUpdate($id)
{
	$model=$this->loadModel($id);
	if(isset($_POST['News']))
	{
		$model->attributes=$_POST['News'];
                $page = Yii::app()->getRequest()->getParam('News_page',false);
                $params = $page? array('News_page'=>$page) : array();
		if($model->save()){
                        // redirecting to admin.php view where our grid is
			$route = $this->createUrl('admin',$params);
			$this->redirect($route,true);
		}
	}
	$this->renderPartial('_form',array(
		'model'=>$model,
	));
}

Further Reading

Quick tip about pagination params

Using CButtonColumn to customize buttons in CGridView



Tweet this!Tweet this!
Go to Top