Drupal 7 – Commerce Migration Class
Here’s a migration class I’ve been working on to import 8200 products. The biggest feature of this code is that it will automatically create a single product display node that groups all products who share the same “grouping identifier.” So, in my CSV import file I have a “grouping_identifier” column. If a product is available in ten colors, and they all share the same grouping identifier, a single product display will be created and each of these products will be referenced in it. This will result in a product on the frontend that allows ten different color choices. I don’t have the time right now to explain anything more… please leave a comment if you have a question.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
name = "Migrate MIVA" description = "Module to migrate MIVA products to Drupal Commerce" package = "Development" core = 7.x dependencies[] = migrate dependencies[] = migrate_extras dependencies[] = field dependencies[] = file dependencies[] = image dependencies[] = number dependencies[] = text dependencies[] = options dependencies[] = taxonomy dependencies[] = commerce_migrate dependencies[] = commerce_product dependencies[] = commerce_product_ui # Migrate classes files[] = miva_migration.module files[] = products.inc |
1 2 3 4 5 6 7 8 9 10 |
/** * Implemenation of hook_migrate_api(). */ function miva_migration_migrate_api() { $api = array( 'api' => 2, ); return $api; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
/** * @file * Commerce Product migration. */ class MivaProductMigration extends Migration { public function __construct() { parent::__construct(); $this->description = t('Import products from Miva (via a custom csv).'); $this->source = new MigrateSourceCSV(DRUPAL_ROOT . '/' . drupal_get_path('module', 'miva_migration') . '/import/csv/all_products.csv', array(), array('header_rows' => 1)); $this->destination = new MigrateDestinationEntityAPI('commerce_product', 'product'); // Create a map object for tracking the relationships between source rows $this->map = new MigrateSQLMap($this->machineName, array( 'product_sku' => array( 'type' => 'varchar', 'length' => 100, 'not null' => TRUE, 'description' => 'Product SKU', 'alias' => 'sku', ), ), MigrateDestinationEntityAPI::getKeySchema('commerce_product', 'product') ); // Field defaults (no values in CSV) $this->addFieldMapping('uid')->defaultValue(0); // Field mappings $this->addFieldMapping('status', 'status')->defaultValue(1); $this->addFieldMapping('sku', 'product_sku'); $this->addFieldMapping('commerce_price', 'price_amount'); $this->addFieldMapping('title', 'title'); $this->addFieldMapping('type')->defaultValue('product'); $this->addFieldMapping('field_product_code', 'product_code'); $this->addFieldMapping('field_taxable', 'taxable'); $this->addFieldMapping('field_supplier_sku', 'supplier_sku'); $this->addFieldMapping('field_actual_cost', 'actual_cost'); $this->addFieldMapping('field_upc', 'upc'); $this->addFieldMapping('field_msrp', 'msrp_amount'); $this->addFieldMapping('field_description', 'body_html'); $this->addFieldMapping('field_description:format')->defaultValue('full_html'); $weight_field_arg = MigrateCommercePhysicalWeightFieldHandler::arguments('lb'); $this->addFieldMapping('field_weight', 'weight')->defaultValue(1)->arguments($weight_field_arg); // Field should look like: black_yellow|Black/Yellow $this->addFieldMapping('field_color', 'color_options')->callbacks(array($this, 'getOptionKey')); // Field should look like: 130mm|130mm $this->addFieldMapping('field_size', 'size_options')->callbacks(array($this, 'getOptionKey')); // Field should look like: hard|Hard $this->addFieldMapping('field_misc_options', 'misc_options')->callbacks(array($this, 'getOptionKey')); // Taxonomy fields $this->addFieldMapping('field_tags', 'tags')->separator('||'); $this->addFieldMapping('field_year', 'year')->separator('||'); $this->addFieldMapping('field_brand', 'brand')->separator('||'); // image_path will look like media/from_adams_script/2012_Swix_U60.jpg $this->addFieldMapping('field_image', 'image_path'); $this->addFieldMapping('field_image:file_replace')->defaultValue(FILE_EXISTS_RENAME); $this->addFieldMapping('field_image:source_dir') ->defaultValue(drupal_get_path('module', 'miva_migration') . '/import'); $this->addFieldMapping('field_image:alt', 'title'); $this->addFieldMapping('field_image:title', 'title'); // Fields from CSV to ignore $this->addUnmigratedSources(array( 'ski_type', 'product_tags', 'grouping_title', 'grouping_identifier', 'image_filenames', ), t('Do Not Migrate')); // Fields in the Product entity to ignore $this->addUnmigratedDestinations(array( 'created', 'changed', 'creator', 'commerce_stock', 'path', 'field_product_code:format', 'field_product_code:language', 'field_brand:source_type', 'field_brand:create_term', 'field_supplier_stock', 'field_supplier_sku:format', 'field_supplier_sku:language', 'field_upc:format', 'field_upc:language', 'field_tags:source_type', 'field_tags:create_term', 'field_description:summary', 'field_description:language', 'field_image:file_class', 'field_image:language', 'field_image:destination_dir', 'field_image:destination_file', 'field_image:preserve_files', 'field_additional_images', 'field_additional_images:file_class', 'field_additional_images:language', 'field_additional_images:destination_dir', 'field_additional_images:destination_file', 'field_additional_images:file_replace', 'field_additional_images:preserve_files', 'field_additional_images:source_dir', 'field_additional_images:alt', 'field_additional_images:title', ), t('Do Not Migrate')); } public function complete($entity, stdClass $row) { if (!$row->grouping_identifier) { return; } $product_id = $entity->product_id; $grouping_id = $row->grouping_identifier; // Check if there is a product display with this grouping identifier $result = db_query('SELECT node.nid AS nid FROM {node} node LEFT JOIN {field_data_field_grouping_identifier} grouping_identifier ON node.nid = grouping_identifier.entity_id WHERE (grouping_identifier.field_grouping_identifier_value = :grouping_id AND node.type = :type)', array( ':grouping_id' => $grouping_id, ':type' => 'product_display')); if ($result->rowCount() == 0) { // No product displays exist. Create one. $this->createProductDisplayEntity($grouping_id, $product_id, $row); } else { // A product display node already exists foreach ($result as $node) { $this->addAnotherProductToDisplay($node->nid, $product_id, $row); } } } /** * Creates a product display node with a specific product referenced */ protected function createProductDisplayEntity($grouping_id, $product_id, $row) { $node = entity_create('node', array('type' => 'product_display')); $wrapper = entity_metadata_wrapper('node', $node); $wrapper->field_grouping_identifier = $grouping_id; $wrapper->field_product_reference = array($product_id); $wrapper->field_individual_colors = explode('||', strtolower($row->individual_colors)); $wrapper->field_gender = explode('||', strtolower($row->gender)); $wrapper->status = $row->status; $wrapper->field_brand = reset($this->getMatchingTids(2, $row->brand)); $tags = $this->getMatchingTids(4, $row->tags); if (count($tags) > 0) { $wrapper->field_tags = $tags; } // Same for every product in group $wrapper->title = $row->grouping_title; $wrapper->field_year = $row->year; $wrapper->save(); // Domains field doesn't seem to have property_info hooks for // entity_metadata_wrapper, so adding via normal node_save $node = $wrapper->value(); // Domain Access information NOW available (after saving the node) // Set the domain visibility based on first product in this group // Domain visibility is set on Product Display node, so no need to // do anything in addAnotherProductToDisplay $node->domains = $this->getMatchingDomains($row->domains); // Default value must ALWAYS be set $default_domain_id = domain_default_id(); if (!array_key_exists($default_domain_id, $node->domains)) { $node->domains[$default_domain_id] = $default_domain_id; } node_save($node); } /** * Adds another product to an existing product display node */ protected function addAnotherProductToDisplay($display_node_id, $product_id, $row) { $wrapper = entity_metadata_wrapper('node', $display_node_id); if ($wrapper->status->value() == 0) { // Only modify the status if it's not currently "published" // because if even one product in this display is published, // we want the whole product display to be published $wrapper->status = $row->status; } // This product's reference $all_product_ids = array(); foreach($wrapper->field_product_reference as $product) { $all_product_ids[] = $product->value()->product_id; } if (!in_array($product_id, $all_product_ids)) { $all_product_ids[] = $product_id; } $wrapper->field_product_reference = $all_product_ids; // This product's tags $all_tags = $this->getMatchingTids(4, $row->tags); foreach($wrapper->field_tags as $tag) { // Store each tid the node already has $all_tags[] = $tag->value()->tid; } if (count($all_tags) > 0) { $wrapper->field_tags = array_unique($all_tags); } // This product's individual colors $all_colors = array(); foreach($wrapper->field_individual_colors as $color) { $all_colors[] = $color->value(); } $wrapper->field_individual_colors = array_unique(array_merge($all_colors, explode('||', strtolower($row->individual_colors)))); // This product's gender $all_genders = array(); foreach($wrapper->field_gender as $gender) { $all_genders[] = $gender->value(); } $wrapper->field_gender = array_unique(array_merge($all_genders, explode('||', strtolower($row->gender)))); $wrapper->save(); } /** * Returns the "key" from a Drupal option (key|value) * * @param $value * A key|value pair string * * @return * The key part of the string (before the pipe) */ protected function getOptionKey($value) { $arr = explode('|', $value); return array_shift(array_values($arr)); } /** * Returns an array of term ids from the Product Tags vocab * * @param $vid * The vocabulary id from which you want matching terms * @param $term_names * A list of term names in the form: Term 1||Term 2||Term 3 * * @return * Array of tids */ function getMatchingTids($vid, $term_names) { $terms = array(); foreach(taxonomy_get_tree($vid) as $term) { $terms[$term->tid] = $term->name; } $matches = array(); foreach(explode('||', $term_names) as $term) { $matches[] = array_search($term, $terms); } return array_unique($matches); } /** * Get the "Domains" array for the domains passed in the domains field * * @param $domain_ids * A list of domain machine names OR ids. (from Domain Access) * e.g., domainx||domainy OR 1||2 * * @return * Array of Domains where keys = domain ID and values = domain ID */ function getMatchingDomains($domain_ids) { $domains = array(); foreach (explode('||', $domain_ids) as $domain_id) { if ($domain = domain_load($domain_id)) { $domains[$domain['domain_id']] = $domain['domain_id']; } if ($domain = domain_machine_name_load($domain_id)) { $domains[$domain['domain_id']] = $domain['domain_id']; } } return $domains; } } /** * Physical Weight field handler * @see <a href="http://drupal.org/node/1626578#comment-6188036">http://drupal.org/node/1626578#comment-6188036</a> */ class MigrateCommercePhysicalWeightFieldHandler extends MigrateFieldHandler { public function __construct() { $this->registerTypes(array('physical_weight')); } static function arguments($unit = NULL) { $arguments = array(); if (!is_null($unit)) { $arguments['unit'] = $unit; } return $arguments; } public function prepare($entity, array $field_info, array $instance, array $values) { $migration = Migration::currentMigration(); $arguments = (isset($values['arguments']))? $values['arguments']: array(); $language = $this->getFieldLanguage($entity, $field_info, $arguments); // Setup the standard Field API array for saving. $delta = 0; foreach ($values as $value) { $unit = isset($arguments['unit']) ? $arguments['unit'] : 'lb'; $return[$language][$delta]['weight'] = $value; $return[$language][$delta]['unit'] = $unit; $delta++; } if (!isset($return)) { $return = NULL; } return $return; } } |
One Comment
Thomas
I know this is an old post, but do you happen to have the all_products.csv file you used for this?
Just learning commerce migrate and trying to get a decent working example.
Thanks!