This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
I think I'm being a bit stupid here, but hey ho it wont be the first time if so!
I'm trying to extend the RainLab blog plugin model so I can access a comment count. I've aded the following to my plugin.php and appropdiate model ifle
BlogPost::extend(function($model) {
$model->hasMany['comments'] = ['\MyPlugin\Blog\Models\Comments', 'foreignKey' => 'post_id'];
});
class Comments extends Model
{
public $belongsTo = [
'post' => ['\RainLab\Blog\Models\Post', 'post_id' => 'id']
];
}
But I can't figure out how I then access that information on the front end in a post loop ( {% for post in posts %} )? Ultimately I want a comment count only to show for each post as part of the Blog Post List. Can I do something within my plugin to return that count to the BlogPostList component?
Am I missing something stupid? Is there a better way?
Last updated
In the code section of the page you can create a onStart() function and do egular eloquent queries there.To inject the results to the page, you need $this['var'] = ... http://octobercms.com/docs/cms/pages#page-cycle-handlers
That doesn't seem like the best way to do it. I'd basically be overriding the existing plugin component posts loop with my own? I'd rather extend the original plugin model appropriately - that seems to me to be the logical way to do it?
The problem with twig view files is, you cant put any logic in them!
So you need to prepare the informations you want to display in your components onRun()
-method. You can look at other plugins how they have done it: https://github.com/rainlab/forum-plugin/blob/master/components/Channel.php#L93-L100
Most likely you want sth like this:
$thhis->posts = $this->page['posts'] = BlogPost::with('comments')->get()->toArray();
To get the comment count you can use the following twig function: http://twig.sensiolabs.org/doc/filters/length.html
Adam, watch http://octobercms.com/blog/post/mastering-components for why he specified $this->posts = $this->page['posts'] = ...
Also, you don't really need the toArray() on the end. You can always use .getAttributes()
in twig if you need to (eg: https://github.com/that0n3guy/oc-menu-plugin/blob/simplifyRender/components/menu/default.htm#L47)
Something like: {% posts.getAttributes().title %}
gets the post title.
1-6 of 6