P
P
phpForeve2017-02-25 22:36:04
MySQL
phpForeve, 2017-02-25 22:36:04

Yii2 How to get the ID of the record I'm working with?

There is a model that creates an entry in the database. Next I have to write. "HOORAY! The $id entry was added successfully"
Here is my controller

public function actionCreate(){
        $model = new NewsForm();
        $model->create_at = (new DateTime())->format('Y-m-d H:i:s');
        $model->update_at = (new DateTime())->format('Y-m-d H:i:s');
        if ($news = $model->create()) {
           echo 'УРА! Запись' .  $model->id . 'была успешно добавлена';
        }
    }

Here is the Create function from the form
public function create()
    {
        if (!$this->validate()) {
            return null;
        }
        $news = new News();
        $news->create_at = $this->create_at;
        $news->status = 'archive';
        var_dump($news);die;
        return $news->save() ? $news : null;
    }

But $model->id returns NULL to me, in the form var_dump($news) - there is also no id.
What to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
padlyuck, 2017-02-25
@phpForeve

public function create()
    {
        if (!$this->validate()) {
            return null;
        }
        $news = new News();
        $news->create_at = $this->create_at;
        $news->status = 'archive';
        var_dump($news);die;
        return $news->save() ? $news : null;
    }

>>> in the form var_dump($news) - also no id.
of course not, because it has not been saved yet. remove the wardump from the form and change the action to
public function actionCreate(){
        $model = new NewsForm();
        $model->create_at = (new DateTime())->format('Y-m-d H:i:s');
        $model->update_at = (new DateTime())->format('Y-m-d H:i:s');
        if ($news = $model->create()) {
           echo 'УРА! Запись' .  $news->id . 'была успешно добавлена';
        }
    }

if it does not display id - we will continue to pick

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question