Created
April 14, 2016 07:05
-
-
Save arildm/12bcfe44e62763ad9a9e25cbfd015321 to your computer and use it in GitHub Desktop.
Solution to https://www.drupal.org/node/2706057
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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