Difference between #9 and #7 of Common Yii questions

unchanged
Title
Common Yii questions
unchanged
Category
FAQs
unchanged
Tags
yii, common, questions, beginners
changed
Content
Introduction
------------
Here I suggest to list the most common questions you meat 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](http://www.yiiframework.com/forum/index.php?/topic/24729-creating-common-questions-wiki/
"http://www.yiiframework.com/forum/index.php?/topic/24729-creating-common-questions-wiki/")

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


~~~
[php]
!faq common questions
~~~

The Questions
-------------

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

#### Answer:
Because save method performs validation
[CActiveRecord::save](http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail
"CActiveRecord::save")

As you can see in the source code:
~~~
[php]
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(true);****$method->save(false);**

<hr/>

### How to connect to database in controller?

#### Answer:
The best approach is to set db coneection 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](http://www.yiiframework.com/doc/guide/1.1/en/database.dao#establishing-database-connection
"http://www.yiiframework.com/doc/guide/1.1/en/database.dao#establishing-database-connection")


<hr/>

### 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](http://www.yiiframework.com/doc/guide/1.1/en/topics.url
"http://www.yiiframework.com/doc/guide/1.1/en/topics.url")

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

~~~
[php]
array(
    'site/action/<id:\d+>' =>
'site/action'site/action'
)
~~~

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

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


<hr/>

### 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 has
the method you want to use!

so 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 is
not exists, you need to check it...

<hr/>

### Why Form /  ActiveForm not doing ajax validation ?

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

~~~
[php]
<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'top-websites-cr-form',
        '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!
via
~~~
[php]
echo CActiveForm::validate($model);

~~~

<hr/>

### How to use find / findByAttributes etc.

#### Answer:
This is an example from UserIdentity:

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

other way is specify
[CDbCriteria](http://www.yiiframework.com/doc/api/1.1/CDbCriteria
"http://www.yiiframework.com/doc/api/1.1/CDbCriteria")

<hr/>

### 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

~~~
[php]
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();
~~~