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.
Related
I've done blog by tutorial and stopped at Deleting Posts (all code is by this link), because has Notice (1024): Element Not Found: Elements\8.ctp ( 8 - id of deleted record) when click Delete in table on index page. And record is really deleted in database. How to solve this notice? My version cakephp is 2.6.1.
Thanks.
<?php
class PostsController extends AppController {
public $helpers = array ('Html', 'Form', 'Session');
public $components = array('Session');
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->Session->setFlash(__('Your post has been saved'));
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Unable to add your post'));
}
}
public function edit($id = null)
{
if (!$id)
{
throw new NotFoundException(__('Invalid post'));
}
$post=$this->Post->findById($id);
if (!$post)
{
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post','put')))
{
$this->Post->id=$id;
if ($this->Post->save($this->request->data))
{
$this->Session->setFlash(__('Your post has been updated'));
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Unable to update your post'));
}
if (!$this->request->data)
{
$this->request->data=$post;
}
}
public function delete($id)
{
if ($this->request->is('get'))
{
throw new MethodNotAllowedException();
}
if ($this->Post->delete($id))
{
$this->Session->setFlash(__('The post with id: %s has been deleted'),h($id));
return $this->redirect(array('action'=>'index'));
}
return $this->redirect(array('action'=>'index'));
}
}
// index.ctp
<h1>Blog posts</h1>
<?php
echo $this->Html->link(
'Add Post',array('controller'=>'posts','action'=>'add')
);
?>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Actions</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']['title'],array(
'controller' => 'posts',
'action' => 'view',
$post['Post']['id']
));
?>
</td>
<td>
<?php
echo $this->Form->postLink(
'Delete',
array('action' => 'delete', $post['Post']['id']),
array('confirm' => 'Are you sure?')
);
?>
<?php
echo $this->Html->link(
'Edit',
array('action' => 'edit', $post['Post']['id'])
);
?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
</table>
$this->Session->setFlash(__('The post with id: %s has been deleted'),h($id));
the problem is here,
setFlash(__('The post with id: %s has been deleted'),h($id));
this should be,
setFlash(__('The post with id: %s has been deleted',h($id)));
Because you didn't provide code (not smart if you want to get help), I guess you're calling somewhere $this->element($id); in your view. The tutorial you've linked doesn't contain this method call anywhere. So you do something different.
Also read the error message, it tells you that it it missing a file called 8.ctp in your app/View/Elements/ folder. To figure out why is now up to you.
Here ajax search working fine but the problem is same data is showing two times, because I have given pagination limit 2.If I make it 3, same result is showing 3 times.
Here is my index.ctp
$( "#search" ).keyup(function() {
var value=$('#search').val();
$.get("<?php echo Router::url(array('controller'=>'userTypes','action'=>'search'));?>",{search:value},function(data){
$('.search_data').html(data);
});
})
Here is my search action
public function search()
{
$search=$_GET['search'];
$request=$this->UserType->find('all', array(
'conditions' => array('UserType.name LIKE' => "%$search%")
));
$this->set('usertype',$request);
}
Here is the search.ctp
<?php foreach($usertype as $usertypes) { ?>
<tr>
<td><?php echo $usertypes['UserType']['id']; ?></td>
<td><?php echo $usertypes['UserType']['name']; ?></td>
<td><?php echo $usertypes['UserType']['description']; ?></td>
</tr>
<?php } ?>
Pagination limit In appcontroller
parent::beforeFilter();
$this->Paginator->settings = array(
'limit'=>2
);
Result is showing me like this
May anybody help me for solve it ?
If you want to use pagination, your search method should look like this:
public function search()
{
if(isset($this->request->query['search'])){
$search = $this->request->query['search'];
}else{
$search = '';
)
$this->Paginator->settings = array(
'conditions' => array('UserType.name LIKE' => "%$search%"),
'limit' => 2
);
));
$this->set('usertype',$this->Paginator->paginate());
}
This is my one of the controller
app\Controller\DashboardsController.php
here Patientslist is my another controller
<?php
class DashboardsController extends AppController {
public $components = array('Session');
public function index() {
$this-> loadModel('Patientslist');
$this->set('posts', $this->Patientslist->find('all', array('conditions' => array('Patientslist.user_id' => $this->Auth->user('id')))));
}
public function view($id) {
$this-> loadModel('Patientslist');
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Patientslist->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
public function add() {
$this-> loadModel('Patientslist');
if ($this->request->is('post')) {
//Added this line
$this->request->data['Patientslist']['user_id'] = $this->Auth->user('id');
if ($this->Patientslist->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
}
}
/* 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'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
}
*/
public function edit($id = null) {
$this-> loadModel('Patientslist');
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Patientslist->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('Patientslist', 'put'))) {
$this->Patientslist->id = $id;
if ($this->Patientslist->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
public function delete($id) {
$this-> loadModel('Patientslist');
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if ($this->Patientslist->delete($id)) {
$this->Session->setFlash(
__('The post with id: %s has been deleted.', h($id))
);
return $this->redirect(array('action' => 'index'));
}
}
public function isAuthorized($user) {
$this-> loadModel('Patientslist');
// All registered users can add posts
if ($this->action === 'add') {
return true;
}
// The owner of a post can edit and delete it
if (in_array($this->action, array('edit', 'delete'))) {
$postId = $this->request->params['pass'][0];
if ($this->Patientslist->isOwnedBy($postId, $user['id'])) {
return true;
}
}//
return parent::isAuthorized($user);
}
}
here view app\View\Dashboards\index.ctp
<div id="tabs">
<ul>
<li>MyProfile</li>
<li>Patients</li>
<li>List</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
<p><?php echo $this->Html->link('Add Patient', array('action' => 'add')); ?></p>
<table>
<tr>
<th>Patient's Name</th>
<th>Address</th>
<th>Email-id</th>
<th>Mobile</th>
<th>Age</th>
<th>gender</th>
<th>Actions</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php
echo $this->Html->link(
$post['Patientslist']['patients_name'],
array('action' => 'view', $post['Patientslist']['id'])
); ?></td>
<td>
<?php
echo $post['Patientslist']['address'];
?>
</td>
<td>
<?php
echo $post['Patientslist']['email'];
?>
</td>
<td>
<?php
echo $post['Patientslist']['mobile'];
?>
</td>
<td>
<?php
echo $post['Patientslist']['age'];
?>
</td>
<td>
<?php
echo $post['Patientslist']['gender'];
?>
</td>
<td>
<?php
echo $this->Form->postLink(
'Delete',
array('action' => 'delete', $post['Patientslist']['id']),
array('confirm' => 'Are you sure?')
);
?>
<?php
echo $this->Html->link(
'Edit', array('action' => 'edit', $post['Patientslist']['id'])
);
?>
</td>
<td>
<?php echo $post['Patientslist']['created']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div id="tabs-3">
</div>
</div>
Here I have to do display same tab for all add, edit, delete in same page how it will be possible?
I'm trying to paginate Workers which belong(s)To Job within a JobsController.
class JobsController extends AppController {
var $name = 'Jobs';
var $helpers = array('Html', 'Form', 'Js');
var $paginate = array(
'Worker' => array(
'limit' => 5,
'recursive' => 0,
'model' => 'Worker',
'order' => array('age' => 'ASC')
),
);
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Job.'));
$this->redirect(array('action'=>'index'));
return;
}
$this->Job->id = $id;
$workers = $this->paginate('Worker', array('Worker.job_id' => $id));
if ($workers) {
$this->set('workers', $workers);
}
}
In view.ctp:
<?php
$this->Html->script(array('jquery.min'), array('inline' => false));
$this->Paginator->options(array(
'update' => '#content',
'evalScripts' => true,
));
?>
<?php if (isset($workers)): ?>
<?php echo $this->Paginator->numbers(array('model' => 'Worker')); ?>
<table>
<tr>
<th>Age</th>
<th>Info</th>
</tr>
<?php foreach ($workers as $worker): ?>
<tr>
<td>
<?php echo $worker['Worker']['age']; ?>
</td>
<td>
<?php echo $worker['Worker']['info']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $this->Paginator->numbers(array('model' => 'Worker')); ?>
<p>
<?php
echo $this->Paginator->counter(array(
'model' => 'Worker',
'format' => __('Page %page% of %pages%, showing %current% records out of %count% total.')
));
?></p>
<?php endif; ?>
<?php echo $this->Js->writeBuffer(); ?>
I'm getting the correct list of workers. But the links generated by numbers are not working. They look like /view/2/page:2/sort:Worker.age/direction:ASC
What am I doing wrong? cakephp version is 2.4.1.
Try this in your view action, by setting the order at run time.
$this->paginate['Worker']['order'] = array('Worker.age' => 'ASC')
Now your function look like this
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Job.'));
$this->redirect(array('action'=>'index'));
return;
}
$this->Job->id = $id;
$this->paginate['Worker']['order'] = array('Worker.age' => 'ASC');
$workers = $this->paginate('Worker', array('Worker.job_id' => $id));
if ($workers) {
$this->set('workers', $workers);
}
}
Hope this helps you.
Hi all Iam using Cakephp 2.x, I need to output individual users' comments for each individual event. Each user has many events and many comments. I have Events, Comments and Users models and want to allow users to post and view comments on each event view.ctp. If anyone could give any starting tips to implement this functionality it would be much appreciated.
I have tried to output the comments model index table in the events view.ctp, but the table is not populated with the comments from the database, but the comments view.ctp does in fact populate the table with the comments. I have used the $this->loadModel('Comments'); function in the events controller.
<div class="events view">
<?php echo $this->Html->css('viewevent'); ?>
<?php echo $this->element('maintitlegen'); ?>
<div style="padding-top: 160px">
<h2><?php echo $event['Event']['name']; ?></h2>
<dl>
<dt><?php echo __('Event Image'); ?></dt>
<dd>
<?php echo $this->Html->image('/uploads/event/filename/thumb/small/'.$event['Event']['filename']); ?>
</dd>
<dt><?php echo __('Date'); ?></dt>
<dd>
<?php echo h($event['Event']['date']); ?>
</dd>
<dt><?php echo __('Time'); ?></dt>
<dd>
<?php echo h($event['Event']['time']); ?>
</dd>
<dt><?php echo __('Description'); ?></dt>
<dd>
<?php echo h($event['Event']['description']); ?>
</dd>
<dt><?php echo __('Dresscode'); ?></dt>
<dd>
<?php echo h($event['Event']['dresscode']); ?>
</dd>
<dt><?php echo __('Slogan'); ?></dt>
<dd>
<?php echo h($event['Event']['slogan']); ?>
</dd>
<dt><?php echo __('Price'); ?></dt>
<dd>
<?php echo h($event['Event']['price']); ?>
</dd>
<dt><?php echo __('Offers'); ?></dt>
<dd>
<?php echo h($event['Event']['offers']); ?>
</dd>
</dl>
<!--<?php foreach ($users as $user): ?>
<?php echo $user['Comment']['comment']; ?>
<?php endforeach; ?>-->
<!--<?php echo $ucomment['Comment']['comment']; ?>-->
<?php echo $this->Form->create('Comment', array('controller' => 'comments', 'action' => 'add')); ?>
<?php echo ('Add Comment'); ?>
<?php echo $this->Form->input('comment'); ?>
<?php echo $this->Form->end('Submit'); ?>
</div>
<div class="comments index">
<h2><?php echo ('Comments'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('comment'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th><?php echo $this->Paginator->sort('user_id'); ?></th>
<th><?php echo $this->Paginator->sort('event_id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($comments as $comment): ?>
<tr>
<td><?php echo h($comment['Comment']['id']); ?> </td>
<td><?php echo h($comment['Comment']['comment']); ?> </td>
<td><?php echo h($comment['Comment']['created']); ?> </td>
<td><?php echo h($comment['Comment']['modified']); ?> </td>
<td>
<?php echo $this->Html->link($comment['User']['name'], array('controller' => 'users', 'action' => 'view', $comment['User']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($comment['Event']['name'], array('controller' => 'events', 'action' => 'view', $comment['Event']['id'])); ?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $comment['Comment']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $comment['Comment']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $comment['Comment']['id']), null, __('Are you sure you want to delete # %s?', $comment['Comment']['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>
////////////////////////////////User model///////////////////////////////////////////////
<?php
class User extends AppModel {
public $name = 'User';
public $displayField = 'name';
public $validate = array(
'name'=>array(
'Please enter your name.'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your name.'
)
),
'username'=>array(
'That username has already been taken'=>array(
'rule'=>'isUnique',
'message'=>'That username has already been taken.'
),
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'password'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password'
),
'Match passwords'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match'
)
),
'password_confirmation'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password'
)
)
);
public function matchPasswords($data) {
if ($data['password'] == $this->data['User']['password_confirmation']) {
return true;
}
$this->invalidate('password_confirmation', 'Your passwords do not match');
return false;
}
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
public $hasMany = array(
'Event' => array(
'className' => 'Event',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $hasOne = array(
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id',
'dependent' => true));
var $actsAs = array(
'MeioUpload.MeioUpload' => array('filename'=>array(
'thumbsizes'=>array(
'small'=>array(
'width'=>'75',
'height'=>'75',
'forceAspectRatio'=>'C'
)))));
}
?>
///////////////////////////////////// Users Controller///////////////////////////////////
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function isAuthorized($user) {
if ($user['role'] == 'admin') {
return true;
}
// if (in_array($this->action, array('delete'))) {
// if ($user['id'] != $this->request->params['pass'][0]) {
// return false;
// }
// }
return true;
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
// public function logout() {
// $this->redirect($this->Auth->logout());
// }
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->User->find('all'));
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if (!$id) {
$this->Session->setFlash('Invalid user');
$this->redirect(array('action' => 'index'));
}
$this->set('user', $this->User->read());
}
public function add() {
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('Now create your profile!');
$this->Auth->login();
$this->redirect(array('controller'=> 'profiles', 'action' => 'add'));
} else {
$this->Session->setFlash('Your account cannot be created. Please try again.');
}
}
// if (!empty($user)){
// $this->request->data['Profile']['user_id'] = $this->User->id;
// $this->User->Profile->save($this->request->data);
// }
}
public function edit($id = null) {
$this->User->id = $id;
$user = $this->User->read();
if($user['User']['id'] != $this->Auth->user('id')){
$this->redirect(array('controller' => 'events','action' => 'index'));
}
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('get')) {
$this->request->data = $user;
} else {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Your account has been updated'));
$this->redirect(array('controller' => 'events', 'action' => 'index'));
} else {
$this->Session->setFlash(__('Your account cannot be saved. Please try again.'));
}
}
}
public function delete($id = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if (!$id) {
$this->Session->setFlash('Invalid id for user');
$this->redirect(array('action'=>'index'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash('User deleted');
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash('User was not deleted');
$this->redirect(array('action' => 'index'));
}
}
?>
I think it is safe to assume your comment table has at least the following columns:
id
user_id
event_id
comment (or name)
The view you display in the OP is the view for the events.view method. But you do not show the even model or controller. So I am not certain if you need help with the events controller or if you are trying to display event data in the users controller. The way to get all of the comments for the view you show in the OP is to pull all of the comments from the model like so:
$this->set('comments', $this->Event->Comment->find('all', array('conditions' => array('event_id' => $event_id))));
If you want the user data to be displayed along with it, you will need to either set recursive = 1 or write a join to join the user data.