0

I try to add a text area with wysiwyg editor in the theme setting.

If i use '#type' => 'textfield', it works :

enter image description here

If I use '#type' => 'text_format', the text is saved but i don’t see it as default value :

enter image description here

If I revert back to '#type' => 'textfield', i can see this :

enter image description here

I guess it is related to the text_format form which is stored as an array ?

How can I use text_format in theme settings ?

Full code in mytheme.theme

function MYTHEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {

  $form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => theme_get_setting('mytheme_texte_presentation'),
    '#description'   => t("lorem ipsum"),
  );
}
3

Text format fields are considered to be a compound field (meaning that multiple values are stored for the one field -- the value and the format).

If you inspect the value of mytheme_texte_presentation, you'll find an array that looks something like this array => ['value' => '<val>', 'format' => 'html_restreint'].

If you look at the docs for text_format, you'll see that there is a #format attribute.

Your code should look something like this:

$texte_presentation = theme_get_setting('mytheme_texte_presentation');
$form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => $texte_presentation['value'],
    '#format'        => $texte_presentation['format'],
    '#description'   => t("lorem ipsum"),
  );

Note: This is untested code. You may need to tweak this a bit to make it functional.

  • Thank you. I understand how it works now. I should have dumped all the variables before asking. The array theme_get_setting('mytheme_texte_presentation') was correct but i had a PHP error and $texte_presentation['value'] was null. – Sébastien Gicquel Jan 3 '18 at 0:47
  • Awesome! Glad you got things sorted. If you provide the correct format, I'll update my answer for anyone who finds this in the future. – lukedekker Jan 3 '18 at 21:27
  • How do you then display this in your twig template? – Randell Aug 22 '18 at 0:32
  • It shouldn't be necessary. Drupal will automatically render all of the form elements. Manually rendering it via the template is just asking for trouble. – lukedekker Aug 23 '18 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.