0

I'm making a custom module with a form controller, that has a text_format field. I'm storing the text_format value in my submitForm function like so.

public function submitForm(array&$form, FormStateInterface $form_state) {
    $this->config('foundation.settings')
         ->set('infoblock_text', $form_state->getValue('infoblock_text'))
        ->save();
}

I'm attempting to retrieve that for the default value of the field like so

    $form['infoblock_text'] = [
        '#type'          => 'text_format',
        '#title'         => t('Infoblock text'),
        '#description'   => t('The body text for the infoblock on the front page'),
        '#format'        => 'full_html',
        '#default_value' => $config->get('infoblock_text'),
    ];

However it's empty. After performing a die(print_r($config->get('infoblock_text'))) I found that infoblock_text is actually an array and 'value' is the key that contains the text I need. This is what the die() statement returns

Array ( [value] =>
Text of infoblock
[format] => full_html ) 1

After seeing that I actually needed to retrieve the value element rather the entire array I attempted the following with no luck.

$config->get('infoblock_text', 'value');
$config->get(['infoblock_text', 'value']);
$config->get('infoblock_text')->value;
$config->get('infoblock_text')->value();
$config->get('infoblock_text')->getValue();
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');

So how would I actually retrieve the value of 'infoblock_text', when $config->get('infoblock_text') returns the entire array?

2

You can handle the config like an array:

$form['infoblock_text'] = [
    '#type'          => 'text_format',
    '#title'         => t('Infoblock text'),
    '#description'   => t('The body text for the infoblock on the front page'),
    '#format'        => isset($config->get('infoblock_text')['format']) ? $config->get('infoblock_text')['format'] : 'full_html',
    '#default_value' => isset($config->get('infoblock_text')['value']) ? $config->get('infoblock_text')['value'] : '',
];

When accessing the array like this, it's always a good idea to check if the key is set. This avoids warnings in your log.

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.