I have a simple cakephp 2.x app that I baked using the bake script. The two main tables are conditions and drugs. A condition HABTM drugs and vice verca. I'm trying to display the drugs that belong to a condition in the condition index, basic listing all conditions, but ONLY those drugs. I have tried doing it like this, to display the drugs belonging to a condition in a comma seperated list, which works in another 1.3 app:
<?php
$condition_drugs = '';
foreach($condition['Drug'] as $drug):
$condition_drugs .= $drug['drug'] . ', ';
//echo $drug['generic'];
endforeach;
//echo substr($condition_drugs, 0, -2);
echo $condition_drugs;
?>
But it gives the following two errors:
Undefined index: Drug [APP/View/Conditions/index.ctp, line 22], and Invalid argument supplied for foreach() [APP/View/Conditions/index.ctp, line 22]
I also looked at another article here that suggested doing it in a similar way. Is there something wrong with the code I have? Do I need a find in my model based on the ID? Here's the full index view code and controller:
View:
<div class="conditions index">
<h2><?php echo __('Conditions'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('condition'); ?></th>
<th><?php echo $this->Paginator->sort('principles'); ?></th>
<th><?php echo $this->Paginator->sort('treatment'); ?></th>
<th><?php echo $this->Paginator->sort('clinical_tips'); ?></th>
<th>Drugs</th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($conditions as $condition): ?>
<tr>
<td><?php echo h($condition['Condition']['condition']); ?> </td>
<td><?php echo h($condition['Condition']['principles']); ?> </td>
<td><?php echo h($condition['Condition']['treatment']); ?> </td>
<td><?php echo h($condition['Condition']['clinical_tips']); ?> </td>
<td>
<?php
$condition_drugs = '';
foreach($condition['Drug'] as $drug):
$condition_drugs .= $drug['drug'] . ', ';
//echo $drug['generic'];
endforeach;
//echo substr($condition_drugs, 0, -2);
echo $condition_drugs;
?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $condition['Condition']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $condition['Condition']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $condition['Condition']['id']), null, __('Are you sure you want to delete # %s?', $condition['Condition']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Condition'), array('action' => 'add')); ?></li>
</ul>
</div>
Controller:
<?php
App::uses('AppController', 'Controller');
/**
* Conditions Controller
*
* #property Condition $Condition
*/
class ConditionsController extends AppController {
/**
* index method
*
* #return void
*/
public function index() {
$this->set('title_for_layout','Condition Index');
$this->Condition->recursive = 0;
$this->set('conditions', $this->paginate());
}
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function view($id = null) {
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
$this->set('condition', $this->Condition->read(null, $id));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Condition->create();
if ($this->Condition->save($this->request->data)) {
$this->Session->setFlash(__('The condition has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The condition could not be saved. Please, try again.'));
}
}
$drugs = $this->Condition->Drug->find('list',array('fields'=>array('id','generic')));
$this->set(compact('drugs'));
}
/**
* edit method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function edit($id = null) {
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Condition->save($this->request->data)) {
$this->Session->setFlash(__('The condition has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The condition could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Condition->read(null, $id);
}
$drugs = $this->Condition->Drug->find('list',array('fields'=>array('id','generic')));
$this->set(compact('drugs'));
}
/**
* delete method
*
* #throws MethodNotAllowedException
* #throws NotFoundException
* #param string $id
* #return void
*/
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
if ($this->Condition->delete()) {
$this->Session->setFlash(__('Condition deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Condition was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
To include habtm data, you need $recursive = 1;
You have set it to 0
Related
I created an application form using cakephp 2.
Now I want to know, How can users view only their application details using their user id. Here is the Form controller, the application form and the table for displaying the form
//Form controller
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Flash->success(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('Unable to add your post.'));
}
}
//Create form
echo $this->Form->create('Post');
echo $this->Form->input('esta',['label'=>'New or Estabilished']);
echo $this->Form->end('Save Post');
//Form display
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Post']['describe_idea'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
</table>
You said that you are using cakephp 2.x please find below code to find record
for Single Record
$posts = $this->Post->find('first', array(
'conditions' => array('id' => 1)
));
For Multiple record
$posts = $this->Post->find('all', array(
'conditions' => array('id' => 1)
));
Add filter in your action
CakePHP 3.x
$posts = $this->Posts->find()
->where([
'Posts.user_id' => $this->Auth->user('id')
]);
CakePHP 2.x
$posts = $this->Posts->find('all', [
'user_id' => $this->Auth->user('id')
]);
Note: Make sure to login user to set Auth data.
hi all when trying to update my database, this function isn't grabbing the id from the table and it isn't updating that line in the table. Its also throwing an error with
$this->Relationship->id = $this->request->data['id'];
here is the function in its entirety
public function approve($id=null){
$this->Relationship->id = $id;
if($this->request->is('get')){
$this->request->data=$this->Relationship->read();}
$this->Relationship->id = $this->request->data['id'];
if($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your Relationship has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
here is form/view
<?php
echo $this->Form->create('Relationship', array('action'=>'approve'));
echo $this->Form->input('expirydate',array('label'=>'Expiry Date: ', 'class' => 'dateclass'));
echo $this->Form->end('Submit');
?>
what I'm trying to do with this function is grab a the id, and edit two fields in that entry
It should be $this->request->data['Relationship']['id']; if you setup your form correctly. Also, you can just do
$this->Relationship->create($this->request->data);
$this->Relationship->save()
public function approve($id=null){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if ($this->request->is('get')) {
$this->request->data = $this->Relationship->read(NULL, $id);
} else {
//sets active to 1
$this->Relationship->read(null, $id);
$this->Relationship->set(array('active' => true,));
if ($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
I also had to change a tinyint from 0=>1 in the database.The other issue I had was with my request view, it was not passing the id to the approve function. Once I changed the code to this it worked
<?php foreach($Relationships as $relationship):?>
<tr>
<td align='center'><?php echo $relationship['Relationship']['partyone']; ?></td>
<td align='center'><?php echo $relationship['Relationship']['partytwo']; ?></td>
<td> </td>
<td><?php echo $this->Html->link($relationship['Relationship']['partyone'], array('action'=>'approve', $relationship['Relationship']['id'])); ;?>
</td>
</tr>
<?php endforeach; ?>
</table>
This code is only updating one row (the one that matches the first in the array):
Edit: showing more code!
Here's my view. It's grabbing db entries based on an association (there's one model "clients" that has a one-to-many relationship with two other models, Programs and Users).
<div class="view">
<h2><?php echo h($program['Program']['title'])?></h1>
<?php echo $this->Form->create('User', array('action' => 'pushing')); ?>
<table id="pushTable">
<tr><th colspan="5">Select the athletes you would like to push this program to:</th></tr>
<tr>
<?php $i=0; ?>
<?php foreach ($clients['Players'] as $player) {?>
<?php if ($i == 0) {?><tr><?php } ?>
<td><?php echo $this->Form->checkbox($player['id']) . ' ' . $player['username'];?></td>
<?php if ($i == 4) {?></tr><?php $i = 0; } else { $i++; } ?>
<?php } ?>
</tr>
</table>
<?php echo $this->Form->end(__('Push')); ?>
</div>
In my Users controller:
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
$athletes = $this->request->data['User'];
foreach ( $athletes as $player => $flag){
if ($flag == 0){
unset($athletes[$player]);
}
}
$this->User->updateAll(
array('User.data' => "'foo'"),
array('User.id' => $athletes)
);
$this->Session->setFlash(__('Programs were pushed!'));
}
}
}
$athletes is the array is collected from checked boxes, and there seem to me no problems with that... so I'm not sure why the updateAll isn't iterating over each ID in the array...
Maybe it's not working for a db related reason? I'm developing on MAMP... maybe the db isn't set up for "atomic" stuff (only heard about that here today!).
I had previously tried using a foreach to loop over the id's, then in the foreach just did this (edit: more code!)
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
foreach ($this->request->data['User'] as $player => $flag) {
if ($flag) {
$this->User->id = $player; // set ID to player we want to save ($player is id that was suplpied in view to checkbox
$this->User->saveField('data', 'foo'); // then, push the data!
}
}
$this->Session->setFlash(__('Programs were pushed!'));
}
$this->autoRender = false;
$this->redirect(array('action' => 'index'));
}
But that caused weird results with redirection. No matter where I put redirection in that action, the save just wanted to do its own thing. That $this->autoRender did nothing. The controller still tried to resolve to the /pushing/ route
Give this a shot :)
In your view:
<div class="view">
<h2><?php echo h($program['Program']['title'])?></h1>
<?php echo $this->Form->create('User', array('action' => 'pushing')); ?>
<table id="pushTable">
<tr><th colspan="5">Select the athletes you would like to push this program to:</th></tr>
<tr>
<?php $i=0; ?>
<?php foreach ($clients['Players'] as $player) {?>
<?php if ($i == 0) {?><tr><?php } ?>
<td><?php echo $this->Form->input('Player.' . $player['id']. '.id', array('type' => 'checkbox', 'value' => $player['id'])) . ' ' . $player['username'];?></td>
<?php if ($i == 4) {?></tr><?php $i = 0; } else { $i++; } ?>
<?php } ?>
</tr>
</table>
<?php echo $this->Form->end(__('Push')); ?>
</div>
In your controller:
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
$athletes = $this->request->data['Player'];
$athlete_ids = array();
foreach($athletes as $a){
$athlete_ids[$a['id']] = $a['id'];
}
$this->User->updateAll(
array('User.data' => "'foo'"),
array('User.id' => $athlete_ids)
);
$this->Session->setFlash(__('Programs were pushed!'));
}
}
}
Hi had to change the code a bit to make it for work me..
$contactsids = array();
foreach($selected as $key => $val){
if(($val <> '') && ($val <> 0) ) {
$contactsids[$val] = $val;
}
}
$this->Contact->updateAll(
array('Contact.contact_category_id' => $category_id),
array('Contact.id' => $contactsids)
);
when user enter the full url..i want to save only youtube id... pregmatch examine and extract video id and then it will be saved into database..the problem is how to make this pregmatch check and extract youtube id before save the full url
thanks for helping
// this is add() function in videos_controller
function add() {
if (!empty($this->data)) {
$this->Video->create();
if ($this->Video->save($this->data)) {
$this->Session->setFlash(__('The Video has been saved', true));
$this->redirect(array('action' => 'admin_index'));
} else {
$this->Session->setFlash(__('The Video could not be saved. Please, try again.', true));
}
}
$vcats = $this->Video->Vcat->find('list');
$this->set(compact('vcats'));
}
// this is add.ctp file
<div class="videos form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Video'); ?>
<fieldset>
<legend><?php __('Add Video'); ?></legend>
<?php
echo $this->Form->input('vcat_id');
echo $this->Form->input('title');
$url= $this->Form->input('link');
echo $url
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true)); ?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li>
</ul>
</div>
// we get the unique video id from the url by matching the pattern but where i put this code to match before save
preg_match("/v=([^&]+)/i", $url, $matches);
$id = $matches[1];
Here
function add() {
if (!empty($this->data)) {
$this->Video->create();
$url = $this->data['Video']['link'];
/*assuming you have a column `id` in your `videos` table
where you want to store the id,
replace this if you have different column for this*/
preg_match("/v=([^&]+)/i", $url, $matches);
$this->data['Video']['id'] = $matches[1];
//rest of the code
}
}
I guess a better place for it is in the Model's beforeSave or beforeValidate method:
class Video extends AppModel {
...
public function beforeSave() {
if (!empty($this->data[$this->alias]['link'])) {
if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) {
$this->data[$this->alias]['some_id_field'] = $matches[1];
}
}
return true;
}
...
}
My Gallery model is related to my image model, but when I retrive images from galleries_controller I cant see any result and instead see this error:
Warning (2): Invalid argument supplied for foreach() [APP\views\galleries\view.ctp, line 35]
Here is the code from my controller action:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
This is the loop I have in my galleries/view to iterate through the array.
<?php
$i = 0;
foreach ($images['Image'] as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['id'] ;?></td>
<td><?php echo $image['name'];?></td>
<!--<td><?php echo $image['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
You aren't setting anything with your set. Your find is being executed and then not stored in a variable. Furthermore, your view loop is iterating through incorrectly.
Change your controller to:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$images = $this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
And your view code to:
<?php
$i = 0;
foreach ($images as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['Image']['id'] ;?></td>
<td><?php echo $image['Image']['name'];?></td>
<!--<td><?php echo $image['Image']['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['Image']['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
That having been said, since all you want to do is pull in associated images when a gallery is viewed, you should look into setting up your model associations and then doing a find on your gallery that will include the images you want like so:
$this->set('gallery',$this->Gallery->find('first', array('conditions' => array('Gallery.id' => $id), 'recursive' => 1));
If the above don't work, then there is something misconfigured in your models. Please post your model code so we can investigate further.