BaronGrivet
BaronGrivet

Reputation: 4424

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?

Upvotes: 2

Views: 449

Answers (2)

theruss
theruss

Reputation: 1746

If you want to modify a method on a DataObject subclass being rendered as a row in a GridField to achieve the same thing, you simply cast it as HTMLText:

    /**
     * @return HTMLText
     */
    public function ImageNice(): \HTMLText
    {
        $image = '<img src="/path/to/foo.png" />';
        return \DBField::create_field(\HTMLText::class, $image);
    }

Upvotes: 0

Michal Kleiner
Michal Kleiner

Reputation: 126

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

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

Upvotes: 4

Related Questions