How To
Small tips and tutos
Using events with CAction classes
2Introduction
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!
Avoiding duplicate script download when using CActiveForm on Ajax calls
0Introduction
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!
Custom Autocomplete Display and Value Submission
4Introduction
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:
- extend from CJuiAutoComplete
- include the required property for method chain and modify its ‘run’ function
- 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!
Implementing a User Level Access System
2I 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’s table named, yep you guessed, level
b. Create an object ‘LevelLookUp’ that will tell us who is who on this system
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=>'Member',
self::ADMIN=>'Administrator');
}
}
c.Modifying UserIdentity so we can store the user Model id on authentication, as CWebUser’s default id is set to the user Model’s username:
class UserIdentity extends CUserIdentity
{
private $_id;
/**
* Authenticates a user.
* @return boolean whether authentication succeeds.
*/
public function authenticate()
{
$username = strtolower($this->username);
// from database... change to suite your authentication criteria
$user = User::model()->find('LOWER(username)=?', array($username));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else{
$this->_id = $user->id;
$this->username = $user->username;
$this->errorCode = self::ERROR_NONE;
}
return $this->errorCode == self::ERROR_NONE;
}
public function getId()
{
return $this->_id;
}
}
d. Modify CWebUser’s application in order to hold the ‘level’ 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’s configuration file.
class EWebUser extends CWebUser{
protected $_model;
function isAdmin(){
$user = $this->loadUser();
if ($user)
return $user->level==LevelLookUp::ADMIN;
return false;
}
// Load user model.
protected function loadUser()
{
if ( $this->_model === null ) {
$this->_model = User::model()->findByPk( $this->id );
}
return $this->_model;
}
}
e. Modify our main.php config file (this file is in protected/config folder)
// go to the 'user' section
// application components
'components'=>array(
'user'=>array(
// There you go, use our 'extended' version
'class'=>'application.components.EWebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
Step 2: Putting everything together
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:
// for normal content
if(Yii::app()->user->isAdmin())
echo 'Is administrator';
// for CMenus
$this->widget('zii.widgets.CMenu',array(
array('label'=>'Categories',
'url'=>array('/category/index'),
'visible'=>(Yii::app()->user->isAdmin()),
//... More stuff
//...
// for data chuncks
<?php if(Yii::app()->user->isAdmin():?>
<b>My HTML</b>
<?php endif;?>
// for access rules
return array(
array('allow',
'actions'=>array('create','delete','update'),
'expression'=>'$user->isAdmin()'
),
// ...
Tweet this!
Actions code reuse with CAction
3Introduction
We 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!
EGMaps 2.0 News: Layers, Polygons and Rectangles
3The 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!
How to use a Widget as an Action Provider
2
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 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!
A sidebar marker trigger with EGMap 2.0
0Introduction
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!
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: <span id="latlng"></span></li>
<li>Address: <span id="formatedAddress"></span></li>
<li>Zoom Level: <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!
Paths, Paths, Yii Paths!
8Introduction
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.
Paths
Before, you continue with this article, I assume that you have read the fundamentals of Path Aliasing and Namespaces from the Definitive Guide of Yii
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 yiic tool. This is how it looks and the definitions of the folders (assuming you have created an application called testweb):
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
Quite impressive, Yii MVC folder structure is very well created and for simple projects, we probably don’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 paths related functions come to resue:
So, tell me, how do they work
A path alias is ‘nickname’ that we give to a folder in our Web project. Yii comes with five of them already established.
system: refers to the Yii framework directory;zii: refers to the Zii library directory;application: refers to the application’s base directory;webroot: refers to the directory containing the entry script file. This alias has been available since version 1.0.3.ext: refers to the directory containing all third-party extensions. This alias has been available since version 1.0.8.
So, in our example above, these are the correspondent translations:
Yii::getPathOfAlias(‘webroot.images’) 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:
$picture_file = CUploadedFile::getInstanceByName('Filedata');
//...
//... some validation code here
//...
// create a picture name
$picture_name = Picture::createPictureName($picture_file->name);
// saving file
// 'othersubfolder' is just an imaginary subfolder under images
$picture_file->saveAs(
Yii::getPathOfAlias('webroot.images.othersubfolder') .
DIRECTORY_SEPARATOR .
$picture_name );
Now, lets imagine that I wish to create a new folder 2010 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:
testweb/
assets/
css/
docs/
clients/
2010/
January/
To make our life easier, we are going to use Yii::setPathOfAlias to provide an alias to the 2010 folder. For the sake of the example we are going to configure it in our index.php file after the creation of our Application:
defined('DS') or define('DS',DIRECTORY_SEPARATOR);
Yii::createWebApplication($config)->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');
Remember, than setPathOfAlias doesn’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.
And what about import?
I wouldn’t explain it better than Yii:
Using aliases, it is very convenient to include the definition of a class. For example, if we want to include theCController class, we can call the following:
Yii::import('system.web.CController');
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.
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.
Yii::import('system.web.*');
Besides import, aliases are also used in many other places to refer to classes. For example, an alias can be passed to Yii::createComponent() to create an instance of the corresponding class, even if the class file was not included previously.
Further Reading
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:
- getBasePath -Returns the root path of the application. Your root URL.
- setBasePath -Sets the root directory of the application. This method can only be invoked at the begin of the constructor.
- getExtensionPath – Returns the root directory that holds all third-party extensions.
- setExtensionPath – Sets the root directory that holds all third-party extensions.
- setRuntimePath – Sets the directory that stores runtime files.
- getRuntimePath – Returns the root directory that stores runtime files
- getLocaleDataPath – Returns the directory that contains the locale data. It defaults to ‘framework/i18n/data’.
- setLocaleDataPath – Sets the directory that contains the locale data.
Hope this helps new comers to better understand the concepts working with path Yii way.
Tweet this! 
