Search code examples
symfony1symfony-1.4doctrine-1.2

Checking how many fields have changed upon saving a form


I am saving records in a transaction using symfony1.4 and Doctrine.

The rows inserted are coming from a CSV file which is updated regularly. I have already got a method that checks if the records in the CSV match that in the DB and do not insert.

What I'm ideally wanting to do though, is to set a user flash telling them how many rows have been updated whenever they import the CSV file.

            $conn = ProductTable::getInstance()->getConnection();
            $conn->beginTransaction();

            try {
                $row = 1;
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if ($row > 1) {
                        $values = array(
                            'blah'            => null
                        );

                        $obj= ProductTable::getInstance()->findOrCreateNewProduct(
                            $values['blah']
                        );


                        $obj->merge($values);
                        $obj->save($conn);
                    }

                    $row++;
                }

                $conn->commit();

            } catch (Doctrine_Exception $e) {
                $conn->rollback();

                throw $e;
            }

I'm wondering how I'd get these updated fields. Is it in the actions.class.php or is it in the actual form.class.php file?

Thanks


Solution

  • On the you can call a Doctrine_Record::getModified() which will give you an array of fields modified (with their values though that doesnt matter for you). Then you can call count on the returned array and keep a cumulative total outside your loop.

            $conn = ProductTable::getInstance()->getConnection();
            $conn->beginTransaction();
            $nbModified = 0;
    
            try {
                $row = 1;
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if ($row > 1) {
                        $values = array(
                            'blah'            => null
                        );
    
                        $obj= ProductTable::getInstance()->findOrCreateNewProduct(
                            $values['blah']
                        );
    
    
                        $obj->merge($values);
                        $nbModified += count($obj->getModified());
                        $obj->save($conn);
                    }
    
                    $row++;
                }
    
                $conn->commit();
    
                // return $nbModified or otherwise do something with it here
    
            } catch (Doctrine_Exception $e) {
                $conn->rollback();
                // youre rolling back so just for consistency set $nbModified to zero
                $nbModified = 0;
    
                throw $e;
            }