ComputedFieldItemTrait.php in Computed Field 3.x
File
src/Plugin/Field/FieldType/ComputedFieldItemTrait.php
View source
<?php
namespace Drupal\computed_field\Plugin\Field\FieldType;
use Drupal\Core\Form\FormStateInterface;
trait ComputedFieldItemTrait {
public function isEmpty() {
$value = $this
->getRawResult();
if ($value === NULL || $value === '') {
return TRUE;
}
return FALSE;
}
protected function getRawResult() {
return $this
->executeCode();
}
public function preSave() {
$value = $this
->executeCode();
$this
->setValue($value);
}
public function executeCode() {
$entity = $this
->getEntity();
$delta = $this->name;
$field_name = $this->definition
->getFieldDefinition()
->getName();
$value = \Drupal::service('computed_field.helpers')
->executeCode($field_name, $entity, $delta);
return $value;
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$field_name = $this->definition
->getFieldDefinition()
->getName();
$service = \Drupal::service('computed_field.helpers');
$element = [];
$element['hook_info'] = [
'#markup' => t('
<p>The hook implementation function signature should be
<strong>%function($entity_type_manager, $entity, $fields, $delta)</strong>,
and the desired value should be returned.</em>
</p>
<p>The variables available to your code include:</p>
<ul>
<li><code>$entity_type_manager</code>: The entity type manager.</li>
<li><code>$entity</code>: The entity the field belongs to.</li>
<li><code>$fields</code>: The list of fields available in this entity.</li>
<li><code>$delta</code>: Current index of the field in case of multi-value computed fields (counting from 0).</li>
<li><code>$value</code>: The resulting value to be set above, or returned in your hook implementation).</li>
</ul>
', [
'%function' => $service
->getComputeFunctionName($field_name),
]),
];
return $element;
}
}