hockie
hockie

Reputation: 1

How to create a function in controller and use it in template/view in cakephp 3.xxx

I need to use the function in my view/template page.

My code:

public function getAppNumber($id = null){

     $aPPLICATIONINFO = $this->AppEstLto->APPLICATIONINFO->find('all', [
     'fields'=>['application_number'],
     'conditions'=>['application_id'=>$id],
     'limit' => 200
     ]);
     foreach($aPPLICATIONINFO as $aPPLICATIONINFO){
        $aPPLICATIONINFOx = $aPPLICATIONINFO;
    } 
     return $aPPLICATIONINFOx;
}

Upvotes: 0

Views: 277

Answers (2)

Oris Sin
Oris Sin

Reputation: 1219

You should be doing something like this in your routes.php file inside your Config folder:

 Router::connect('/get-app-number', array('controller' => 'yourController', 'action' => 'get_app_number'));

That way you will be able to connect the url that will be used for your view. Your action corresponds and sends data to your view. The action is the function that is inside your controller in which you developed for setting the data and variables. The example of the slug which would be generated:

http://localhost/get-app-number

Upvotes: 0

calum
calum

Reputation: 11

You can use set() to use the function variables in your view as given in cookbook:https://book.cakephp.org/3/en/views.html#setting-view-variables

public function get_app_number($id = null){

     $applicationInfo = $this->AppEstLto->APPLICATIONINFO->find('all', 
     [
     'fields'=>['application_number'],
     'conditions'=>['application_id'=>$id],
     'limit' => 200
     ]);

     //Create an array
     $applicationArray = new array();

     //Store all results in array
     foreach($applicationInfo as $application){
        $applicationArray = $application;
     }
     // Pass the array to view 
     $this->set(compact('applicationArray'));
}

Now, you can use it in your view:

get_app_number.ctp:

<?php
 foreach($applicationArray as $application)
 {
   echo $application['application_number'];
 }
?>

Upvotes: 1

Related Questions