nova-flexible-content icon indicating copy to clipboard operation
nova-flexible-content copied to clipboard

Access resource within custom layout

Open justkidding96 opened this issue 3 years ago • 5 comments

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?

justkidding96 avatar Jun 29 '22 06:06 justkidding96

Hi @justkidding96, I'm not sure what your issue is. Can you elaborate ?

toonvandenbos avatar Jun 29 '22 09:06 toonvandenbos

@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 [];
    }
}

justkidding96 avatar Jun 30 '22 20:06 justkidding96

@toonvandenbos Any update about this issue/question?

justkidding96 avatar Jul 10 '22 12:07 justkidding96

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 ?

toonvandenbos avatar Jul 18 '22 11:07 toonvandenbos

+1 for this

@toonvandenbos $this->model returns undefined.

riptin avatar May 08 '23 11:05 riptin