• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

XF 2.0 Adding a parameter to route

#1
Hello!

In post_macros template I am adding an action-link (near like link):

PHP:
<a href="{{ link('posts/best', $post, {'thread_id': $thread.thread_id}) }}" class="actionBar-action actionBar-action--mq.is-selected">Best answer</a>
Next I extend XF\Pub\Controller\Post.php class and adding actionBest method to it:
PHP:
public function actionBest(ParameterBag $params) {
    echo print_r($params, true);
}
The problem is when I click on my "Best answer" button I don't see thread_id in parameters... The output is:
Code:
XF\Mvc\ParameterBag Object ( [params:protected] => Array ( [post_id] => 14 ) )
 

Chris D

XenForo developer
Staff member
#2
The second parameter of the link function is what populates the parameter bag; $post in your case. But it will also only ever contain parameters ithe route knows about (Look at Admin CP > Development > Routes and check out the posts route and its route format - it only looks for post_id so the ParameterBag will only know about that).

To access other types of input, such as that in the URL or in a POST request, you'd use the input filterer:

PHP:
$threadId = $this->filter('thread_id', 'uint');
However it's probably not necessary.

You can access the post_id on the ParameterBag object so you can just query for the post entity and then you can access the thread_id from that.
 
#3
Oh I see. I missed that the line of code I used as an example calls threads/post route which has thread_id in it's format in Admin CP so it is correct to request this parameter in link() function.

You can access the post_id on the ParameterBag object so you can just query for the post entity and then you can access the thread_id from that.
Yes it works!
PHP:
public function actionBest(ParameterBag $params) {   
    $post = $this->assertViewablePost($params->post_id);

    $finder = \XF::finder('XF:Thread');
    $thread = $finder->where('thread_id', $post->thread_id)->fetchOne();

    $questionThread = $thread->getRelationOrDefault('QuestionThread');
    $questionThread->best_post_id = $params->post_id;
    $questionThread->save();

}
Chris D, thank you. You rescued me once again!
 
Last edited:

Mike

XenForo developer
Staff member
#4
You can actually simplify getting $thread through the entity relationships:
Code:
$thread = $post->Thread;
No finder needed.