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

Updating a row

Hi again,

At the moment I'm trying to update a row specially whenever a user last visits but everytime I keep getting errors saying few fields like email and usermae are required. My function which updates looks like this

$userId = 46;
$userModel = new User();
$userModel->user_id = $userId;
$userModel->last_login = time();
$userModel->update();

Any help would be appreciated.



4.1k
Accepted
answer

You should do a search for the user, then assign the values as the table fields, is an example.

        $user = Users::findFirstById($id);
        if (!$user) {
            $this->flash->error("User was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }
        if ($this->request->isPost()) {
                $user->assign(array(
                    'name' => $this->request->getPost('name', 'striptags'),
                    'username' => $this->request->getPost('username', 'striptags'),
                    'email' => $this->request->getPost('email', 'email'),
                    'profilesId' => $this->request->getPost('profilesId', 'int'),
                    'active' => $this->request->getPost('active')
                ));
                if (!$user->save()) {
                    $this->flash->error($user->getMessages());
                } else {
                    $this->flash->success("User was updated successfully");
                    Tag::resetInput();
                }
        }
        $this->view->user = $user;
        $this->view->form = new UsersForm($user, array(
            'edit' => true
        ));


2.9k

Thanks! That did the job :)