Skip to content

Instantly share code, notes, and snippets.

@gormus
Created October 20, 2016 05:40
Show Gist options
  • Select an option

  • Save gormus/41a27519e9f870f32d88a9afcfe6e32a to your computer and use it in GitHub Desktop.

Select an option

Save gormus/41a27519e9f870f32d88a9afcfe6e32a to your computer and use it in GitHub Desktop.
Improve user experience with Paragraphs on Drupal 8 - Modify the label of paragraph components - source: http://flocondetoile.fr/blog/improve-user-experience-paragraphs-drupal-8
<?php
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form_object = $form_state->getFormObject();
// Paragraphs are only set on ContentEntityForm object.
if (!$form_object instanceof ContentEntityForm) {
return;
}
/** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
$entity = $form_object->getEntity();
// We check that the entity fetched is fieldable.
if (!$entity instanceof FieldableEntityInterface) {
return;
}
// Check if an entity reference revision field is attached to the entity.
$field_definitions = $entity->getFieldDefinitions();
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
foreach ($field_definitions as $field_name => $field_definition) {
if ($field_definition instanceof FieldConfigInterface && $field_definition->getType() == 'entity_reference_revisions') {
// Fetch the paragrahs entities referenced.
$entities_referenced = $entity->{$field_name}->referencedEntities();
/** @var \Drupal\Core\Entity\FieldableEntityInterface $entity_referenced */
foreach ($entities_referenced as $key => $entity_referenced) {
$fields = $entity_referenced->getFieldDefinitions();
$title = '';
$text = '';
foreach ($fields as $name => $field) {
if ($field instanceof FieldConfigInterface && $field->getType() == 'string') {
if (strpos($name, 'title') !== FALSE) {
$title = $entity_referenced->{$name}->value;
}
// Fallback to text string if no title field found.
elseif (strpos($name, 'text') !== FALSE) {
$text = $entity_referenced->{$name}->value;
}
}
}
// Fallback to $text if $title is empty.
$title = $title ? $title : $text;
// Override paragraph label only if a title has been found.
if ($title) {
$title = (strlen($title) > 50) ? substr($title, 0, 50) . ' (...)' : $title;
$form[$field_name]['widget'][$key]['top']['paragraph_type_title']['info']['#markup'] = '<strong>' . $title . '</strong>';
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment