I create a new filed type and attached it to entries. Now I need to get the entry id which the field is attached to.
I tried $this->element
in my field class, but got an error said that I'm calling an unknown property.
Any way to do that please?
It may depend on where in the request you need to access the element.
If you need to access the element in a Field class on your Entry Edit page, the getInputHtml
method may be useful:
public function getInputHtml($value, ElementInterface $element = null): string
{
// $element stuff
return Craft::$app->getView()->renderTemplate('my-plugin/field',
[
'field' => $this,
// make the Element available in your field's input template
'element' => $element
]);
}
If you need to access the element in a Field class after the Element is saved there is the afterSaveElement method:
public function afterElementSave(ElementInterface $element, bool $isNew)
{
parent::afterElementSave($element, $isNew);
// $element stuff
}
Note: The Entry ID may not exist while a new entry is being created. Accessing the Element via the afterElementSave
ensures that the Entry has been saved and has an ID.
getInputHtml
method Robin mentions as well.
Commented
Jun 6, 2018 at 13:35
getInputHtml
do. Maybe I didn't make myself clear. Basically there are two Asset field types: A and B. Let's say a user selected three images to A, Ctrl+s to save and then he can only select these three images to B. The field B is what I want to create. afterElementSave
has the limit which is users have to save to trigger this function.
getInputHtml
. But I have to rewrite the template in this function which is gonna take too much effort
Way one:
Inside the field class, there is a inputTemplateVariables
function with two params, like this
protected function inputTemplateVariables($value = null, ElementInterface $element = null): array
{
$vars = parent::inputTemplateVariables($value, $element);
$settings = $this->getSettings();
//here you can get element
$entryId = $element->id;
return $vars;
}
Way two:
In your plugin's main file, put codes below into init()
function
Craft::$app->getView()->hook('cp.entries.edit.details', function (&$context)
{
//here you can also get the element id
//you can save it into session and use it anywhere you need
$id = $context['entry']['id'];
});