Skip to content

Instantly share code, notes, and snippets.

@seutje
Created August 31, 2016 13:51
Show Gist options
  • Save seutje/fed6b6ab59d7c8c627c4863e5f062e6c to your computer and use it in GitHub Desktop.
Save seutje/fed6b6ab59d7c8c627c4863e5f062e6c to your computer and use it in GitHub Desktop.
Field clone example, doesn't work with actual DS fields that aren't on the entity.
<?php
/**
* @file
* DS field clone base.
*/
namespace Drupal\mymodule;
use Drupal\ds\Plugin\DsField\DsFieldBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Abstract class to serve as a base for field clones.
*/
abstract class FieldCloneBase extends DsFieldBase {
/**
* Entity manager.
*
* @var EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Field to clone.
*
* @var (string)
*/
protected $field;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->field = FALSE;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.manager')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$room = $this->entity();
$config = $this->getConfiguration();
$viewBuilder = $this->entityTypeManager->getViewBuilder('node');
$output = FALSE;
if ($this->field !== FALSE) {
$field = $room->{$this->field};
$output = $viewBuilder->viewField($field, $config['view_mode']);
}
return $output;
}
}
<?php
/**
* @file
* DS price field clone.
*/
namespace Drupal\mymodule\Plugin\DsField;
use Drupal\mymodule\FieldCloneBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Plugin that renders a clone of a field.
*
* @DsField(
* id = "mymodule_some_field_clone",
* title = @Translation("DS Field: Some field clone"),
* entity_type = "node",
* provider = "mymodule",
* ui_limit = { "room|*"}
* )
*/
class SomeFieldClone extends FieldCloneBase {
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->field = 'field_some_field';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment