5

This might provide it's own answer, but I thought I would ask to be sure. How do you reference the current entry in custom fieldType or CP templates? I have tried {{ entry.id }}, {{ element.id }} but neither work. Do you need to explicitly set these variables in your getInputHTML() function?

I see in the craft '_entry.html' template that {{ entry.id }} is used for a hidden field. Since that reference is not available, I assume that template variables are scoped to the template and not inherited by other templates on the same page?

Through trial and error I finally discovered the current entry can be referenced in PHP as $this->element;, and the id and section via $this->element->id, $this->element->section respectively. So, I could add entry as a template variable, but I just assumed it would already be there.

public function getInputHtml($name, $value)
{
    $entry = $this->element;
    return craft()->templates->render('myPlugin/fieldtypes/MyField/input', array(
        'name'          => $name,
        'value'         => $value,
        'entry'         => $entry
    );
}

1 Answer 1

5

As you discovered, you can get the current element that a field type is getting applied to via $this->element. However you must keep in mind that that property will not always be set. So make sure that your PHP/template code is defensive about the possibility that there is no known element yet.

Another assumption to avoid is that the current element is going to be an entry. Craft lets you associate fields with any type of element - entries, users, assets, categories, tags, globals, and Matrix blocks, and even any custom element types that plugins may add. So $this->element->section should be avoided unless you know that $this->element is actually an EntryModel; otherwise that will give you a PHP error.

2
  • Thank you brandon! Those are all great points. I will make sure and update my plugin to test for the element type. When might the element not be known yet? Commented Oct 21, 2014 at 18:15
  • When creating new entries, for example. And sometimes $this->element might be set, but the element doesn’t actually have an ID yet, because it hasn’t been saved, such as when creating a new entry, attempting to save it, but there was a validation error. Commented Oct 21, 2014 at 18:43

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.