Skip to content

Instantly share code, notes, and snippets.

@arildm
Created April 14, 2016 07:05
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 arildm/12bcfe44e62763ad9a9e25cbfd015321 to your computer and use it in GitHub Desktop.
Save arildm/12bcfe44e62763ad9a9e25cbfd015321 to your computer and use it in GitHub Desktop.
<?php
/**
* @file
* Contains \Drupal\mymodule\Feeds\Target\EntityReferenceDefaultValue.
*/
namespace Drupal\mymodule\Feeds\Target;
use Drupal\Core\Form\FormStateInterface;
use Drupal\feeds\Exception\EmptyFeedException;
use Drupal\feeds\Feeds\Target\EntityReference;
/**
* Decorates the entity reference target with a default value field.
*
* @FeedsTarget(
* id = "mymodule_entity_reference",
* field_types = {"entity_reference"},
* arguments = {"@entity.manager", "@entity.query"}
* )
*/
class EntityReferenceDefaultValue extends EntityReference {
/**
* {@inheritdoc}
*/
protected function prepareValue($delta, array &$values) {
try {
parent::prepareValue($delta, $values);
}
catch (EmptyFeedException $e) {
if (!empty($this->configuration['default_value'])) {
$values['target_id'] = $this->configuration['default_value'];
return;
}
}
throw new EmptyFeedException('No default value');
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
'default_value' => NULL,
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['default_value'] = [
'#type' => 'textfield',
'#title' => $this->t('Default target id'),
'#description' => $this->t('This target id is used if there is no result.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function getSummary() {
$summary = [parent::getSummary()];
if (!empty($this->configuration['default_value'])) {
$summary[] = $this->t('Default target id: ' . $this->configuration['default_value']);
}
return implode('<br>', $summary);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment