Posts tagged PHP

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!
Restaurant La Parada del Mar

La Parada del Mar

1

Restaurant La Parada del MarWebsite developed for the Spanish Restaurant La Parada del Mar. Customer wanted to have a very simple and direct webpage where to show information about their services.

Website Features



Tweet this!Tweet this!
Home Page

Real Estate Colonia San Pedro

10

Real Estate Web Application fully developed with Yii Framework.

To visit the site: http://www.mallorcacolonia.com/

Website Features

Web Panel Features

  • The webpanel allows to manage:
  • Web Translations
  • Property Types
  • Properties (Sale, Rent, Inactive) – Gallery – Property Owners
  • Zones
  • Site Languages
  • Inbox

Backend Gallery



Tweet this!Tweet this!
Yii Framework

Yii Learning Guide

2

Yii FrameworkI am a ‘plugged’ person, means that I am constantly connected to the net and being a member of a certain number of social networks and tools (I maybe a weirdo but *no facebook* account) and I am very surprised of the amount of people that are highly interested on Yii and asks information on what is the best way to learn the framework. In order to solve those doubts I would like to put my two cents on this matter by sharing with you what was my learning curve with Yii -this way I do not need to post in every social network I am involved with.

For this post I assume that you know PHP (beginner, intermediate) and some DB skills for whatever the DB Engine you prefer to work with (MySQL, Oracle, etc…)

Yii Learning Guide

When you first arrive to Yii’s website, even though is an amazingly easy to navigate and use Website, you will obviously feel lost and won’t know where to start working with, and this is the most important steps of them all: download and READ its Definitive Guide to Yii. Do not worry if you do not understand some concepts, but you need to read it all, do not let any episode without a look as you will soon understand everything and will get ‘hooked’ by the easiness and magic of Yii. If you prefer not to download it, an online version of the guide is also available. If you are new to MVC, then I also recommend the visit to Larry Ullman’s Learning Yii Series blog.

After the guide, you will have tons of questions to solve and, even though will become a great tool in the future, do not jump immediately on the forum to drop them all. You need to get your hands on a practical example and for that, the demo application of The Yii Blog Tutorial is the perfect playground. It is highly recommended that you have your preferred PHP editor with two projects open: one that is the full demo blog application that comes with the Yii Framework download package, and the practical project that you will create following the tutorial. There are a couple of lines of code that you need to discover in the builded demo application and there are not in the tutorial.

There is also a book, “Agile Web Application Development with Yii1.1 and PHP5“, that takes you step-by-step through the process of using a test-driven development (TDD) approach to develop a real world Web application with Yii, from initial concept through production-readiness. This is another good practical tutorial to follow. If you do buy the book, then I recommend you to subscribe to Yii’s forum and follow this discussion: http://www.yiiframework.com/forum/index.php?/topic/11920-identified-issues/.

If you have reached this far on the article and follow the above steps then you are already amazed of Yii’s power and probably started your first real-world project with the Framework. Real issues and challenges will arise, it is time to find out about Yii’s amazing network of people, register and subscribe to Yii’s forum. Ask and you will be answered, people are so helpful and polite, it is just unreal the response time of this community. If you prefer  to get immediate help, then use Yii’s live IRC chat.

Don’t think that your learning curve has stopped here, to be ‘plugged’ to the network is highly recommended, so ‘plug’ your self to the Wiki. Its articles are written by other fellow programmers, it is a programmers-to-programmers experience, and due to the nature of the people that are part of this network, the Wiki grows day-by-day. This is the reason that I am subscribed to its RSS. You can also stay up to date by following any of the next social networks accounts: TwitterFacebook or LinkedIn

Once you know the ins and outs of the Framework, one great learning resource are the Extensions written by other programmers. Use them in order to easy your tasks and solve your problems but also read at its guts, its code behind. You will be surprised on how much you can learn from that. If you do not understand something within that code, have *always* a browser window or a tab opened with Yii’s Class Reference.

If you are comfortable with PHP, then I also recommend that you look at the code of the Framework. For example, if you wish to display a radio button using CHtml::radioButton look at the function itself too. Lots of forum questions wouldn’t be posted if they follow this simple advice.

Final Words

There are other resources to take into account (resources directly extracted from Yii’s site):

Cheat Sheets

The Yii cheat sheet, created by Sebastián Thierer. This presents commonly used Yii classes, methods and properties in a single printable sheet.

Yii 1.1 validator cheatsheet: created by schmunk. This summarizes all of Yii’s built-in validators in a single printable sheet.

Yii Playground

The Yii Playground is a community-contributed demo application that uses the PHP Yii Framework to show some features of the framework by explicit example. It is great place to see how some of the features work, and learn the code behind them.

Radio Podcasts

Yii Radio Podcasts, created by Imre Mehesz, covers hot topics and recent activities about the Yii framework.

Blogroll

The community-driven wiki page Yii Related Sites is collecting links to sites with useful tips and tutorials related to the Yii Framework.

The most important thing is that, once you get your hands on this amazing framework you get actively involved in the community (Forum, Wiki, Extensions), and share your projects so others can look at Yii’s real power and provide you with positive feedbacks.

I truly hope this article provides you with an easy guidance to get into Yii’s framework.



Tweet this!Tweet this!
Yii Framework

Custom Page Size for CGridView

4

Yii FrameworkThis post is actually something that, after permission granted from a Yii collegue Mike, was posted on Yii forum and I thought that was a *golden hint* too bad not to be shared among people interested on Yii: How to include a custom page size select box on your CGridView.

Step 1

First we need to modify the actionAdmin of the (CRUD) controller we want to include the select box that will change the page size of our CGridView. For the sake of this example, we are going to use the user controller which is created by default with Yii.

//
// page size drop down changed
if (isset($_GET['pageSize'])) {
//
// pageSize will be set on user's state
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
//
// unset the parameter as it
// would interfere with pager
// and repetitive page size change
unset($_GET['pageSize']);
}

Step 2

Now we have to modify the model’s search() function (e.g. model/User.php):

return new CActiveDataProvider(get_class($this),array(
'pagination'=>array(
//
// please check how we get the
// the pageSize from user's state
'pageSize'=> Yii::app()->user->getState('pageSize',
//
// we have previously set defaultPageSize
// on the params section of our main.php config file
Yii::app()->params['defaultPageSize']),
),
'criteria'=>$criteria,
));

Step 3

Finally, we need to change our view (e.g. views/user/admin.php) and we are done:

//
//
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);
// we use header of button column for the drop down
// so change the CButtonColumn in columns array like this:
...
array(
    'class'=>'CButtonColumn',
    'header'=>CHtml::dropDownList('pageSize',
        $pageSize,
        array(20=>20,50=>50,100=>100),
        array(
       //
       // change 'user-grid' to the actual id of your grid!!
        'onchange'=>
        "$.fn.yiiGridView.update('user-grid',{ data:{pageSize: $(this).val() }})",
    )),
),
...

Hope you find this hint as good as I thought it is. As Mike states, this information is to prove how easy is to enhance Yii components if you are not afraid of Javascript.

References

For futher reading please refer to original post.
Mike’s Forum Post

Happyiing!

Tweet this!Tweet this!
Yii Framework

How to create a Yii Behavior

4

Yii FrameworkFirst of all let’s find out what is exactly a behavior in Yii’s language (text extracted from Yii’s Definitive Guide):

A behavior is an object whose methods can be ‘inherited’ by its attached component through the means of collecting functionality instead of specialization (i.e., normal class inheritance). A component can be attached with several behaviors and thus achieve ‘multiple inheritance’.

Behavior classes must implement the [IBehavior] interface. Most behaviors can extend from the CBehavior base class. If a behavior needs to be attached to a model, it may also extend from CModelBehavior or CActiveRecordBehavior which implements additional features specifc for models.

This means that if we require additional features to the models we could extend them by using behaviors and also, that a model could actually implement more than one behavior thus extending endlessly its functionality.

Behaviors is the answer to those who wish to do things that differ from normal use and they need to be shared among other models but not to all of them. What that means? Well, IMHO, I think that if you need a special functionality that is shared among model objects then I suggest that would it better that you create a class that extends from the CActiveRecord and then extend your models from it.

I heard so many times that people wishes to create functions in controllers and we should stick to the MVC approach as it is, and not try to reinvent the wheel with things that come out our creative minds. If you need to do specific actions thing about a controller but if that action involves DB data then work with Models. This is a long discussion that could hold an article by itself; let’s be focus with this article.

Building and Using a Behavior

Our behavior will transform a model into a JSON array and as the Yii guide says, it implements the IBehavior interface as it extends from CBehavior. The code is extracted from my own extension behavior EJsonBehavior, here it is:

//
// EJsonBehavor extends from CBehavior
class EJsonBehavior extends CBehavior{
//
// this property will hold a reference to
// its owner - the model class that will
// have this behavior attached to it
private $owner;
//
// this property will reference the
// relations of the model class -owner
private $relations;
public function toJSON(){
//
// getting a reference to model class
// having this behavior attached to it
$this->owner = $this->getOwner();
//
// making sure it is a CActiveRecord descendant
if (is_subclass_of($this->owner,'CActiveRecord')){
//
// play with it!
//
// get model attributes
$attributes = $this->owner->getAttributes();
//
// if this model has related model classes
// get them attributes
$this->relations 	= $this->getRelated();
//
// structure the to-be-converted JSON
$jsonDataSource = array('jsonDataSource'=>array('attributes'=>$attributes,'relations'=>$this->relations));
//
// return the JSON result
return CJSON::encode($jsonDataSource);
}
return false;
}
//
// returns related model's attributes
private function getRelated()
{
$related = array();
$obj = null;
$md=$this->owner->getMetaData();
foreach($md->relations as $name=>$relation){
$obj = $this->owner->getRelated($name);
$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;
}
return $related;
}
} // end of class

The important thing about the above code is not the funcitonality exposed, converting the model to a JSON array, but how we could get a hold to the behavior’s parent and access all its properties. That means, that by the same technique we could use that reference (owner) to play with the database referred by the object itself (check for example the code of the SLUG behavior).

Attaching the Behavior to a Model

This is the easiest part -yes, it is true, writing behaviors is a pretty easy thing with Yii. One way is the one referred on the wiki, which is the way I use it when I just need the use of a behavior certain times but the way I mostly use them is like this:

//
// This function is in the model
// where we want to attach the
// behavior too
public function behaviors() {
//
// needs to return an array
// of behavior objects
return array(
'EJsonBehavior'=>array(
//
// please check how it says to Yii
// where the class is located
'class'=>'application.behaviors.EJsonBehavior'
),
);
}

In the code above, you see how I tell Yii where the class is located in my applications folder; in this case I say to Yii to look for our behavior in the protected/behaviors folder and inside it there is a file EJsonBehavior.php which holds a behavior with a class name as the name of the file -EJsonBehavior.

Once we have attached the behavior to our model class, to use it is as simple as to call its public methods and/or properties. With our behavior above, we just do:

//
// pfff, so easy...
echo $model->toJSON();

After you have seen how easy is to create behaviors, having a look to the code of the Behaviors list at Yii’s site, will incredibly help your current learning curve. Hope this article has helped you to better understand behaviors.

Tweet this!Tweet this!
Picture-6-300x143

How to use SWFUpload’s Yii Extension

15

I regularly used SWFUpload in my projects to handle multiple file uploads, most of them picture gallery related functions. Just because I am using Yii now I wasn’t going to change that, so I was ready to build my SWFUpload extension in order to continue with my ‘traditional’ way of doing things. One of the lessons learned along these years of programming is  not to reinvent the wheel and first thing I did was searching the Yii extensions repository just to check if anybody has done something like that before; and yes, somebody did: mr ThiagoVidal. That made things easier :)

I made small modifications to the extension as I didn’t like the handlers.js file (is part of the SWFUpload package) to be outside of the extension’s package. I thought that a plug and play extension should be all in one place, so it is easier to use and move around projects. So, for the sake of this example, and if mr ThiagoVidal haven’t updated my modifications, please download the zipped package below.

Installation

Once you download the files, unzip the contents of the package and place all in your applications protected/widgets folder.

How to use

First of all, we need to tweak our index.php file. This is because SWFUpload requirements with a variable named PHPSESSID that is needed for handling file uploads. Due that is a conditional statement I decided to put it in the main file as won’t affect at all the rest of the application.

if (isset($_POST['PHPSESSID']))
{
  $_COOKIE['PHPSESSID'] = $_POST['PHPSESSID'];
}

Now, we are going to construct a view that will handle the uploads. The following example is extracted from one of my projects that most of the CMS calls are done through AJAX and this view is actually displayed via fancybox . In our view, we first configure the SWFUpload widget and afterwards its HTML like this:

SWFUpload

//'use_query_string'=>true,
// Creating the URL that will handle our uploads
// check the parameter at the end
// $uurl = $this->createUrl('picture/upload',array('yourvarname'=>$yourvar));
$uurl = $this->createUrl('picture/upload');
// here is our widget!
$this->widget('widgets.CSwfUpload', array(
// here you include the post params you want the
// upload function to handle when a file is submitted
//  'postParams'=>array('yourvarname'=>$yourvar),
'config'=>array(
    'use_query_string'=>false,
    //Use $this->createUrl method or define yourself
    'upload_url'=> CHtml::normalizeUrl($uurl),
   // This is a workaround to avoid certain
   // issues (check SWFUpload Forums)
   'file_size_limit'=>'2 gb',
   // Allowed file types
   'file_types'=>'*.jpg;*.png;*.gif',
   // File types description (mine spanish)
   'file_types_description'=>'Imagenes',
   // unlimited number of files
   'file_upload_limit'=>0,
   // refer to handlers.js from here below
   'file_queue_error_handler'=>'js:fileQueueError',
   'file_dialog_complete_handler'=>'js:fileDialogComplete',
   'upload_progress_handler'=>'js:uploadProgress',
   'upload_error_handler'=>'js:uploadError',
   'upload_success_handler'=>'js:uploadSuccess',
   'upload_complete_handler'=>'js:uploadComplete',
   // what is our upload target layer?
   'custom_settings'=>array('upload_target'=>'divFileProgressContainer'),
   // where are we going to place the button?
   'button_placeholder_id'=>'swfupload',
   'button_width'=>230,
   'button_height'=>20,
   'button_text'=>'<span class="button">Selecciona las Imagenes (2 MB Max)</span>',
   'button_text_style'=>'.button { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 11pt; text-align: center; }',
   'button_text_top_padding'=>0,
   'button_text_left_padding'=>0,
   'button_window_mode'=>'js:SWFUpload.WINDOW_MODE.TRANSPARENT',
   'button_cursor'=>'js:SWFUpload.CURSOR.HAND',
   ),
  )
);

HTML

<!-- SPANISH sorry -->
<div id="main-content">
<h2>Cargador de Im&aacute;genes</h2>
<p>Haz click en el siguiente boton para cargar las im&aacute;genes de la Propiedad.
El cargador de Im&aacute;genes las cargar&aacute; y redimensionar&aacute; autom&aacute;ticamente.
</p>
<form>
<div class="form">
    <div class="row">
    <div class="swfupload"  style="display: inline; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;">
       <span id="swfupload"></span>
    </div>
    <div id="divFileProgressContainer" style="height: 75px;"></div>
    <div id="thumbnails"></div>
    </div>
</div>
</form>
</div>

Ok, now that we have our view (and placed in its correspondent folder within your application’s protected/view folder), we need to have a controller that handles the file uploads of SWFUpload and the rendering of the view. I have one controller named picture that renders the view on an uploader action and handles the uploads through its upload action. One thing very important is that we remove accessControl’s filters for our Upload action, otherwise our code just won’t work at all. Please, remember to set the rules() of your controller for each action respectively, I have them set only accessible by the administrator in my CMS. Here is the code:

//
// lets remove access control filters
// for our upload action
public function filters()
{
   return array(
     'accessControl -upload',
    );
}
public function actionUploader(){
// In case you wish to  post a variable each time a file
// is uploaded. This is good if a picture is related to an object
// and you wish to pass the ID so to related both picture
// or file to parent.
// $yourvar = 'variabletopost';
// $this->render('uploader',array('yourvar'=>$yourvar));
   $this->render('uploader');
   // In my case is AJAX
   Yii::app()->end();
}
// For the sake of simplicity the following function
// does not have any file validation procedures
// I highly recommend you that you create one
// If you need help, let me know, and I will forward
// mine so you see an example.
public function actionUpload(){
 try{
     // get the file
     $picture_file = CUploadedFile::getInstanceByName('Filedata');
     if(!$picture_file || $picture_file->getHasError()){
	echo 'Error: Documento Invalido';
	Yii::app()->end();
     }
     // remember the post params?
     // $yourvar = Yii::app()->request->getParam('yourvarname');
     $picture_name = $picture_file->name;
     //
     // I normally here I use PhpThumb Library instead of this
     // make sure 'thepathyousavethefile' is a writable path
     $picture_file->saveAs(
         Yii::getPathOfAlias('thepathyousavethefile').
         $picture_name
      );
      // Return the file id to the script
      // This will display the thumbnail of the uploaded file to the view
      echo "FILEID:" . Yii::app()->getBaseUrl() .
         '/thepathyousavethepicture/' .
         $picture_name;
     }
     catch(Exception $e){
	echo 'Error: ' . $e->getMessage();
     }
     Yii::app()->end();
}

Final Words

I would like to remark that the upload action I created above is very simple and some file validations should be applied such as checking their sizes, file types, and so on. I used this approach without problems at all.


http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: SWFUpload for Yii (43.52KB)
added: 06/11/2010
clicks: 629


Tweet this!Tweet this!
Captura de pantalla 2010-11-05 a las 20.05.08

How to use PHPExcel with Yii

4

Trying to learn and help some other programmers to find their solutions on the Yii Forum (I think is a superb way to learn the framework), I was facing one challenge with an external library that a fellow programmer wanted to use -quite good indeed: PHPExcel . And what is PHPExcel?

PHPExcel – OpenXML – Create Excel2007 documents in PHP – Spreadsheet engine

Project providing a set of classes for the PHP programming language, which allow you to write to and read from different file formats, like Excel 2007, PDF, HTML, … This project is built around Microsoft’s OpenXML standard and PHP.

Checkout the Features this class set provides, such as setting spreadsheet meta data (author, title, description, …), multiple worksheets, different fonts and font styles, cell borders, fills, gradients, adding images to your spreadsheet and much, much more!

The Challenge

The fellow programmer (Jack Fiallos) had a problem of using the libraries within Yii. He was surprised that he could easily use the libraries outside of the framework but not within the framework itself. At first we didn’t think about it but suddenly we thought about the autoloading features of Yii and looked into the guts of PHPExcel to find out what was causing the problems.

We were right, PHPExcel has an autoloading feature itself that when a classes is called (i.e. PHPExcel_Shared_ZipStreamWrapper) the first part of the name is actually reflecting the folder’s path where the class is located (i.e. PHPExcel_Shared_ZipStreamWrapper = PHPExcel/Shared_ZipStreamWrapper.php). Please review the following code (extracted from PHPExcel_Autoloader class):

public static function Load($pObjectName){
    if ((class_exists($pObjectName)) || (strpos($pObjectName, 'PHPExcel') === False)) {
       return false;
    }
    // this is the code that shows what I am saying
    $pObjectFilePath =  PHPEXCEL_ROOT.
           str_replace('_',DIRECTORY_SEPARATOR,$pObjectName).'.php';
           if ((file_exists($pObjectFilePath) === false) || (is_readable($pObjectFilePath) === false)) {
		return false;
           }
	require($pObjectFilePath);
}	//	function Load()

Solution

The workaround to this problem (at least the one I know) is by making use of the spl_autoload_register and spl_autoload_unregister PHP’s functions. The following code shows how we got the library working -I assume that you have downloaded the PHPExcel files, unzipped its contents and place them into a phpexcel folder within your application’s protected/extensions folder:

//
// VERY DUMMY TEST CONTROLLER
// FOR THE SAKE OF THE EXAMPLE
// TEST IT AS http : / / <yourapplicationurl> / index.php ? r=test/test
class TestController extends Controller{
     // no layouts here
     public $layout = '';
     public function actionTest()
     {
     //
     // get a reference to the path of PHPExcel classes
     $phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
     // Turn off our amazing library autoload
      spl_autoload_unregister(array('YiiBase','autoload'));
     //
     // making use of our reference, include the main class
     // when we do this, phpExcel has its own autoload registration
     // procedure (PHPExcel_Autoloader::Register();)
    include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
     // Create new PHPExcel object
     $objPHPExcel = new PHPExcel();
     // Set properties
     $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("PDF Test Document")
							 ->setSubject("PDF Test Document")
							 ->setDescription("Test document for PDF, generated using PHP classes.")
							 ->setKeywords("pdf php")
							 ->setCategory("Test result file");
     // Add some data
     $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');
      // Miscellaneous glyphs, UTF-8
     $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
      // Rename sheet
      $objPHPExcel->getActiveSheet()->setTitle('Simple');
      // Set active sheet index to the first sheet, so Excel opens this as the first sheet
     $objPHPExcel->setActiveSheetIndex(0);
      // Redirect output to a client’s web browser (Excel2007)
      header('Content-Type: application/pdf');
      header('Content-Disposition: attachment;filename="01simple.pdf"');
      header('Cache-Control: max-age=0');
      $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
      $objWriter->save('php://output');
       //
       // Once we have finished using the library, give back the
       // power to Yii...
       spl_autoload_register(array('YiiBase','autoload'));
       }
}

Final Words

This post is using PHPExcel external library as an example, but this procedure should be taken into account when we encounter a problem like this. Whenever you find a library that you wish to include in your Yii application, check out its autoloading functions first.



Tweet this!Tweet this!
Yii Framework

How to use jQueryslidemenu with Yii’s CMenu

4

Yii FrameworkYii makes it really easy for all to use their already made objects that automate everything we do. It provides also great power of flexibility and styling but hey, we programmers tend to complicate our lives and push a little more the power of our tools.

This tutorial makes use of the jqueryslidemenu plugin to give us a cool featured slidemenu with just a little bit of effort taking advantage of the way Yii’s CMenu widget renders its items.

Installation of Script

Once we download the plugin we are going to place its contents to their correspondent folders (i.e. styles on the css folder, js files on scripts folder, images -yes you guessed right, the images folder). Nevertheless is up to you how you order the files as long as the images and styles have their image paths correctly set.

Creating the Menu

We are going to use it in our main.php layout file for the sake of the example -and because it is the place where we, most of us, will use it.

First we register the required css and js files for our menu.

// remember that you can actually point to the js files directly if
// your script file is outside of protected/subfolders
$jqueryslidemenupath = Yii::app()
     ->assetManager
     ->publish(Yii::app()->basePath.'/scripts/jqueryslidemenu/');
//Register jQuery, JS and CSS files
Yii::app()
     ->clientScript
     ->registerCoreScript('jquery');
Yii::app()
     ->clientScript
     ->registerCssFile($jqueryslidemenupath.'/jqueryslidemenu.css');
Yii::app()
     ->clientScript
     ->registerScriptFile($jqueryslidemenupath.'/jqueryslidemenu.js');

And finally we create our menu. Please note that our menu is wrapped with a layer ‘div’ and one its classes to jqueryslide menu.

<div id="myslidemenu" class="jqueryslidemenu">
<?php $this->widget('zii.widgets.CMenu',array(
   'items'=>array(
      array('label'=>'Home', 'url'=>array('/site/index')),
      array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
      array('label'=>'Contact', 'url'=>array('/site/contact')),
      array('label'=>'jqSlideMenuTest', 'url'=>array('#'),
        'items'=>array(
           array('label'=>'Home',
                    'url'=>array('/site/index')),
           array('label'=>'About',
                    'url'=>array('/site/page', 'view'=>'about')),
           array('label'=>'Contact',
                    'url'=>array('/site/contact'),
                   'items'=>array(
                      array('label'=>'Home',
                               'url'=>array('/site/index')),
                      array('label'=>'About',
                               'url'=>array('/site/page', 'view'=>'about')),
                      array('label'=>'Contact',
                              'url'=>array('/site/contact'),
                              'items'=>array(
                                   array('label'=>'Home',
                                            'url'=>array('/site/index')),
                                   array('label'=>'About',
                                            'url'=>array('/site/page', 'view'=>'about')),
                                   array('label'=>'Contact',
                                            'url'=>array('/site/contact')),
                       )),
                  )),
              )),
       array('label'=>'Login',
                'url'=>array('/site/login'),
                'visible'=>Yii::app()->user->isGuest),
       array('label'=>'Logout ('.Yii::app()->user->name.')',
                'url'=>array('/site/logout'),
                'visible'=>!Yii::app()->user->isGuest)),
     )); ?>
</div><!-- mainmenu -->

That’s it… quite easy right? You can change its style to suit your ‘design’ needs.

Download Example Files

Our colleague programmer Trejder has compiled an example for all of you to play with it. download files

Just make sure that you have the runtime and assets’s folders permissions to be writable and correct the index.php file Yii path’s to the correct one on your computer.

Tweet this!Tweet this!
Yii Framework

jqPrettyPhoto Extension for Yii

9

I am currently developing a site for a real estate business and it is all built with Yii Framework -I am alone here so I need the best allies for this job :) . During this development I come up with the creation of some cool extensions that I am, of couse, going to share with all of you.

Introducing jqPrettyPhoto

This extension is making use of the grrrreat jQuery plugin called PrettyPhoto. Here is its description in detail:

rettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes. It’s a full blown media lightbox.

It is very easy to setup, yet very flexible if you want to customize it a bit. Plus the script is compatible in every major browser, even IE6.

It also comes with useful APIs so prettyPhoto can be launched from nearly anywhere (yes, that includes Flash)!

How to Install

Unzip the contents of the downloaded package below and copy its contents into your application’s protected/extensions folder.

How to Use

Once we have move the contents of the zipped file into the extensions folder we are ready to go. Use it at your own will into your views like this:

</p>
Yii::import('ext.jqPrettyPhoto');
jqPrettyPhoto::addPretty('.gallery a',jqPrettyPhoto::PRETTY_GALLERY,jqPrettyPhoto::THEME_FACEBOOK);

Wow! That was easy! Please allow me to explain the addPretty function. It comes with three parameters:

1) element/s selector: the JQUERY SELECTOR to the links you want to set pretty photo to. In the example above I had the following on the view’s HTML:

</p>
<p><div class="gallery"><br />
 <a href="URL_TO_IMAGE_TO_OPEN"><img src="URL_TO_IMAGE_TO_SHOW"/></a><br />

2) The second parameter is of the value jqPrettyPhoto::PRETTY_GALLERY or jqPrettyPhoto::PRETTY_SINGLE, which tells the extension whether the selector will be a list of a gallery images or just a single file.

3) The third one is what theme to use -please refer to jqPrettyPhoto.php’s code to see more options on this one.

Download

** If you have problems please use this link.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: jqPrettyPhoto Yii Extension (72.29KB)
added: 21/10/2010
clicks: 1269

Tweet this!Tweet this!
Go to Top