4

I'm trying to import data from another database into a 'table' fieldtype via a plugin, and have a couple questions.

When setting the content on the EntryModel, are there any methods to assist in setting the rows and/or columns, or do I need to just format the data as a string in the expected format?

    $entry->getContent()->setAttributes(array(
        'tableFieldHandle' => '[{"col1":"data","col2":"data"}]'
    ));

Secondly, what's the recommended method to prepare strings for a table field (i.e. so as to escape or encode double and single quotes)?

1 Answer 1

7

The thing to keep in mind here is that a table field contains a simple JSON string. So you can (and should) use PHP's native json_encode function to prepare your data...

// Your data will be an array of arrays:
$tableData = array(
    array(
        "col1" => "data",
        "col2" => "data",
    )
);

// Then simply encode it when you set your field value:
$entry->getContent()->setAttributes(array(
    'tableFieldHandle' => json_encode($tableData)
));

This will also solve any string escaping concerns for you!

2
  • That makes total sense. Thank you Lindsey! Commented Feb 1, 2015 at 4:08
  • Just incase anyone else stumbles on to this - You actually have to use "col1" etc and not the handle of your column... Commented Mar 10, 2020 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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