Skip to content

Instantly share code, notes, and snippets.

@brianjhanson
Created June 15, 2017 18:01
Show Gist options
  • Save brianjhanson/fd8fd1f63c0c96615852e166be767837 to your computer and use it in GitHub Desktop.
Save brianjhanson/fd8fd1f63c0c96615852e166be767837 to your computer and use it in GitHub Desktop.
Importing Categories, Matrix fields and Super Table fields with Craft Import
<?php
/**
* Modify data just before importing
*
* @param BaseElementModel $element The current element receiving import data.
* @param array $map Mapping of data between CSV -> Craft fields.
* @param array $data Raw data provided for this row.
*/
public function modifyImportRow($element, $map, $data)
{
// Map data to fields
$fields = array_combine($map, $data);
$categoryCriteria = craft()->elements->getCriteria(ElementType::Category);
$categoryCriteria->limit(1);
// Initialize content array
$content = array();
// Arrange your content in a way that makes sense for your plugin
foreach ($fields as $handle => $value) {
BelgraviaLogicPlugin::Log('Saving $content['.$handle.'] = '.$value, LogLevel::Info);
$locationIdx = 1;
// Handle neighborhood info
switch ($handle) {
case 'neighborhood':
// Need to lookup the ID of our category,
$categoryCriteria = craft()->elements->getCriteria(ElementType::Category);
$categoryCriteria->limit(1);
$categoryCriteria->group = 'neighborhood';
$categoryCriteria->title = $value;
$category = $categoryCriteria->first();
if (count($category) != 0) {
$content[$handle][] = $category->id;
}
continue;
case 'state':
$content[$handle] = strtolower($value);
continue;
case 'developmentType':
$categoryCriteria->group = 'developmentType';
$categoryCriteria->title = $value;
$type = $categoryCriteria->first();
if (count($type) != 0) {
$content[$handle][] = $type->id;
} else {
$content[$handle][] = 80; // Set to "Residential by default"
}
continue;
case 'mainContent':
// Handle our body matrix field
$content[$handle]['new1']['type'] = 'richText';
$content[$handle]['new1']['enabled'] = '1';
$content[$handle]['new1']['fields']['body'] = $value;
continue;
case 'location':
$content[$handle]['new'.$locationIdx]['type'] = '7';
$content[$handle]['new'.$locationIdx]['fields']['location'] = $value;
$locationIdx++;
continue;
default:
$content[$handle] = $value;
continue;
}
}
// Set modified content
$element->setContentFromPost($content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment