/** * {@inheritdoc} */ public function getValueFromProperty(FieldItemListInterface $property, $delta = 0) { if ($property->getValue() && $property->getFieldDefinition()->getCardinality() == 1) { return $property->referencedEntities()[0]; } return $property->referencedEntities(); }
/** * {@inheritdoc} */ public function generateFieldMetadata(FieldItemListInterface $items, $view_mode) { $entity = $items->getEntity(); $field_name = $items->getFieldDefinition()->getName(); // Early-return if user does not have access. $access = $this->accessChecker->accessEditEntityField($entity, $field_name); if (!$access) { return array('access' => FALSE); } // Early-return if no editor is available. $formatter_id = EntityViewDisplay::collectRenderDisplay($entity, $view_mode)->getRenderer($field_name)->getPluginId(); $editor_id = $this->editorSelector->getEditor($formatter_id, $items); if (!isset($editor_id)) { return array('access' => FALSE); } // Gather metadata, allow the editor to add additional metadata of its own. $label = $items->getFieldDefinition()->getLabel(); $editor = $this->editorManager->createInstance($editor_id); $metadata = array('label' => String::checkPlain($label), 'access' => TRUE, 'editor' => $editor_id, 'aria' => t('Entity @type @id, field @field', array('@type' => $entity->getEntityTypeId(), '@id' => $entity->id(), '@field' => $label))); $custom_metadata = $editor->getMetadata($items); if (count($custom_metadata)) { $metadata['custom'] = $custom_metadata; } return $metadata; }
/** * Generates unique ids for the field items. * * @param \Drupal\Core\Field\FieldItemListInterface $items * The field items. * @return array * Array of ids keyed by field item delta. */ protected function generateIds(FieldItemListInterface $items) { $entity = $items->getEntity(); $ids = array(); foreach ($items as $delta => $item) { $ids[$delta] = implode('_', array($entity->getEntityTypeId(), $entity->bundle(), $entity->id(), $items->getFieldDefinition()->getName(), $delta)); } return $ids; }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $main_widget = $element + array('#type' => 'textfield', '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL, '#placeholder' => $this->getSetting('placeholder'), '#attributes' => array('class' => array('geocoder-source'))); $element['value'] = $main_widget; $source_field_id = 'edit-' . str_replace('_', '-', $items->getFieldDefinition()->getName()) . '-' . $delta . '-value'; $destination_field_id = 'edit-' . str_replace('_', '-', $this->getSetting('destination_field')) . '-wrapper'; $google_api_key = \Drupal::config('geocoder.google')->get('api_key'); $element['#attached'] = array('library' => array(array('system', 'jquery.ui.autocomplete')), 'js' => array('sites/all/libraries/geocoder-js/dist/geocoder.js', drupal_get_path('module', 'geocoder') . '/js/geocoderWidget.js', array('data' => array('geocoder' => array('engine' => 'google', 'api_key' => $google_api_key, 'fields' => array(array('sourceField' => $source_field_id, 'destinationField' => $destination_field_id, 'sourceType' => 'geofield')))), 'type' => 'setting'))); return $element; }
/** * {@inheritdoc} */ public function isCompatible(FieldItemListInterface $items) { $field_definition = $items->getFieldDefinition(); // This editor is incompatible with multivalued fields. if ($field_definition->getFieldStorageDefinition()->getCardinality() != 1) { return FALSE; } elseif (in_array($field_definition->getType(), array('text', 'text_long', 'text_with_summary'), TRUE)) { return FALSE; } else { return TRUE; } }
/** * {@inheritdoc} * * @todo The processed text logic is too coupled to text fields. Figure out * how to generalize to other textual field types. */ public function isCompatible(FieldItemListInterface $items) { $field_definition = $items->getFieldDefinition(); // This editor is incompatible with multivalued fields. if ($field_definition->getFieldStorageDefinition()->getCardinality() != 1) { return FALSE; } elseif ($field_definition->getSetting('text_processing')) { return FALSE; } else { return TRUE; } }
/** * {@inheritdoc} */ public function isCompatible(FieldItemListInterface $items) { $field_definition = $items->getFieldDefinition(); // This editor is incompatible with multivalued fields. if ($field_definition->getFieldStorageDefinition()->getCardinality() != 1) { return FALSE; } // This editor is compatible with formatted ("rich") text fields; but only // if there is a currently active text format and that text format is the // 'full_html' text format. return $items[0]->format === 'full_html'; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = []; // As the Field API only applies the "field default value" to newly created // entities, we'll apply the default value for existing entities. if ($items->count() == 0) { $field_default_value = $items->getFieldDefinition()->getDefaultValue($items->getEntity()); $items->status = $field_default_value[0]['status']; } if ($items->status == 1 && $this->currentUser->hasPermission('view disqus comments')) { $element[] = ['#type' => 'disqus', '#url' => $items->getEntity()->toUrl('canonical', ['absolute' => TRUE])->toString(), '#title' => (string) $items->getEntity()->label(), '#identifier' => $items->identifier ?: "{$items->getEntity()->getEntityTypeId()}/{$items->getEntity()->id()}"]; } return $element; }
/** * {@inheritdoc} */ public function isCompatible(FieldItemListInterface $items) { $field_definition = $items->getFieldDefinition(); // This editor is incompatible with multivalued fields. if ($field_definition->getFieldStorageDefinition()->getCardinality() != 1) { return FALSE; } elseif ($editor = editor_load($items[0]->format)) { $definition = \Drupal::service('plugin.manager.editor')->getDefinition($editor->getEditor()); if ($definition['supports_inline_editing'] === TRUE) { return TRUE; } } return FALSE; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $elements = array(); // Only collect allowed options if there are actually items to display. if ($items->count()) { $provider = $items->getFieldDefinition()->getFieldStorageDefinition()->getOptionsProvider('value', $items->getEntity()); // Flatten the possible options, to support opt groups. $options = OptGroup::flattenOptions($provider->getPossibleOptions()); foreach ($items as $delta => $item) { $value = $item->value; // If the stored value is in the current set of allowed values, display // the associated label, otherwise just display the raw value. $output = isset($options[$value]) ? $options[$value] : $value; $elements[$delta] = array('#markup' => $output, '#allowed_tags' => FieldFilteredMarkup::allowedTags()); } } return $elements; }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { // Get easychart entity field values. $field_name = $items->getFieldDefinition()->getName(); $entity = $items->getEntity(); $values = $entity->get($field_name)->getValue(); $config = \Drupal::config('easychart.settings'); $settings = ['easychartOptions' => $config->get('options'), 'easychartTemplates' => $config->get('templates'), 'easychartPresets' => $config->get('presets')]; // Attach settings and libraries to render array. $element['#attached']['drupalSettings']['easychart'] = $settings; $element['#attached']['library'][] = 'easychart/easychart.widget'; $element['#attached']['library'][] = 'easychart/lib.highcharts'; $element['#attached']['library'][] = 'easychart/lib.easycharts.full'; $element['container'] = array('#prefix' => '<div class="easychart-wrapper clearfix entity-meta">', '#suffix' => '</div>', '#type' => 'container', '#attributes' => array('class' => array('entity-meta__header clearfix'), 'style' => array('padding:0;'))); $element['container']['config'] = array('#description' => $this->t('The configuration options as described at http://api.highcharts.com/highcharts'), '#type' => 'hidden', '#default_value' => isset($values[$delta]['config']) ? $values[$delta]['config'] : NULL, '#attributes' => array('class' => array('easychart-config'))); $element['container']['csv'] = array('#type' => 'hidden', '#description' => $this->t('Your chart data in CSV format'), '#default_value' => isset($values[$delta]['csv']) ? $values[$delta]['csv'] : NULL, '#attributes' => array('class' => array('easychart-csv')), '#element_validate' => array(array(get_called_class(), 'validateCSVElement')), '#csv_required' => $element['#required']); $element['container']['csv_url'] = array('#type' => 'hidden', '#description' => $this->t('The URL to a CSV file'), '#default_value' => isset($values[$delta]['csv_url']) ? $values[$delta]['csv_url'] : NULL, '#attributes' => array('class' => array('easychart-csv-url'))); $element['container']['preview'] = array('#title' => $this->t('Easychart'), '#markup' => '', '#prefix' => '<div class="easychart-embed">', '#suffix' => '</div>'); return $element; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $element = array(); // If there are no images, don't do anything else. if ($items->isEmpty()) { return array(); } $entity = $items->getEntity(); $field_instance = $items->getFieldDefinition(); $entity_type_id = $entity->getEntityTypeId(); $entity_id = $entity->id(); $field_name = $field_instance->getName(); $display_name = $this->viewMode; $add_js = TRUE; // Check for incompatible view modes - see issue #2217791 if ($display_name == 'search_result' || $display_name == 'search_index') { $add_js = FALSE; } // The gallery shown in preview view will only display field data from the // previously saved version (that is the only version the XML generation // methods will have access to). Display a warning because of this. if (!empty($entity->in_preview)) { drupal_set_message(t('Juicebox galleries may not display correctly in preview mode. Any edits made to gallery data will only be visible after all changes are saved.'), 'warning', FALSE); } // Generate xml details. $xml_route_info = array('route_name' => 'juicebox.xml_field', 'route_parameters' => array('entityType' => $entity_type_id, 'entityId' => $entity_id, 'fieldName' => $field_name, 'displayName' => $display_name), 'options' => array('query' => $this->request->query->all())); // Try building the gallery and its XML. try { // Initialize the gallery. $gallery = $this->juicebox->newGallery($xml_route_info['route_parameters']); // Build the gallery. $this->buildGallery($gallery, $items); // Build field-specific contextual links. $contextual = $this->buildContextualLinks($xml_route_info, $entity_type_id); // Create a render array with the gallery markup. $element[0] = $this->juicebox->buildEmbed($gallery, $this->getSettings(), $xml_route_info, $add_js, $this->isPseudoInstance(), $contextual); } catch (\Exception $e) { $message = 'Exception building Juicebox embed code for field: !message in %function (line %line of %file).'; watchdog_exception('juicebox', $e, $message); } return $element; }
/** * {@inheritdoc} */ public function viewField(FieldItemListInterface $items, $display_options = array()) { $entity = $items->getEntity(); $field_name = $items->getFieldDefinition()->getName(); $display = $this->getSingleFieldDisplay($entity, $field_name, $display_options); $output = array(); $build = $display->build($entity); if (isset($build[$field_name])) { $output = $build[$field_name]; } return $output; }
/** * {@inheritdoc} */ public function viewField(FieldItemListInterface $items, $display_options = array()) { $output = array(); $entity = $items->getEntity(); $field_name = $items->getFieldDefinition()->getName(); // Get the display object. if (is_string($display_options)) { $view_mode = $display_options; $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode); foreach ($entity as $name => $items) { if ($name != $field_name) { $display->removeComponent($name); } } } else { $view_mode = '_custom'; $display = entity_create('entity_view_display', array('targetEntityType' => $entity->getEntityTypeId(), 'bundle' => $entity->bundle(), 'mode' => $view_mode, 'status' => TRUE)); $display->setComponent($field_name, $display_options); } $build = $display->build($entity); if (isset($build[$field_name])) { $output = $build[$field_name]; } return $output; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { $elements = array(); $entity = $items->getEntity(); $field_instance = $items->getFieldDefinition(); $entity_type_id = $entity->getEntityTypeId(); $entity_id = $entity->id(); $field_name = $field_instance->getName(); $display_name = $this->viewMode; $files = $this->getEntitiesToView($items, $langcode); $settings = $this->getSettings(); // Early opt-out if the field is empty. if (empty($files)) { return $elements; } $url = NULL; $image_link_setting = $this->getSetting('image_link'); // Check if the formatter involves a link. if ($image_link_setting == 'content') { $entity = $items->getEntity(); if (!$entity->isNew()) { $url = $entity->urlInfo(); } } elseif ($image_link_setting == 'file') { $link_file = TRUE; } $image_style_setting = $this->getSetting('image_style'); // Collect cache tags to be added for each item in the field. $cache_tags = array(); if (!empty($image_style_setting)) { $image_style = $this->imageStyleStorage->load($image_style_setting); $cache_tags = $image_style->getCacheTags(); } foreach ($files as $delta => $file) { if (isset($link_file)) { $image_uri = $file->getFileUri(); $url = Url::fromUri(file_create_url($image_uri)); } $cache_tags = Cache::mergeTags($cache_tags, $file->getCacheTags()); // Extract field item attributes for the theme function, and unset them // from the $item so that the field template does not re-render them. $item = $file->_referringItem; $item_attributes = $item->_attributes; unset($item->_attributes); $elements[$delta] = array('#theme' => 'image_jssor_formatter', '#item' => $item, '#item_attributes' => $item_attributes, '#image_style' => $image_style_setting, '#caption' => $this->getSetting('caption'), '#url' => $url, '#settings' => $settings, '#cache' => array('tags' => $cache_tags)); } $container = array('#theme' => 'images_jssor_formatter', '#children' => $elements, '#settings' => $settings, '#attributes' => array('class' => array('slider'), 'id' => array('slider-dom-id-1'))); // Attach library. $container['#attached']['library'][] = 'jssor/jquery.jssor.slider'; $settings = []; // ID. // @todo generate random ? $settings['view_dom_id'] = '1'; // Global settings. $settings['$ArrowKeyNavigation'] = TRUE; // Arrow navigator. if ($this->getSetting('arrownavigator')) { $settings['$ArrowNavigatorOptions'] = array('$Class' => '$JssorArrowNavigator$', '$ChanceToShow' => 1, '$AutoCenter' => 2, '$Scale' => TRUE); } // Bullet navigator. if ($this->getSetting('bulletnavigator')) { $settings['$BulletNavigatorOptions'] = array('$Class' => '$JssorBulletNavigator$', '$ChanceToShow' => 2, '$AutoCenter' => 1, '$Scale' => TRUE); } // Attach settings. $container['#attached']['drupalSettings']['views']['jssorViews'][] = $settings; return $container; }
/** * Process a field. * * @param \Drupal\Core\Field\FieldItemListInterface $field * @param string $op * @param boolean $force if set, we don't check if encryption is enabled, we process the field anyway. This is used during batch processes. */ protected function process_field(\Drupal\Core\Field\FieldItemListInterface $field, $op = 'encrypt', $force = FALSE) { if (!is_callable([$field, 'getFieldDefinition'])) { return; } /** * @var $definition \Drupal\Core\Field\BaseFieldDefinition */ $definition = $field->getFieldDefinition(); if (!is_callable([$definition, 'get'])) { return; } $field_type = $definition->get('field_type'); /** * Filter out fields that do not have a defined map. */ if (!in_array($field_type, array_keys($this->getFieldEncryptMap()))) { return; } /** * @var $storage \Drupal\Core\Field\FieldConfigStorageBase */ $storage = $definition->get('fieldStorage'); if (is_null($storage)) { return; } /** * If we are using the force flag, we always proceed. * The force flag is used when we are updating stored fields. */ if (!$force) { /** * Check if we are updating the field, in that case, skip it now (during * the initial entity load. */ if ($this->updatingStoredField === $definition->get('field_name')) { return; } // Check if the field is encrypted. $encrypted = $storage->getThirdPartySetting('field_encrypt', 'encrypt', FALSE); if (!$encrypted) { return; } } /** * @var $field \Drupal\Core\Field\FieldItemList */ $field_value = $field->getValue(); foreach ($field_value as &$value) { // Process each of the sub fields that exits. $map = $this->fieldEncryptMap[$field_type]; foreach ($map as $value_name => $service) { if (isset($value[$value_name])) { $value[$value_name] = $this->process_value($value[$value_name], $service, $op); } } } // Set the new value. // We don't need to update the entity because the field setValue does that already. $field->setValue($field_value); }
/** * {@inheritdoc} */ public function isCompatible(FieldItemListInterface $items) { $field_definition = $items->getFieldDefinition(); // This editor is incompatible with multivalued fields. return $field_definition->getFieldStorageDefinition()->getCardinality() == 1; }
/** * {@inheritdoc} */ public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) { $parents = $form['#parents']; // Identify the manage field settings default value form. if (in_array('default_value_input', $parents, TRUE)) { // Since the entity is not reusable neither cloneable, having a default // value is not supported. return ['#markup' => $this->t('No widget available for: %label.', ['%label' => $items->getFieldDefinition()->getLabel()])]; } return parent::form($items, $form, $form_state, $get_delta); }