2

I've built a custom field that stores its data in its own table. How can I get data from MyCustomField to show up as a column in the Entries Table?

A few details:

  • My custom field is made up of multiple fields, in this case a Date/Time field and a text field.
  • My custom field is is returned as an array by the prepValue() function in my fieldtype file.
  • Not every entry will have a record in my custom field's table

How can I check to see if a value exists in my custom field's table for an entry and display it in the Entries Table?

I'm copying this over from the Craft Slack channel so we don't lose the solution.

1 Answer 1

4

It will take two hooks in the MyCustomPlugin.php file to display data from the custom field.

public function modifyEntryTableAttributes(&$attributes, $source)
{
    if ($source == '*')
    {
        unset($attributes['expiryDate']);
        $attributes['whatever-you-want'] = Craft::t('Desired Table Heading');
    }
}

The modifyEntryTableAttributes() hook will allow us to add/remove columns from the Entries Listing table. Note that the $attributes[] variable will automatically try to match up whatever you put in there with an attribute on the entries.

This is probably all you need to drop a standard custom field into the table. However, since my custom field is an array, holding multiple bits of data, we need to use the getEntryTableAttributes() hook to dig in to my custom field and grab the item we want to display.

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    if ($attribute == 'whatever-you-want')
    {
        // Assign my custom field to a variable
        $fieldData = $entry->mycustomfield;

        // Check if there is any data in the variable
        if (!empty($fieldData)) {

            // If so, return the specific key AS A STRING to the table
            return $fieldData['myCustomDate']->format('n/j/y');
        }

        return '';
    }
}

Notice the return ''; at the end? That's important, because if an entry DOESN'T have my custom field attached to it, it will try to look up the $attribute['whatever-you-want'] assuming that's a legitimate DB column, and will fail.

1

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.