Search code examples
silverstripesilverstripe-4

How to display formatted HTML in GridField DataColumn in Silverstripe 4


We have an object which has two fields - one is Text, the other is HTMLText:

private static $db = [
    'Question' => 'Varchar(255)',
    'Answer' => 'HTMLText'
];

We are referencing this object in a Gridfield using DataColumns:

$questionsGrid = GridField::create(
  'Questions', 'Questions', 
  $this->Questions(), 
  GridFieldConfig_RelationEditor::create()
);

$dataColumns = $questionsGrid->
  getConfig()->getComponentByType(GridFieldDataColumns::class);

$dataColumns->setDisplayFields([
        'Question' => 'Question',
        'Answer' => 'Answer'
    ]);
    $dataColumns->setFieldCasting([
        'Question' => 'Text',
        'Answer' => 'HTMLText'
    ]);

Yet the Answer column is displayed as raw HTML - with visible tags & no formatting.

<p>The answer to life the universe & everything is 42.</p><p>A second paragraph for good measure.</p>

How do we display the Answer column as formatted HTML?


Solution

  • You can use 'HTMLFragment->RAW' for that column

    $dataColumns->setFieldCasting([
        'Question' => 'Text',
        'Answer' => 'HTMLFragment->RAW'
    ]);