We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

update() the wrong record?

Hi,

I’m currently doing my first Phalcon project. I have a problem with updating records. only the record with ID 1 is updated?

public function edithAction(){
$postId = $this->dispatcher->getParam('postId');
$article = Articles::findFirst($postId);
        Phalcon\Tag::prependTitle('Edith Article');
        \Phalcon\Tag::setDefaults(array("title" => $article->getArticleTitle(), "date" => $article->getPostDate() ,"articleDesc" => $article->getArticleDescription(), "article" => $article->getArticleContent()));

        if ($this->request->isPost()) {

            $article->setArticleTitle($this->request->getPost("title"));
            $article->setPostDate($this->request->getPost("date"));
            $article->setArticleDescription($this->request->getPost("articleDesc"));
            $article->setArticleContent($this->request->getPost("article"));
            $article->update();

           $messages = $article->getMessages();
            if (count($messages)) {
                $this->flash->error("Umh, We can't update article right now.");
                return $this->dispatcher->forward(array(
                    'controller' => 'admin', 'action' => 'search'));
            } else {
                $this->flash->success("Great, article was updated successfully!");
                return $this->dispatcher->forward(array(
                    'controller' => 'admin', 'action' => 'search'));
            }
        }}

Hi,

you are trying to get article here:

 $article = Articles::findFirst($postId);

And the you update the same record.. twice..:

         $article->update();

        if ($article->update() === false) {

If you want to check is successfully updated, check

$messages = $article->getMessages();
if (count($messages)) {
    // bad update
} else {
    // good update
}
edited Jul '18

Thank you for your response, but did not solve the problem.

I get the correct article, edith it and once save button is pressed no matter which record is selected, not the one selected but the article with ID 1 is being updated.

Hi,

you are trying to get article here:

$article = Articles::findFirst($postId);

And the you update the same record.. twice..:

        $article->update();

       if ($article->update() === false) {

If you want to check is successfully updated, check

$messages = $article->getMessages();
if (count($messages)) {
   // bad update
} else {
   // good update
}
edited Jul '18

Are you sure that $postId is correct id? You should try to get param from request, not from dispatcher

$this->request->get('postId');

And try to do

$article = Articles::findFirstById($postId);

This won't allow to pass null|false value.

Because Model::findFirst(null) always gets first data record. It can be your issue.