User login

Setting text format per field in Drupal 8

UPDATE: There is a contributed Drupal 8 module to set allowed formats that was spun off of the core issue to allow text field to enforce a specific text format.

Right now, there's no good way to do it, but there's good hope that this issue will be fixed in Drupal 8 core. OK but right now? Better Formats isn't stable for Drupal 8 yet. So hacky custom form alters is the best i've come up with.

<?php
/**
 * Implements hook_form_alter().
 *
 * Make project details paragraph text fields use only "Simple HTML" text format.
 */
function example_form_alter(&$form, $form_state, $form_id) {
  if (
$form_id !== 'node_work_form' && $form_id !== 'node_page_form') {
    return;
  }
  if (isset(
$form['field_paragraphs']['widget'][0]['subform'])) {
   
$paragraph_widget =& $form['field_paragraphs']['widget'];
   
$key = 0;
    while (isset(
$paragraph_widget[$key]['subform'])) {
      if (!isset(
$paragraph_widget[$key]['subform']['#process'][0][0])
          ||
$paragraph_widget[$key]['subform']['#process'][0][0]->getTargetBundle() != 'project_details') {
       
$key++;
        continue;
      }
     
$fields = array(
       
'field_clients',
       
'field_partners',
       
'field_team',
       
'field_location',
      );
      foreach (
$fields as $field) {
       
$paragraph_widget[$key]['subform'][$field]['widget'][0]['#allowed_formats'] = array('simple_html');
      }
     
$key++;
    }
  }
}
?>
Searched words: 
drupal 8 set text format per field

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.