nova-flexible-content
nova-flexible-content copied to clipboard
Access resource within custom layout
Hi I've created a custom layout to use the media library. But when do so I lost my resource data ($this->id) How can I access this within the custom layout?
Hi @justkidding96, I'm not sure what your issue is. Can you elaborate ?
@toonvandenbos Sorry for the unclear explanation. What I mean is the following. So I have created a custom layout like below and in it I want to access the resource. After a long time of trying, I finally succeeded via the constructor. But this doesn't seem like the solution or does it?
class HeaderHome extends Layout implements HasMedia
{
use HasMediaLibrary;
/**
* The layout's unique identifier.
*
* @var string
*/
protected $name = 'header-home';
/**
* The displayed title.
*
* @var string
*/
protected $title = 'Header (home)';
/**
* The parent model instance.
*
* @var string
*/
protected $model = \App\Models\Page::class;
/**
* Holds the resource.
*
* @var string
*/
protected $resource = null;
/**
* @param $title
* @param $name
* @param $fields
* @param $key
* @param $attributes
* @param callable|null $removeCallbackMethod
*/
public function __construct($title = null, $name = null, $fields = null, $key = null, $attributes = [], callable $removeCallbackMethod = null)
{
// Access the resource for getting relevant data
$this->resource = (new $this->model)->find(request()->resourceId);
parent::__construct($title, $name, $fields, $key, $attributes, $removeCallbackMethod);
}
/**
* Get the fields displayed by the layout.
*
* @return array
*/
public function fields()
{
return [];
}
}
@toonvandenbos Any update about this issue/question?
Hi @justkidding96. Indeed, this is not best way to get the resource because this package can also be used on "fake" resources (like inside the nova-page package) where request()->resourceId could give unexpected results.
However, the base Layout class has a $model attribute, which should contain the original model (resource) the field is rendered for (even when used as a sub-field). Did you try accessing $this->model in your custom layout ?
+1 for this
@toonvandenbos $this->model returns undefined.