CakePHP 3 - Use data in an Element - cakephp

I just started using CakePHP, version 3. What I liked to start with is creating a menu based on a database table.
For creating a menu, I have seen that it should be placed inside the Element folder and called in 'default.ctp'. No problems here.
The problem is: How can I retrieve the data from the table while I'm not working in the controller, using the power of CakePHP? I can't find an example or something.
Inside 'Element/Menus/main.ctp' I do something like this (I know the link is not correct):
<?php
$menus = $this->requestAction('/Menus/index');
foreach ($menus as $menu) {
?>
<li><?= $this->Html->link('Menu', ['controller' => 'Menus', 'action' => 'index', '_full' => true]); ?></li>
<?php
}
?>
I try to get the data by calling 'requestAction' but it doesn't seem to be the right way.

Related

How is current and modified time is saving in CakePHP's blog tutorial?

I have just started learning CakePHP and I started with the official blog tutorial. So far so good but I am not getting how current and modified time is saving in db because neither in views nor in controller there is any line which points to these fields.
Here is PostsController.php code for add:
public function add()
{
if($this->request->is('post'))
{
$this->Post->create();
if($this->Post->save($this->request->data))
{
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash(__('Unable to add your post.'));
}
}
}
And here is view code for add.ctp:
<!-- File: /app/View/Posts/add.ctp -->
<?php echo $this->Html->link('Home', 'index/home'); ?>
<h1>Add Posts</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->submit('Add Post', array('name' => 'add_post'));
//echo $this->Form->end('Save Post');
?>
So someone please tell me which line is saving current time? Thanks a lot for help.
There's a hidden function inside the default Cake parent model that checks for fields with the name 'created' and 'modified', and updates the values automagically.
Search inside /lib/Cake/Model/Model.php for the string 'modified', and you'll see lots of references to this.
I'm not sure how well this is documented, I came across it while debugging some funky saving behavior.
In my system I settled on the fields 'created_at' and 'modified_at' before I found this little gem.
EDIT: This is documented here:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#using-created-and-modified
Check if AppModel.php contains function save(){} and UpdateAll(){}. Next check datatype of created and modified fields in mysql. then modify your question for more clarity.

How can i save multiple checkbox value those are checked in cakephp hasMany relation?

Suppose I have 3 tables property_details, property_feature_details, property_feature_relations.
PropertyDetail Model has the hasMany relation with PropertyFeatureRelation.
AT the time saveing my data array looks like that:
$this->data = array('PropertyDetail' => array('name'=>'xyz'),'PropertyFeatureRelation' => array('0' => array('feature_id'=>1),'1' => array('feature_id'=>5),'2' => array('feature_id'=>0),'3' => array('feature_id'=>0)));
Those feature_ids values are coming out from the checkboxes. Those are checked they are contains ids value and non checked are having 0 value. But in the child table saves all the data zero and non zeros.
Actually I want to save those checkboxes values which are only checked. Please do not provide any manual controller logic. Help me.
I am explaining you with my example which is having question ,answer and its survey
you can use multiple checkbox syntax as below:
$answers=array();
$tmp_ans=$question['Answer'];
for($j=0;$j < count($tmp_ans);$j++)
$answers[$tmp_ans[$j]['id']]=$tmp_ans[$j]['answer'];
echo '<li>';
echo $this->Form->input('Answer', array(
'type' => 'select',
'name'=>'Answer['.$question['Question']['id'].']',
'class'=>'test',
'label'=>false,
'multiple' => 'checkbox',
'options' =>$answers ,
));
echo '</li>';
after that you will have only those answers which you have checked others will not come in array of post so to save data you can use below syntax
if(!empty($this->data['Answer'])){
foreach ($this->data['Answer'] as $key=>$val):
if(!empty($val)):
if(is_array($val)):
foreach ($val as $ans):
$post_data['UserAnswer']['id']='';
$post_data['UserAnswer']['survey_id']=$id;
$post_data['UserAnswer']['user_id']=$this->Auth->user('id');
$post_data['UserAnswer']['question_id']=$key;
$post_data['UserAnswer']['answer_id']=$ans;
$this->UserAnswer->save($post_data['UserAnswer']);
endforeach;
else:
$post_data['UserAnswer']['id']='';
$post_data['UserAnswer']['survey_id']=$id;
$post_data['UserAnswer']['user_id']=$this->Auth->user('id');
$post_data['UserAnswer']['question_id']=$key;
$post_data['UserAnswer']['answer_id']=$val;
$this->UserAnswer->save($post_data['UserAnswer']);
endif;
endif;
endforeach;
}

cakephp view printing out the same values from database

created a view function and any time i click the link to view a template, the url at the top of the page is correct but it spits out the same list of fields in the database.
the fields are
accounts - id, company name, abn
template - id, name, description, account_id
field - id, name, field type, template_id
function view(){
$accounts=$this->User->AccountsUser->find('list',
array('fields'=>array('id', 'account_id'),
'conditions' =>array('user_id' =>
$this->Auth->user('id'))));
$templates=$this->Template->find('first',
array('conditions' => array(
'Template.account_id' => $accounts)));
$fields=$this->Field->find('all',
array('conditions' => array(
'Field.template_id' => Set::extract('/Template/id', $templates))));
$this->set('template', $templates);
$this->set('account', $accounts);
$this->set('field', $fields);
}
here is the view
<div class = "conlinks">
</br></br></br></br></br><h2>Here is your template fields</h2></br>
<?php foreach($field as $fields): ?>
<tr>
<td align='center'><?php echo $fields['Field']['name']; ?>
</tr></br>
<?php endforeach; ?>
</div>
so the problem is its grabbing the exact same list of fields, not the correct template_id when it prints out the fields
You should be able to debug this for yourself. Just narrow the bug down step by step.
For starters, in your view function, do a print_r on the following variables, and make sure each one contains a logical result:
$accounts
$templates
$fields
If you find unexpected results there, I'd be looking at the parameters you pass into each of your finds, and making sure they're OK. You're passing in $accounts as an array to your find condition - make sure it matches the format that cake expects. Do the same for Set::extract('/Template/id', $templates).
Also look at the SQL that Cake is producing.
If you're not already using it, I'd highly recommend installing Cake's Debug Kit Toolbar - https://github.com/cakephp/debug_kit/ because it makes debugging variables and SQL much easier.
If you do the above steps and can't solve your problem, you should at least be able to narrow it down to a line or two of code. Update your answer to show what line or two is causing the problem, and include print_r's of some of the variables you're working with. That should help others on StackOverflow to give you a specific answer.
Hope that helps!
the issue was I wasn't getting the parameters when click the link
function view($name){
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
and the view
<div class = "conlinks">
</br><h2>Here is your template fields</h2>
<?php foreach($field as $name): ?>
<tr>
<td align='center'>
<?php echo $name; ?>
</tr></br>
<?php endforeach; ?>
</br>
<?php
echo $this->Html->link('Back', '/templates/view', array('class' => 'button'));?>
</div>

CakePHP - how to use $html->link inside an element

How can I use $html->link from within an element?
Thanks,
Tee
In both 1.2 and 1.3,this should work:
echo $html->link('linkname',array('controller'=>'somecontroller','action'=>'someaction/somearguments'));
Update
The html helper has changed a little in version 2.x.An example from the cook book
echo $this->Html->link('Enter', '/pages/home', array('class' => 'button', 'target' => '_blank'));
The new version of Cakephp has easier ways to work with html->links, definitely you can convert links into buttons.
If you want using bootstrap or some css however for normal links you can use:
<?= $this->Html->link ('Sometexthere', ['controller' =>'myController', 'action' =>'myAction']); ?>

how to point to my correct address in this situation?! need help

I plan to add up a calender function to my system, but i had mess up with the link which not link to the direct address that i want..
i am still new to cakephp, need some help to get understand the code and the correct way for me to point to the correct address i want..
here is some of the code in the controller, other side is not a problem to run just left the pointing address which had make me mad..
when i press to the link, which i want to view my data, it's just jump to the other side that not in my set up.
// here is the declaration which in the original controller that i learn from the net.
$view_base_url = $this->webroot. 'calendars';
//this the original link that i using which cant point to my correct side.
$data[$day] .= 'a href="'.$view_base_url.'/view/'. $v['Calendar']['id'] . '">' . $v['Calendar']['name'] . '</a>';
in the details,
i wanted to link to my side with just the calendars/view/id of the link i point.
but with this code, i will redirect to the app/webroot/view/id side.
can i change the $this->webroot to just link to where i want??
if i not using the $this->webroot, i am not able to redirect while i click other page in the calendar..
it might be a poor explanation, cause i am still new to cakephp.
just any 1 can kindly drop me a comment what i can do?
You should use the Router class to create links to within your application. For example:
Router::url(array('controller' => 'my_controller', 'action' => 'view', $id));
// returns, for example, /my_controller/view/5
Router::url(array('controller' => 'my_controller', 'action' => 'view', $id), true);
// returns, for example, http://example.com/root_directory/my_controller/view/5
This method is used by many functions throughout Cake, for example by the HTML Helper:
echo $html->link('My Link', array('controller' => 'my_controller', 'action' => 'view', $id));
// echos:
My Link
The URLs that Router returns are based on the routes defined in app/config/routes.php. This way you can define handy shortcuts:
Router::connect('/view/*', array('controller' => 'my_controller', 'action' => 'view'));
echo $html->link('My Link', array('controller' => 'my_controller', 'action' => 'view', $id));
// echos:
My Link
This is the way you should handle all links in your Cake application. You shouldn't make links in the Controller, only in the View, using the HTML Helper. In the rare case were you do need links in the Controller, use Router::url().

Resources