cakephp 3 url in controller

Ye Htun Z picture Ye Htun Z · Feb 23, 2016 · Viewed 8.9k times · Source

I have to send url from controller to view with json..It not ok when i use $this->Html->link or $this->Url->build for link. How can i send link to json..

use Cake\View\Helper\UrlHelper; at top

foreach($schedules as $s) :
            $start=$s->start_at;
            $end=$s->finished_at;

   $link= $this->Url->build([ 
                                    'controller' => 'Bookings','action' => 'makebooking',
                                    'comid' => 1,
                                    'comslug' =>'Moe Moe',
                                    'sevid'=>2,
                                    'sevslug'=>'face washing',
                                    'sid'=>$s->id,
                                    'start'=>$start,
                                    'end'=>$end
                                    ]); 
            $out[]=array(
                'id'=>$s->id,
                'title'=>'( '.$s->start_at.'-'.$s->finished_at.' )'.$s->name,
                'url'=>$link,
                'start'=>strtotime($s->start_at).'000',
                'class'=>'event-important'

                );
         endforeach;


         echo json_encode(array('success'=>1,'result'=>$out));exit;

Error: Call to a member function build() on a non-object and i was

Answer

Faiyaz Alam picture Faiyaz Alam · Feb 23, 2016

use this code to generate url anywhere in the app:

use Cake\Routing\Router;

    $link =  Router::url([ 
                                        'controller' => 'Bookings','action' => 'makebooking',
                                        'comid' => 1,
                                        'comslug' =>'Moe Moe',
                                        'sevid'=>2,
                                        'sevslug'=>'face washing',
                                        'sid'=>$s->id,
                                        'start'=>$start,
                                        'end'=>$end
                                        ]);

To generate the full URL pass second arg as TRUE. see example below:

 $fullLink =  Router::url([ 
                                            'controller' => 'Bookings','action' => 'makebooking',
                                            'comid' => 1,
                                            'comslug' =>'Moe Moe',
                                            'sevid'=>2,
                                            'sevslug'=>'face washing',
                                            'sid'=>$s->id,
                                            'start'=>$start,
                                            'end'=>$end
                                            ],TRUE);

I have not tested the above code but I am sure it will work. Let me know if it does not work.