Common Yii questions

  1. Introduction
  2. The Questions

Introduction

Here I suggest to list the most common questions you meet in the forum or freenode irc. Feel free to edit this wiki article, and add another question with answer

Put attention of the question answer form

[html]
<hr/>

### Questions text

#### Answer:
The answer text

Discuss it here

To give some one link to this wiki in freenode yii chat write:

!faq common questions

The Questions

Why is $model->save() not saving the record/object/model?
Answer:

Because save method performs validation CActiveRecord::save

As you can see in the source code:

public function save($runValidation=true,$attributes=null)
{
    if(!$runValidation || $this->validate($attributes))
        return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
    else
        return false;
}

if you don't want it to validate just do $method->save(false);

Other possible reason is that "beforeSave" method (if overridden) doesn't return "true". <hr/>

How to connect to database in controller?
Answer:

The best approach is to set db connection in your main.php config.

The second one would be just using the CDbConnection::__construct

Examples for both aproaches can be found here Guide::Establishing Database Connection

How to change site/page?id=123 to site/page/id
Answer:

For this you should use urlManager

it is actually very-well documented... URL Manager

The direct answer to the question is - using that rule:

array(
    'site/action/<id:\d+>' => 'site/action'
)

In your you can set $id like this: actionPage($id)

or get it via Yii::app()->request->getQuery('id');

I got an error: Call to a member function getAttributes() on a non-object ...

what to do?

Answer:

First of all you should always read the error... The problem is actually indeed that you trying to use a function on some variable that is not an object, and because it is not an object - it doesn't have the method you want to use!

Use var_dump or echo CVarDumper::dump($param, 10, true); or print_r , to understand why it is not an object!

For example if you tried to get a user via active record it can be null if it does not exist, you need to check it...

Why Form / ActiveForm is not doing ajax validation ?
Answer:

In most of the cases this code snippet will help for generated form via gii:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'form-id',
    'enableAjaxValidation'=>true,
    'clientOptions' => array(
        'validateOnSubmit'=>true,
        'validateOnChange'=>true,
        'validateOnType'=>false,
    ),
)); ?>

If you create your own form, and trying to do this... better create CRUD with gii, and see how it is done there!

You need to echo the validation results if this is an ajax request! By using:

echo CActiveForm::validate($model);
How to use find() / findByAttributes() etc.
Answer:

This is an example from UserIdentity:

$user = User::model()->findByAttributes(array('username'=>$this->username));

Other way is to specify CDbCriteria.

How to increment or decrement counter via query builder
Answer:

The simplest answer would be - don't use query builder for that... But just for the protocol

Yii::app()->db->commandBuilder->createUpdateCommand( 
   '{{table}}', 
   array( 
      'counter' => new CDbExpression( 'counter + :counter' , array(':counter'=>1))
   ), 
   new CDbCriteria(
      array(
         "condition" => "id = :id" , 
         "params" => array(
            "id"=>1
         )
      )
   )
)->execute();
How to use model()->find() / model()->findAll()
Answer:

There are three ways:
First CdbCriteria:

$criteria = new CDbCriteria();
$criteria->compare('first_name', 'Paul');
$criteria->compare('last_name', 'Smith');
$users = User::model()->findAll($criteria);

Second:

User::model()->findAll('first_name=? AND last_name=?', array('Paul', 'Smith'));

Third:

User::model()->findAllByAttributes(array('first_name'=>'Paul', 'last_name'=>'Smith'));

The result will be collection of models, to get an array you can use DAO or QueryBuilder

Property ClassName.xxx is not defined , what is the problem?
Answer:

First of all, actually the error message say all what you need to know!

This is very common error in component configuration, and widget configuration. This is not a framework issue!

To solve it, you should make sure that the ClassName has a field with the name you are trying to use. This can be a capital letter issue, or just the property aka field not exists in the class...

Read the class reference to see if there is a property that you want to use, or if this is an extension or widget - open the class file, and see if there is the property and you spelled it well

for example if this is the class:

class Foo{
    public $bar = 123;
}

And you trying to access Foo.bor , it not exists there!

See also: 1 2 3 4 5

Trying get uploaded file via CUploadedFilee::getInstanceByName() and getting null every time
Answer:

I will just show you working example:

//this is how to get the file
$file = CUploadedFile::getInstanceByName('data');
//upload form
CHtml::beginForm('', 'post',array('enctype'=>'multipart/form-data'));
//the file field
CHtml::fileField('data', '');
what's the difference between exit and Yii::app()->end()
Answer:

Both terminates the application. But end method calls onEndRequest event before doing the exit... In this case as in a lot of others the source code explains itself very-well

public function end($status=0, $exit=true)
{
    if($this->hasEventHandler('onEndRequest'))
        $this->onEndRequest(new CEvent($this));
    if($exit)
        exit($status);
}
14 0
23 followers
Viewed: 50 357 times
Version: 1.1
Category: FAQs
Written by: dckurushin
Last updated by: migajek
Created on: Oct 17, 2011
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles