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

On model->update() Phalcon is trying to INSERT new record

After a couple of months of break from Phalcon I finally came back to my project. In the meantime I updated to 1.3.1. I am now having an issue with model update. In short the following is happening:

        $country = Country::findFirst(array(
            "conditions"=>"cntID = ?1",
            "bind" => array(1 =>$this->persistent->cntID),
            "for_update" => true
            )
        ...
        $formFields->bind($this->request->getPost(), $country);
        try
                {
                    if ($country->update() == false) {
                    ...
                        $this->flash->error($message->getMessage());

Here I get "Duplicate key (...)" MySQL error. While debugging I noticed that Phalcon instead going to Country->beforeUpdate() it actually goes to Country->beforeCreate(). And I thought that

    $country->update() 

tells it explicitly to go to beforeUpdate... And at the end Phalcon is trying to do INSERT SQL statement.... This situation is happening always after initial insert of a record and later on attempt of updating it. I know this i as short description. If necessary I will gladly elaborate.

can you show the "getPost" content?



9.8k
Accepted
answer

Sorry for such a delay (long weekend). Your request gave an idea and I found a solution. My understanding of Phalcon is very limited and maybe that is why I see this as a bug.

The problem I had was that in addAction I have an option to Save or to Apply. Save option was obviously saving and forwarding to indexAction, however Apply was saving and forwarding to editAction. The problem here was that from addAction the content of the POST global was missing the primary key cntID field value (the field was there, but it was empty). That value was obviously missing from $this->request->getPost() that was used for binding data to edit form. So when I was trying to save, phalcon probably figured that is needs to create a new record. What I did - just before forwarding to editAction I inserted

$_POST['cntID'] = $country->cntID;

this way forcing the getPost() to get all the data. However it is little confusing to me - I was thinking that creating a model object $country I already had all the necessary data and binding will only be used to validate the fields. And using explicit update() method should not generate INSERT statement in any case...

Anyway, thanks a lot for your help.

u r welcome :)