Thursday, November 22, 2012

CakeDC CsvImport Behavior with belongsTo

Hi All!

I've implemented the CakeDC CsvImport Behavior (https://github.com/CakeDC/utils/blob/master/Model/Behavior/CsvImportBehavior.php) to allow me to save csv data to my models.
It's working fine, but I have some questions if there is anyone else who has used this behavior.

Say I have the following tables and columns:

Products:
id
product_type_id
price_date
price

Product_types:
id
product_type_code
product_type_name

Product belongsTo ProductType

I have a file layout like this to load product data:

"Product.product_type_code","Product.price_date","Product.price"

When the file is loaded a record must be inserted into the Product table, using the ProductType id.

What I've done is in the beforeImport function I call $this->ProductType->findByProductTypeCode to get the id.
I've also modified the behavior so the beforeImport function can return errors - if the product type is not valid.

BeforeImport code on Product model:

    public function beforeImport($data, $errors) {
    // get ProductType id using the code
        $productTypeId = $this->ProductType->findByProductTypeCode($data[$this->alias]['product_type_code'], array('ProductType.id'));
        if ($productTypeId == null) {
            $errors = 'Product Type ' . $data[$this->alias]['product_type_code'] . ' does not exist. ProductType must be added before file is reloaded.';
            return false;
        } else {
        // build new data array
            $new = array($this->alias => array('product_type_id' => $productTypeId['ProductType']['id'],
                                               'price_date' => $data['Product']['price_date'],
                                               'price' => $data['Product']['price']));
            return $new;
        }
    }

I also changed the original behavior code which calls the beforeImport function:


            if (method_exists($Model, 'beforeImport')) {
//start custom
                $beforeImportErrors = null;
                $data = $Model->beforeImport($data, &$beforeImportErrors);
                if ($beforeImportErrors != null) {
                    $this->errors[$Model->alias][$i]['Custom'] = $beforeImportErrors;
                    $this->_notify($Model, 'onImportError', $this->errors[$Model->alias][$i]);
                    $error = true;
                }
//end custom
            }

Have I done something extra that is not required?  What would you do differently?

Thanks very much!
Kevin

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
 
 

No comments: