Import Binding a Company, creating the record if it doesn’t exist
Estimated reading: 2 minutes
The following example shows how to set the Owner Company model field with the ID of a company which has been specified by name in the import file. If the company doesn’t exist then it is created.
This example is very import, because it demonstrates how to create a related entity starting from a value specified in the Excel File.
/* $value contains the value of the current column in the import file, calling trim()
method (after casting as string type) to eliminate any space at the beginning or
at the end of the string */
$value = trim((string)$value);
/* if the company name field specified in the import file is not empty */
if($value) {
/* if the company name (transformed into uppercase) doesn’t exist in DeepDesk.
Here we are checking the keys of $companyArray created in the 'Before Run' area */
if(!array_key_exists(strtoupper($value), $companyArray)){
/* a new Company object is created through the static getModel() method of the Deep class (
via the abstract factory pattern)*/
$companyModel = Deep::getModel('deep_company/company');
$companyModel->setName($value);
$companyModel->setStatus(1);
/* saving the company to Database after setting the name and the status (1 = Enabled) */
$companyModel->save();
/* adding the company just created to the $companyArray */
$companyArray[strtoupper($value)] = $companyModel->getId();
}
/* the field owner_company_id of the CI is set here.
The id is calculated starting from the name of the company specified in the import file */
$model->setOwnerCompanyId($companyArray[strtoupper($value)]);
}