Search code examples
zend-frameworkzend-framework2sql-updateinsert-updatetablegateway

How to update an object in Zend Framework 2


i'm trying to update an object by using this code : The column co_nbre will be updated to 0 !!!! I think you will help me to fix this issue and thnx a lot.

public function update($model) {
        $data = get_object_vars($model);
        $id = (int) $model->id;
        $this->tableGateway->update($data, array('id' => $id));
    }

and this is how did i use it in my controller:

 if ($form->isValid()) {
                    $data = $form->getData();
                    $addi_info = new Addiinfo();
                    $addi_info->exchangeArray($data);
                    $addi_info->co_nbre = $request->getPost("co_nbre");  
                    $addi_info->user_pin = $this->layout()->pin;  
                    $addi_info->co_latitude = $request->getPost("latitude");
                    $addi_info->co_longitude = $request->getPost("longitude");
                    $addi_info->co_adresse = $request->getPost("adresse");
                    print_r($addi_info);die;
                    $checkuser=$this->getAddiinfoTable()->getAddiInfoByUserPin($user_pin);
                   if($checkuser[user_pin]==$user_pin){
                       $this->getAddiinfoTable()->update($addi_info);

Solution

  • I think you should create a function that returns associative array from model itself.

    May be some of property in "Addiinfo" class be protected/private, so you need to get all property-value of model from inside it.

    This one should be in your "Addiinfo" class,

    public function getArrayData()
    {
        return get_object_vars($this);
    }
    

    Then call it in update function

    public function update($model) {
            $data = $model->getArrayData();
            $id = (int) $model->id;
            $this->tableGateway->update($data, array('id' => $id));
        }