Social Icons

Pages

Thursday, April 25, 2013

How to upload a file using a model Yii



The Model 

First declare an attribute to store the file name in the model class (either a form model or an active record model). Also declare a file validation rule for this attribute to ensure a file is uploaded with specific extension name.
class Item extends CActiveRecord
{
    public $image;
    // ... other attributes
 
    public function rules()
    {
        return array(
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }
}


The Controller 

Then, in the controller class define an action method to render the form and collect user-submitted data.
class ItemController extends CController
{
    public function actionCreate()
    {
        $model=new Item;
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->image=CUploadedFile::getInstance($model,'image');
            if($model->save())
            {
                $model->image->saveAs('path/to/localFile');
                // redirect to success page
            }
        }
        $this->render('create', array('model'=>$model));
    }
}

The View 

Finally, create the action view and generate a file upload field.
$form = $this->beginWidget(
    'CActiveForm',
    array(
        'id' => 'upload-form',
        'enableAjaxValidation' => false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
    )
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
$this->endWidget();


Tuesday, April 23, 2013

Monday, April 22, 2013

Multiple Image Uploading



step-1:

In view

    <div class="row">
        <?php echo $form->labelEx($model,'image'); ?>
        <?php
          $this->widget('CMultiFileUpload', array(
             'model'=>$model,
             'name'=>'image',
             'attribute'=>'image',
             'accept'=>'jpg|gif|png',
            ));
        ?>
        <?php echo $form->error($model,'image'); ?>
    </div>


in controller at actionCreate

public function actionCreate()
{
        $model=new Photo;
        // Uncomment the following line if AJAX validation is needed
         $this->performAjaxValidation($model);

        if(isset($_POST['Photo']))
        {
            $model->attributes=$_POST['Photo'];
            $images = CUploadedFile::getInstancesByName('image');
           
            if(isset($images) && count($images)> 0)
            {
                foreach ($images as $image=>$pic)
                {
                                if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name,0777))     
                    {  
                        $model->setIsNewRecord(true);
                        $model->id = null;
                        $model->image = $pic->name;
                        $model->save();
                    }              
                }
                        $this->redirect(array('view','id'=>$model->id));
            }
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

Friday, April 19, 2013

Calender in Cgridview filter




here my model field is update_date



 
 'afterAjaxUpdate'=>"function(){jQuery('#date_purchased_search').datepicker({'dateFormat': 'yy-mm-dd'})}",

    'columns'=>array(
..............................
 array(
     'name' => 'update_date', 'type' => 'raw',
     'filter'=>$this->widget('zii.widgets.jui.CJuiDatePicker',
 array('model'=>$model, 'attribute'=>'update_date',
     'htmlOptions' => array('id' => 'date_purchased_search'), 'options' => array('dateFormat' => 'yy-mm-dd')), true)
 ),
......................

) //end columns

Name of current module controller or action from Yii view


 Useful in situations where you want to build a navigation user interface element etc. This is all you need to know...

// Module
if(isset($this->module)): echo $this->module->getName(); endif;

// Controller
echo $this->ID;

// Action
echo $this->action->id;

Sunday, March 31, 2013

auth module integration steps

1) Download the latest release from Yii extensions Auth.
http://www.yiiframework.com/extension/auth/

and placed under folder protected/modules, if not please create one folder named modules

2)Then protected/config/main.php 

on module array add

        'modules'=>array(
                .........
                'auth', 
                
                ),


OR 

'modules'=>array(
        .........

  'auth' => array(
        'strictMode' => true, // when enabled authorization items cannot be assigned children of the same type.
        'userClass' => 'User', // the name of the user model class.
        'userIdColumn' => 'id', // the name of the user id column.
        'userNameColumn' => 'name', // the name of the user name column.
        'appLayout' => 'application.views.layouts.main', // the layout used by the module.
        'viewDir' => null, // the path to view files to use with this module.
  ),

  ),


in components array

  'components' => array(
    'authManager' => array(
        ......
      'behaviors' => array(
        'auth' => array(
          'class' => 'auth.components.AuthBehavior',
          'admins' => array('admin', 'foo', 'bar'), // users with full access
        ),
      ),
    ),
    'user' => array(
      'class' => 'auth.components.AuthWebUser',
    ),
  ),



Please note that while the module doesn't require you to use a database, if you wish to use CDbAuthManager you need it's schema (it can be found in the framework under web/auth/schema-mysql.sql(if mysql is using), and it import to your db).

also change the authManager array to 

   'authManager' => array(
                'class' => 'CDbAuthManager',
                'connectionID' => 'db',
                'behaviors' => array(
                        'auth.components.AuthBehavior',
                ),
        ),
        


and in main controller  use 

        public function filters()
        {
        return array(
        array('auth.filters.AuthFilter'),
        );
        }




auth module will ready to use index.php?r=auth with normal template 

3) if you want to use bootstrap pleas do as below

download bootstrap from http://www.yiiframew...nsion/bootstrap and placed under protected/extension/bootstrap
then copy the theme from bootstrap to theme folder under you webapplication/themes/



Top of the protected/config/main.php add 

        Yii::setPathOfAlias('bootstrap', dirname(__FILE__).'/../extensions/bootstrap');

in components array 

   'bootstrap'=>array(
                                'class'=>'bootstrap.components.Bootstrap',
                ),



and change appLayout from auth array as below

    modules =array(
                
                auth=>array(
                ......
                'appLayout' => 'webroot.themes.theme.views.layouts.main', // the layout used by the module.
                                )
        ),

Saturday, March 30, 2013

Display a nice exception message on ajax requests


please refer the link


 http://www.yiiframework.com/wiki/228/display-a-nice-exception-message-on-ajax-requests/


or use the below code in your default controller


public function actionError()
{
    if($error=Yii::app()->errorHandler->error)
    {
        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('error', $error);
    }
}