While I was proceeding with the tutorial for cakephp at the following URL, I was wondering
For example, what should I do if I use the $data output from foreach to create a program called search from the database with the find helper?
I don't think I can use find helper on index.ctp file.
Please let me know if you know more.
http://libro.tuyano.com/index3?id=755001&page=3
If association is not configured, the controller will find each one.I haven't checked the operation, but it looks like this.
function index(){
...
$datas=$this->MyModel->find('list');
$submodels=array();
foreach($data as$key=>$data){
$submodels[$key] = $this->SubModel->find('list', array(
'conditions' = > array(
'SubModel.mainkey' = > $key
)
));
}
$this->set('datas',$datas);
$this->set('submodels', $submodels);
}
<?php foreach($data as $key=>$data): ?>
<h2><?phpecho$data;?>/h2>
<?phpforeach($submodels[$key]as$submodel): ?>
<?phpecho$submodel;?>
<?php endforeach;?>
<?php endforeach;?>
We put the SubModel find results in an array of MyModel primary keys, but the way and structure of it depends on what data you get and what you pass to the view side.
With Ajax, you can implement it without destroying the MVC of CakePHP and without being too conscious of the view on the controller.
For Controllers
<?php
// こっち Add only this side
function Ajax($data_id){
$record = $this->MySampleData->findById($data_id);
$this->set('record', $record['MySampleData']);
$this->set('_serialize', ['record']);
}
// 何 I haven't touched anything.
function index() {
$this->layout="Sample";
$this->set("header_for_layout", "Sample Application");
$this->set("footer_for_layout", "copyright by SYODA-Tuyano.2011.");
$datas=$this->MySampleData->find('list');
$this->set('datas',$datas);
}
?>
index.ctp
<h1>Index Page</h1>
<p>MySampleDataIndexView.</p>
<table>
<?php foreach($datasas$id=>$data): ?>
<tr>
<td>
<div class="data"data-id="<?phpecho$id;?>">?phpecho$data;?>;/div>;
<div class="data-extra"></div>
</td>
</tr>
<?php endforeach;?>
</table>
<script>
// Click to find more
$('.data').click(function(){
variable = this;
$.ajax({
url: 'ajax.json?id='+$(elem).attr('data-id'), // Rewrite this
type: 'json',
success:function(json){
$('.data-extra',elem).html(json.record.extra); // rough but
},
error: function() {
alert('Communication Error');
}
});
});
</script>
If you want to search all at once, you should use association, but if you want to search individually, I think this is better.It is very useless for the controller to load data that might not be used for View every time.
You can call the controller with Helper, but you shouldn't.
Similarly, it is better not to give it to $this->set('Controller', $this)' etc.
MVC will be meaningless.
© 2024 OneMinuteCode. All rights reserved.