Skip to content

Instantly share code, notes, and snippets.

@socketwench
Created March 6, 2018 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save socketwench/557cdaf262bdc03cb4d1929111aa1d31 to your computer and use it in GitHub Desktop.
Save socketwench/557cdaf262bdc03cb4d1929111aa1d31 to your computer and use it in GitHub Desktop.
Drupal 8 migration source to pull a node if a field is set or not
<?php
namespace Drupal\my_migrate_common\Plugin\migrate\source;
use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d7\Node as D7_Node;
/**
* Source for node content depending on if a field is set or not.
*
* Use:
*
* ```yaml
* source:
* plugin: my_node_with_field
* field: field_to_split_on
* # Use present: true to pull nodes with the field populated, false for field empty.
* present: true
* # See core's node source for how these work:
* node_type: source_node_type
* translations: false
* ```
*
* @MigrateSource(
* id = "my_node_with_field"
* )
*/
class MyNodeWithField extends D7_Node {
public function query() {
$query = parent::query();
if (!empty($this->configuration['field'])) {
// We can't inner join as field data may have multiple rows per entity.
// Instead, we're going to use a subquery with distinct.
$subquery = $this->select('field_data_' . $this->configuration['field'], 'f')
->fields('f', [
'entity_id'
])
->distinct();
$operator = 'IN';
if (isset($this->configuration['present']) && $this->configuration['present'] == FALSE) {
$operator = 'NOT IN';
}
$query->condition('n.nid', $subquery, $operator);
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment