This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi,
I would just pass/attach one or many objects to my component 'default.htm' view from the method onRun() (or onRender maybe?) of this same component. How can I do that?
I would something simply like from a Laravel controller:
return view('my.view', compact('my_var_1', 'my_var_2', 'my_var_3'));
So, I tried...
public onRun()
{
$myObject = MyModel::where('id', 1)->with('a_related_model')->get();
$this->page['something'] = $myObject;
}
And...
{{ dump(something) }}
{{ something.id }}
{{ something.slug }}
{{ something.title }}
or...
{% for something in somethings %}
{{ something.value }}
{% endfor %}
...
Nothing works (except 'user' accessible from any view). Unfortunately official documentation is too vague about this point, or there's a subtlety I didn't understand about the components...
Thanks for help.
Last updated
Hi! You can try declaring a public property and assign your object to that property:
...
class Something extends ComponentBase
{
public $something;
public onRun()
{
$myObject = ....;
$this->something = $this->page["something"] = $myObject;
}
}
It should be accessible from default.html view with SELF
{% set something = __SELF__.something %}
{{ dump(something) }}
As you said documentation is not very clear. Let me know!
That works! Thank you!
In the meantime, I was also able to find another method from API doc (not in standard doc): https://octobercms.com/docs/api#preparevars
(used by User Plugin too: https://octobercms.com/plugin/rainlab-user)
class Something extends ComponentBase
{
public prepareVars()
{
$myObject = ....;
$this->page["something"] = $myObject;
$this->page['anotherthing'] = $this->getAnotherThing();
}
public getAnotherThing()
{
...
}
public onRun()
{
$this->prepareVars();
}
}
{{ dump(something) }}
{{ dump(anotherthing) }}
// Can too directly use user relations, without declaration from component's class
{{ dump(user.comments) }}
// Or get value from pivot column (don't forget 'pivot' array declaration in your model in this case)
{{ dump(user.steps.pivot.status) }}
I hope it will help other people....
Last updated
1-3 of 3