Zabs
Zabs

Reputation: 14142

Yii record is not inserting into DB

Below is my controller & model logic - I just started a barebones Yii installation to play around with it more.

I get no errors but don't see the new entry in the database - my db has been configured in the main.php (this works as Gii runs).

// controllers/PageController.php
class PageController extends Controller
{
    public function actionSave($value='')
    {
        $pageObj = new Page;
        $pageObj->savePage();
    }     
}


// models/Page.php

class Page extends CActiveRecord
{
/**
 * @return string the associated database table name
 */
public function tableName()
{
    return 'page';
}

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('title, date_updated', 'required'),
        array('live', 'numerical', 'integerOnly'=>true),
        array('user_id', 'length', 'max'=>10),
        array('title', 'length', 'max'=>100),
        array('content, date_published', 'safe'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, user_id, live, title, content, date_updated, date_published', 'safe', 'on'=>'search'),
    );
}

/**
 * @return array relational rules.
 */
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'comments' => array(self::HAS_MANY, 'Comment', 'page_id'),
        'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        'files' => array(self::MANY_MANY, 'File', 'page_has_file(page_id, file_id)'),
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'user_id' => 'User',
        'live' => 'Live',
        'title' => 'Title',
        'content' => 'Content',
        'date_updated' => 'Date Updated',
        'date_published' => 'Date Published',
    );
}

/**
 * Retrieves a list of models based on the current search/filter conditions.
 *
 * Typical usecase:
 * - Initialize the model fields with values from filter form.
 * - Execute this method to get CActiveDataProvider instance which will filter
 * models according to data in model fields.
 * - Pass data provider to CGridView, CListView or any similar widget.
 *
 * @return CActiveDataProvider the data provider that can return the models
 * based on the search/filter conditions.
 */
public function search()
{
    // @todo Please modify the following code to remove attributes that should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id,true);
    $criteria->compare('user_id',$this->user_id,true);
    $criteria->compare('live',$this->live);
    $criteria->compare('title',$this->title,true);
    $criteria->compare('content',$this->content,true);
    $criteria->compare('date_updated',$this->date_updated,true);
    $criteria->compare('date_published',$this->date_published,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

/**
 * Returns the static model of the specified AR class.
 * Please note that you should have this exact method in all your CActiveRecord descendants!
 * @param string $className active record class name.
 * @return Page the static model class
 */
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

public function savePage($value='')
{
    $page = new page;
    $model->isNewRecord = true;
    $model->primaryKey = NULL;
    $page->title='sample page';
    $page->content='content for the sample page';
    $page->save(false);
}
}

Upvotes: 2

Views: 6085

Answers (3)

Zabs
Zabs

Reputation: 14142

Thanks for that - I had missed out some columns.. (silly me) Improve the function even further with the help above..

public function savePage()
{
    $page = new page;
    $page->isNewRecord = true;
    $page->primaryKey = NULL;
    $page->user_id = 1;
    $page->live = 0;
    $page->content='content for the sample page';
    $page->date_updated = date('Y-m-d H:i:s');
    $page->date_published = date('Y-m-d H:i:s');        
    $page->title='sample page';

    if ($page->validate()) {
        $page->save();
    } else {
        CVarDumper::dump($page->getErrors(),5678,true);
        Yii::app()->end();          
    }
}

Upvotes: 0

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

In Yii, when you want to insert into a table which has some null columns, you must put null columns in your rules as SAFE like below:

array('primaryKey','safe'),

Now, Yii knows that primaryKey is a null column. So, there would be no problem via inserting into the current model.

As a note, when you call save() method with FALSE, you are telling to your model to do not the validation on insert.

Also, the correct way to skip possible errors is to validate your model before inserting like below:

if($model->validate()){
    // VALIDATE, YOU CAN CALL SAVE FUNCTION
}else{
    //here you can send an error message via FLASH or you can debug what the exact error is like below:
    CVarDumper::dump($model->getErrors(),5678,true);
    Yii::app()->end();
}

I hope, it help

Upvotes: 8

Zabs
Zabs

Reputation: 14142

So simple... I hate Yii sometimes :-)

Had to set the save() to save(false)

    $page = new page;
    $page->isNewRecord = true;
    $page->primaryKey = NULL;
    $page->title='sample page';
    $page->content='content for the sample page';
    $page->save(false);

Upvotes: 1

Related Questions