Book Image

Instant Building Multi-Page Forms with Yii How-to

By : Uday Sawant
Book Image

Instant Building Multi-Page Forms with Yii How-to

By: Uday Sawant

Overview of this book

Yii is a high-performance PHP framework for rapid web application development. It is well-designed, well-supported, easy to learn, and easy to maintain. Forms are the basic method used to collect information on the Internet, and in cases like user registration and payment process, there's a lot of data to be presented and the lists can get lengthy. Instant Building Multi-Page Forms with Yii is a simple and descriptive how-to that provides step-by-step recipes to help you in converting your lengthy forms into short, interactive forms. It will guide you through the inbuilt features of Yii framework to help you with this complex job. The book starts with the basics of Yii and will guide you through creating simple forms before then converting your simple forms into multi-page forms. It will use the capabilities of Yii to ease the tasks required to do this. Yii eases your work by providing options like database connectivity. We will also take a look at the automated code generation capabilities of Yii in generating forms and necessary CRUD operations, as well as looking at how to divide a single long form into multiple views with same controller/action, and then add form validations and AJAX support to the forms. We will also cover the upload process and how to customise Yii's looks.
Table of Contents (7 chapters)

Connecting to the database (Simple)


This recipe describes the steps required to set up database access in a Yii application.

Getting ready

We will use a sample application like the one created in the previous recipe. Additionally, we will need a database server like MySQL, PostgreSQL, or SQLite; also, we will need its credentials and some interface like PHPMyAdmin or command-line access to execute SQL statements against our database.

How to do it...

First of all, we need to create a database.

  1. Create a new database in MySQL.

  2. Now, go to the sample application and change the folder to protected/config. It contains the following three files:

    • console.php: This is the configuration file to run applications in console mode

    • main.php:This is the configuration file for web applications

    • test.php: This is the configuration file for testing web applications

  3. Open main.php and locate the following code:

    'db'=>array(
      'connectionString' =>
      'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
    ),
    // uncomment the following to use a MySQL database
     */
    'db'=>array(
      'connectionString' => 
      'mysql:host=localhost;dbname=sampleapp',
      'emulatePrepare' => true,
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
    ),
    
    */

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  4. The basic application created uses the SQLite database. Remove the code for SQLite configuration and uncomment the MySQL configuration.

  5. Change the connectionString, username, and password to match your environment. This is all you need to set the database connection.

There's more...

Yii provides the following three methods to work with database connections:

  • Active Record

  • Query Builder

  • Data Access Objects (DAO)

Models in Yii generally extend the CActiveRecord class to provide database access using the Active Record method. This uses a complete object-oriented coding style and creates all the necessary SQL to deal with the database server. Additionally, we can set validation rules in models and also add pre- and post-save hooks. Yii provides the GUI tool named Gii to generate the models for database tables. Though the Active Record method is easy to use, it consumes more memory and needs more execution time than other methods. The sample code to get all records from a table (say, User) will go as follows:

$users = User::model()->findAll(array('status'=>'active'));

With Query Builder, we create a command object with Yii::app()->db->createCommand() and then add other parts of SQL query with methods such as select, from, where, and join. Query Builder is faster than Active Record and provides a clean API to query the database. For example:

$command = Yii::app()->db->createCommand();
$command->select(*)->from('user')->where(array(
'status'=>'active'
));
$users = $command->queryAll();

Finally, with a DAO we create the same command as in Query Builder, but instead of adding a query using methods, we pass the entire SQL statement to it as Yii::app()->db->createCommand($sql). This is the fastest method to access the database and also useful when we need to write complex queries such as the following:

$sql = 'select * from user where status = "active"';
$users = Yii::app()->db->createCommand($sql)->queryAll();

Both Query Builder and the DAO return data in the raw-array format, whereas Active Record returns an array of models with each representing a single row.