简体   繁体   English

如何在Codeigniter中从视图使用控制器方法

[英]How to use controller method from view in Codeigniter

Problem : I cannot seem to call controller method from view. 问题:我似乎无法从视图调用控制器方法。 Why : because i want to pass argument in the method and loop the data 为什么:因为我想在方法中传递参数并循环数据

In view : 鉴于:

foreach($data as $key => $val){
   foreach($methodData($val['dataID']) as $mKey => $mVal){
       echo $mVal['name'];
   }
}

This is not recomended in the MVC pattern. 在MVC模式中不建议这样做。 You should only display the data in the view (data you passed from the controller). 您只应在视图中显示数据(从控制器传递的数据)。

Think about so set up the data as you need it in your controller and pass the right model to your view. 考虑一下,因此在控制器中根据需要设置数据,然后将正确的模型传递给视图。

lets say there is a model called 'jungle'. 可以说有一个名为“丛林”的模型。 in the model we search for elephants using a search term. 在模型中,我们使用搜索词搜索大象。 if no elephants come back, we load a search form and pass the search term back to it. 如果没有大象回来,我们将加载搜索表格并将搜索字词传递回去。

in your controller 在您的控制器中

  // check first if no results came back from the model
  if( ! $data['elephants'] = $this->jungle->getElephants($searchterm) ){

     $data['searchterm'] = $searchterm ; 

     $this->load->view( 'searchform_elephants', $data ); } 

     // we have results, $elephants data structure is assigned to $data 
     // and passed to the view so it can be accessed on the view page
     else { $this->load->view( 'show_elephants', $data ); }

if some elephants came back, then that $elephant object (or array) is assigned to $data, and then it gets passed to the view. 如果一些大象回来了,则将该$ elephant对象(或数组)分配给$ data,然后将其传递给视图。

so then in your view - you can foreach through the results depending on the type of data structure. 因此,在您看来,您可以根据数据结构的类型逐一查看结果。

 foreach($elephants as $index => $elephant) : 

    echo $elephant->firstname . ' ' . $elephant->lastname ; 

Last - if you know that what you are retrieving from the database etc is a single record - then you can assign the query results to row() . 最后-如果您知道从数据库等中检索的内容是单个记录,则可以将查询结果分配给row()。 THEN in the view you don't have to do a foreach etc. For example if you are getting a unique snowflake by $id 然后,在视图中,您无需进行foreach等操作。例如,如果通过$ id获得唯一的雪花

    // controller 
    $data['snowflake'] = $this->blizzard->getFlakeBy($id) ; 

   // view 
   echo $snowflake->firstname ; 

this page for the deets: https://ellislab.com/codeigniter/user-guide/database/results.html 该页面的设计者: https ://ellislab.com/codeigniter/user-guide/database/results.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM