insert multiple record without loop-createMultipleInsertCommand

If you are developing any big application or we say a Product or ERP then database operation is very very important thing. Yii is very good for CRUD operation. It use save() function for inserting data in database. But when we deal with multiple data to insert at a time then save method and loop is not a good solution. It is very time consuming which degrade performance of application.

So Yii provides createMultipleInsertCommand method. This method could be used to achieve better performance during insertion of the large amount of data into the database tables.

//only for 1.1.14
$command=$builder->createMultipleInsertCommand('tbl_post', array( 
array('title' => 'record 1', 'text' => 'text1'),  
array('title' => 'record 2', 'text' => 'text2')));

So for this method we have to just create data array using loop. Then just execute the command.

Giix Controller with JToggleColumn

Hello If you are using JToggleColumn extension with GxController then the loadModel syntax look like following:

$this->loadModel($id, ‘ModelName’),

So if we want to use JToggleColumn extension following changes needed in extension so we can dynamically use toggle button.

changes in JToggleColumn.php

1. declare public variable called

public $model_name = null;

2. put following code in init() function for exception

 if ($this->model_name === null)
            throw new CException(Yii::t(‘toggle_column’, ‘Model attribute (“model_name”) must be specified for CToggleColumn.’));
 3. put following code in initDefaultButtons() function

$this->toggle_button = array(
                ‘url’ => ‘Yii::app()->controller->createUrl(“‘ . $this->action . ‘”,array(“id”=>$data->primaryKey,”attribute”=>”‘ . $this->name . ‘”,”model_name”=>”‘.$this->model_name.'”))’,
                ‘options’ => array(‘class’ => $this->name . ‘_toggle’),

changes in ToggleAction.php

public function run($id,$attribute,$model_name) {
            // we only allow deletion via POST request
            $model = $this->controller->loadModel($id,$model_name);
            $model->$attribute = ($model->$attribute==0)?1:0;
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
                $this->redirect(isset($_POST[‘returnUrl’]) ? $_POST[‘returnUrl’] : array(‘admin’));
        throw new CHttpException(400,’Invalid request. Please do not repeat this request again.’);

This is Done..

If you want to put togglebutton in gridview this the column code look like following…

                    ‘name’=>’active’, // boolean model attribute (tinyint(1) with values 0 or 1)
                    ‘model_name’=>’ModelName’,             //here is my model name so click on button change done in table related this model
                    ‘filter’ => array(‘1’ => ‘Yes’,’0′ => ‘No’), // filter
            ‘action’=>’toggle’, // other action, default is ‘toggle’ action
            ‘checkedButtonLabel’=>Yii::app()->baseUrl.’/images/checked.png’, // tooltip


So by this changes you can dynamically toggle the column value..


Interview Questions for Yii

What is Yii Framework?

=>Yii is a high-performance component-based PHP framework best for Web 2.0 development.

What Yii is so FAST?

=> Yii is so much faster because it is using the lazy loading technique extensively. For example, it does not include a class file until the class is used for the first time; and it does not create an object until the object is accessed for the first time. Other frameworks suffer from the performance hit because they would enable a functionality (e.g. DB connection, user session) no matter it is used or not during a request.

Can you Remember what is directory structure when you downloaded Yii?

params-local.php *


main-local.php *
params-local.php *
yiic.php *
main-local.php *
params-local.php *

index.php *

What is the first file that gets loaded when you run a application using Yii?   


What is model,view,controller?                                                                     
=> Models represent the underlying data structure of a Web application. Models are often shared among different sub-applications of a Web application. For example, a LoginForm model may be used by both the front end and the back end of an application; a News model may be used by the console commands, Web APIs, and the front/back end of an application. Therefore, models
·         should contain properties to represent specific data;
·         should contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;
·         may contain code for manipulating data. For example, a SearchForm model, besides representing the search input data, may contain a search method to implement the actual search.
=> Views are responsible for presenting models in the format that end users desire. In general, views
·         should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;
·         should avoid containing code that performs explicit DB queries. Such code is better placed in models.
·         should avoid direct access to $_GET, $_POST, or other similar variables that represent the end user request. This is the controller’s job. The view should be focused on the display and layout of the data provided to it by the controller and/or model, but not attempting to access request variables or the database directly.
·         may access properties and methods of controllers and models directly. However, this should be done only for the purpose of presentation.
=>Controllers are the glue that binds models, views and other components together into a runnable application. Controllers are responsible for dealing directly with end user requests. Therefore, controllers
·         may access $_GET, $_POST and other PHP variables that represent user requests;
·         may create model instances and manage their life cycles. For example, in a typical model update action, the controller may first create the model instance; then populate the model with the user input from$_POST; after saving the model successfully, the controller may redirect the user browser to the model detail page. Note that the actual implementation of saving a model should be located in the model instead of the controller.
·         should avoid containing embedded SQL statements, which are better kept in models.
·         should avoid containing any HTML or any other presentational markup. This is better kept in views.


What is the naming convention inYii?                                                        
=> You can define table prefix when using Gii. In your case you need to set it to tbl_. Then it should  generate UserController instead of TblUserController.
=> The Yii Framework employs a class naming convention whereby the names of the classes directly map to the directories in which they are stored. The root level directory of the Yii Framework is the “framework/” directory, under which all classes are stored hierarchically.
Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged. Dot (.) is only permitted in place of the path separator.

What is the component,helper and why are they used,is there other way we can do same thing,what is better?

=> A component is an independent piece of code written for specific task that can be used by calling in controllers (example : email component), helper is used for helping yii in rendering the data to be shown to user with views, these only adds to modularity in code otherwise same coding can be implemented in controllers.

How do you proceed when you have to use Yii for any application?
=> take the framework either from Yii site or if you have changed according to your needs start from there. Proceed with basic software engg. concepts as requirement gathering etc..

This is a basic Understanding Concept in yii
1.    Yii-based apps are driven by data logic. When I build an app, I always start by making sure that my database schemes are well-designed and optimised to fit the business flow of the app. Therefore, my codes are automatically generated based on my database design. And, yes…
2.    … Yii can generate the whole shebang of PHP codes for you automatically! Just define which database you want to use, and with a few clicks it will create a CRUD (create-read-update-delete) app for you. It looks so cute, I tell you! Speaking of automatic…
3.    … Yii can generate a skeleton app for you automatically. This skeleton app include a view page, a login page, contact page and basic navigation, all wrapped within a completely organized folder tree based on the standard MVC programming model.
4.    The extensive choice of Yii functions makes sense. As a self-taught web programmer, I was able to map out its functions to all of the RESPONSE and REQUEST tasks I most often use when building webapps within a matter of minutes. It also doesn’t hurt that the Yii community has kindly provided cheat sheets for the functions so that I can do a quick reference when I need to.
5.    The Definitive Guide to Yii document that comes with the Yii install is actually quite easy to go through, at least for me. I don’t know why, though. I thought CakePHP docs were more user-friendly and attractive, but surprisingly I was able to go through Yii documentation and tutorial in just two hours and not get cross-eyed by the end of it.
6.    Yii uses MySQL and SQLite as its choice database types. Of course, you can run any other type of databases as long as you have its PDO enabled in your php.ini file. I develop using MySQL most of the time, but my fondness for SQLite is increasing, due to the fact that SQLite is so darn lightweight and easy to use.
7.    Yii is integrated with jQuery, which means that many of the necessary validation functions I use can easily be plugged within the Yii function calls itself, which is usually only a line of code or two.
8.    Yii is open-source, and it’s free. Open-source products turn me on.

What is the first function that gets loaded from a controller?               
=> index

 what is habtm?                                                                                                 
=>has and belongs to many is a kind of associations that can be defined in models for retrieving associated data across different entities.

11. How can we use ajax in Yii?                                                                                             
=>by calling ajax helper and then using it in controller for rendering.

12.If you have to validate a registrations module for a user, what all can be possible ways, which one is the best?
=>can be done on submission in controller, or using javascript/ajax while user is still filling the data. Second option is better.

13. can you list some database related functions in Yii?                                 
=> find, findAll , findByPk , find By ,query

14. How can you include a javascript menu throught the site? Give Steps…     
=>By adding the javascript files in webroot and call them in default views if needed everywhere or just in the related views.

Features of Yii
Whether you are one developer building a fairly simple Web site, or a team of distributed developers building an extremely complex Web application, using Yii is like augmenting your development team with additional experienced, professional, and efficient resources. All for free!
You can stay focused on the tasks specific to your business requirements, and let Yii provide an implementation strategy for all of the following:

Model-View-Controller (MVC) design pattern Yii adopts the proven MVC architecture, which allows for clean separation of concerns (SoC).
Database Access Objects (DAO), Query Builder, Active Record, DB Migration Yii allows developers to model database data in terms of objects and avoid the tedium and complexity of writing repetitive SQL statements.
Form input and validation Yii makes collecting form input extremely easy and safe. It comes with a set of validators as well as numerous helper methods and widgets to simplify the task for form input and validation.
AJAX-enabled widgets Integrated with jQuery, Yii comes with a set of AJAX-enabled widgets, such as auto-complete input field, treeview, data grid, which enables writing highly efficient and versatile user interface extremely simple.
Authentication and authorization Yii has built-in authentication support. It also supports authorization via hierarchical role-based access control (RBAC).
Skinning and theming Yii implements a skinning and theming mechanism that allows you to quickly switch the outlook of a Yii-power website.
Web services Yii supports automatic generation of complex WSDL service specifications and management of Web service request handling.
Internationalization (I18N) and localization (L10N) Yii supports message translation, date and time formatting, number formatting, and interface localization.
Layered caching scheme Yii supports data caching, page caching, fragment caching and dynamic content. The storage medium of caching can be changed easily without touching the application code.
Error handling and logging Errors are handled and presented more nicely, and log messages can be categorized, filtered and routed to different destinations.
Security Yii is equipped with many security measures to help prevent your Web applications from attacks such as SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and cookie tampering.
Unit and functionality testing Yii provides support for writing and running unit tests as well as functionality tests, based on PHPUnit and Selenium.
Automatic code generation Yii provides a set of intuitive and highly extensible code generation tools that can help you quickly generate the code you need for features such as form input, CRUD.
Compliance to XHTML HTML code produced by Yii components and code generators complies to the XHTML standard.
Purely object-oriented Yii framework sticks to strict OOP paradigm. It does not define any global function or variable. And the class hierarchy that it defines allows maximum reusability and customization.
Friendly with third-party code Yii is carefully designed to work well with third-party code. For example, you can use code from PEAR or Zend Framework in your Yii application.
Detailed documentation Every single method or property is clearly documented. A book and comprehensive tutorials are also available for you to systematically learn Yii.
Extension library Yii provides an extension library consisting of user-contributed components. This makes the above feature list never ending.

You might initially try Yii for its speed, security, feature richness, and superb engineering. But you’ll stick with it because it is just so intuitive, flexible and fun. Don’t take our word for it. Dive in deeper and see for yourself: Take the tour. And when your ready to get your hands a little dirty, download the framework and follow the tutorials.

Yii Theme Development

The three simple steps are:
1.Choose a HTML template and keep it under the theme directory an declare it in application configuration.
2.Making valid directory structure so that framework configuration can identify the theme
3.Add PHP code to the static HTML template

Step 1.
For this post I have used a Open Source Free HTML5 template,you can choose you own and play with it.
Declare the theme name into the application configuration and it is application/protected/config/main.php and add
Here “custom_theme” is the name of the theme I am using.

Step 2.
Keep the HTML template into the themes folder of the application.And create four directory named as follows:
>>js: here we will keep all the javascript files
>>css: here we will keep all the css files
>>images:will keep images related to the theme
>>views:here we will have to create two more directory inside it=> sites and layouts.Here we will keep our files.
Inside layout the main.php file should be kept and this file is inherited by all over the theme.
And inside layout we can keep static and custom layouts like contact us,log in etc.

Step 3.
In t his step we will add php code to our html template so that it can work properly and dynamic.

<link rel=”stylesheet” type=”text/css” href=”<?php echo Yii::app()->theme->baseUrl;?>/css/style.css” />
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.’/js/script.js’); ?>

For title you have to add

<title><?php echo CHtml::encode($this->pageTitle); ?></title>
For menu you have to add

<?php $this->widget(‘zii.widgets.CMenu’,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)
)); ?>
And the main layout is ready,as other pages are inherited from this main.php the theme is almost ready.

Concate String in CHtml::listData

I have table with following fields :

Here is my data :

1    7005    Ravi          CE
2    7006    Parth        CE
3    7007    Yashpal    IT
4    7008    Sukunj      IT

I want to display data in dropdown with following format
Sukunj-7008(IT)     using CHtml::listData

Here is my view file code
    echo CHtml::dropDownList(‘stud_id’, ”,CHtml::listData(Student::model()->findAll(), ‘id’, ‘concate’)
); ?>

Here is my model file’s concate method

    public function getConcate()
        return $this->name.”-“.$this->roll_no.”(“.$this->branch.”)”;
// or whatever format you want to display

By create this type of method you can concate any type of string that you need.
Here is the output.


List Of Query Commands for getting Data from database

Get Single Record.

1. ModelName::model()->findByPk($primaryKey);
2. ModelName::model()->findByAttributes(array(‘columnName1’=>$value1, ‘columnName2’=>$value2));
3. ModelName::model()->find(array(‘condition’=>’columnName1=’.$value1. ‘ and columnName2=’.$value2));
4. Yii::app()->user->db->createCommand()
->where(‘columnName1=’.$value1.’ and columnName2=’.$value2)

Get Last Single Record.

1. ModelName::model()->findByAttributes(array(‘columnName1’=>$value1, ‘columnName2’=>$value2,array(‘order’=>’Auto_Increment_ID desc’)));
2. ModelName::model()->find(array(‘condition’=>’columnName1=’.$value1.’ and columnName2=’.$value2,  ‘order’=>’auto_Increment_ID desc’));
3. Yii::app()->user->db->createCommand()
->where(‘columnName1=’.$value1.’ and columnName2=’.$value2.’ order by auto_Increment_ID’)

Get Multiple Records.

1. ModelName::model()->findAll(array(‘condition’=>’columnName1=’.$value1.’ and columnName2=’.$value2));
2. ModelName::model()->findAll(‘columnName1=’.$value1.’ and columnName2=’.$value2);
3. ModelName::model()->findAllByAttributes(array(‘columnName1’=>$value1,’columnName2’=>$value2));
4. ModelName::model()->findAllByAttributes(array(‘columnName1’=>$value1,’columnName2’=>$value2),
$condition= ‘columnName3 <> :aliasName3 AND columnName4 >= :aliasName4 OR columnName5 = :aliasName5’,
$params =array(
‘:aliasName3’ => $value3,
‘:aliasName4’ => $value4,
‘:aliasName5’ => $value5,
5. Yii::app()->user->db->createCommand()
->where(‘columnName1=’.$value1.’ and columnName2=’.$value2)