Newbie: Problem Storing From A Model

Hi,

I used CRUD to generate a model.

I am trying to store a record with it.

Here is what I do:

$model = new NewsModel;

$model->attributes = array(

'id' => '',


'user_id' => Yii::app()->user->id,


'title' => $this->title,


'description' => $this->description,


'active' => 1,


'store_date' => date('Y-m-d H:i:s'),

);

$model->store();

when I run the code, I don’t get an error message, but there is no record stored in the database.

Can anyone help me with this one?

In general, some resources about specifics to YII MVC would be highly appreciated, as I use Yii for a couple of days.

I use XAMP/Windows, with MySQL as database

Thanks,

Saylor

The method to store is save(). Try this to determine what the error actually is:




if (!$model->save)

    print_r($model->getErrors());



Also note that you can set attributes like so:




$model->id = '';

$model->user_id = Yii::app()->user->id;

.

.

.



Hi,

I did all of the tasks, both by trying to set AR by the attributes array and initializing individual attributes.

The error I receive is: Array ( [id] => Array ( [0] => ID cannot be blank. ) )

As I already mentioned, I have a CRUD generated model, and a PK in the table which cannot be blank.

How can I store?

Thanks,

Saylor

It sounds like your database id field isn’t configured as an auto incrementing field. Change the field in the database to ensure that it’s both the primary key and auto incrementing.

Hi, here the dump of the table structure:

CREATE TABLE IF NOT EXISTS tbl_news (

id int(11) unsigned NOT NULL,

user_id int(11) NOT NULL,

title varchar(255) NOT NULL,

description varchar(5000) NOT NULL DEFAULT ‘’,

date_created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

PRIMARY KEY (id),

KEY user_id (user_id)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

OK,

I fixed the autoincrement, but the error persists.

You need to mark the id field with the AUTO_INCREMENT attribute. It should look like this:


`id` int(11) unsigned NOT NULL AUTO_INCREMENT,

Is it the same error or a different one? If you’re caching your model schemas then your app will still be seeing stale data. Try turning off schema caching temporarily.

Hi, disabled te following row in config/main.php

// ‘cache’ => array(‘class’ => ‘CDummyCache’),

still the same error

Hi,

After regenerating the model, everything is fine now :)

Huge thanks for the support, :)!

Saylor

Make sure ‘id’ doesn’t appear in your ‘required’ validators in the model rules. It may have been generated by CRUD if no AUTO_INCREMENT attribute was found.

EDIT: I suspect this was the case judging by the post above.