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)

Uploading files (Advanced)


Let's add the upload functionality to our registration form. We'll add a file-upload dialog, asking the user to upload his image.

Getting ready

We'll use the form we have developed in the Creating basic forms recipe.

How to do it...

  1. Let's start with editing our model User.php. Add a public attribute named $image.

    public $image;
    
    public static function model($className=__CLASS__)
    {
      return parent::model($className);
    }
  2. Now add some validation rules for this attribute.

    return array(
      array('image', 'file', 'allowEmpty' => true, 
        'types' => 'jpg, jpeg, gif, png'
      ),
    ...
    );
  3. Add the attribute's name to this attribute:

    'image'=>'Upload Photo',
  4. Edit _form.php under protected/views/user to add the following lines to enable this form to accept file uploads:

    'htmlOptions' => array('enctype' => 'multipart/form-data'),
    <code in uploads/_form.php>
  5. Finally, add the following lines to the UserController.php action created, to save the uploaded file:

    if(isset($_POST['User']))
    {
      $model->attributes=$_POST['User'];
      $model->image=CUploadedFile::getInstance($model,'image');
      if($model->save())
      {
        $path=Yii::getPathOfAlias(
        'webroot.images.'.$model->first_name
        );
      $model->image->saveAs($path);
      $this->redirect(array('view','id'=>$model->id));
      }
    }

That's it, we are done. Now try to fill the form, select the file to be uploaded and you can find the uploaded file at the web_root/images folder.

How it works...

At the start, we set a public attribute to our User model to hold the file data. Next we set some validation rules to specify that the file upload is not compulsory and the user can upload only .jpg, .gif, and .png files.

Then we set our form to accept file uploads. As we are uploading the binary data in the form of a file, we need to enable our form to accept binary data. We did this with 'enctype' => 'multipart/form-data'. Additionally, the form method must be set to POST.

At this stage we are done with the upload part, but at the server side we need some logic to process the uploaded contents. We added this functionality with the following line:

$model->image=CUploadedFile::getInstance($model,'image');

To get the uploaded contents in $model->image, we add the following line:

$model->image->saveAs($path.$model->first_name);

We have saved and received data in a file with the same name as the user's first name. Alternatively, you can get the original filename with $model->image->getName().

We have used two components provided by Yii. Following are the two components:

  • CUploadedFile: This represents the information for an uploaded file. It's a wrapper class for the $_FILE array that PHP uses to hold uploaded files. We have used its getInstance() method to get the uploaded file and then used saveAs() to save the data to the file. Additionally, we can get other information about the file, including the name, temporary name, type, size, and errors. Get more details on the website http://www.yiiframework.com/doc/api/1.1/CUploadedFile.

  • CFileValidator: This verifies if an attribute is receiving a valid uploaded file. With the file validator, we can make the file field compulsory, specify the maximum number of files, and specify the minimum and maximum limits on the file size and a file type. We can also set the details of the errors to be displayed. By adding the following lines in the rules array of the model, we can enable the file field validation:

    return array(
      array('image', 'file', 'allowEmpty' => true, 
        'types' => 'jpg, jpeg, gif, png'
      ),
    ...
    );

With these lines, we have set the image attribute to be optional and we have restricted the file types to image files.

You can get more details from the website http://www.yiiframework.com/doc/api/1.1/CFileValidator/.