Populate Fields From one Controller, in another.. CAKEPHP - php

I am currently trying to allow the users to archive events that have already been completed.
Then the event will be viewed in the Archive Table.
So basically I have one archive table, and one event table, and when the user wants to archive the event, they should be able to view the event in the archive add form (which needs to be populated by the $id of the event).
But I do not know how to populate the field.. I have tried setting a value.. but the events are not sessions so that didn't work, and I have also tried setting the $id at the start of the form, but that also didn't work.
Here is the code to my archive function in the events controller.
public function archive($id = null) {
if ($this->request->is('post')) {
$event = $this->Event->read($id);
$archive['Archive'] = $event['Event'];
$archive['Archive']['eventID'] = $archive['Archive']['archiveID'];
unset($archive['Archive']['archiveID']);
$this->loadModel('Archive');
$this->Archive->create();
if ($this->Archive->save($archive)) {
$this->Session->setFlash(__('The event has been archived'));
$this->Event->delete($id);
$this->redirect(array('action' => 'eventmanage'));
} else {
$this->Session->setFlash(__('The event could not be archived. Please, contact the administrator.'));
}
}
}

You need to do one of the following:
Set the values for the fields using $this->request->data in the controller.
public function add($id = null) {
if ($this->request->is('post')) {
[..snip..]
}
$this->loadModel('Event');
$event = $this->Event->read($id);
$this->request->data['Archive'] = $event['Event'];
}
OR
Update the form to set the values.
Update the existing code with the same event read:
public function add($id = null) {
if ($this->request->is('post')) {
[..snip..]
}
$this->loadModel('Event');
$this->set('event', $this->Event->read($id));
}
Then in your form in the Archives/add.ctp file, update each input to reflect the value of the $event.
echo $this->Form->input('eventID', array('type' => 'hidden', 'value' => $event['Event']['id']));
OR
Write a function that will move the record.
Put a button on the Event View called 'Archive'. Create a method in the Event Controller that will archive the event.
public function archive($id = null) {
if ($this->request->is('post')) {
$event = $this->Event->read($id);
$archive['Archive'] = $event['Event'];
$archive['Archive']['event_id'] = $archive['Archive']['id'];
unset($archive['Archive']['id']);
$this->loadModel('Archive');
$this->Archive->create();
if ($this->Archive->save($archive)) {
$this->Session->setFlash(__('The event has been archived'));
$this->Event->delete($id);
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The event could not be archived. Please, contact the administrator.'));
}
}
}

Related

Update existing record in CakePHP

I want to create the following in CakePHP:
Starting page: User enters a loginname which pre exists in the DB. Table name loginname.
Once the user has entered the right loginname, the user continues to the registration form, where the user can add personal data to the existing record.
When the user saves the form, the record with only the loginname has personal data added.
This is what i have:
Logic for starting page:
public function checkCodeRespondent() {
//set var
$password = $this->data['Respondent']['loginname'];
//set condition for hasAny function
$condition = array('Respondent.loginname'=>$password);
//if password matches continue to registreer
if($this->Respondent->hasAny($condition)){
//find data by password
$respondent = $this->findByPass($password);
//set var for current id
$id= $respondent['Respondent']['id'];
//redirect with current id
$this->redirect(array('action' => 'aanmelden', $id));
} else {
//if password does not match, return to index with errormessage
$this->redirect(array('action' => 'index'));
}
}
public function findByPass($pass) {
$respondent = $this->Respondent->find('first', array('conditions' => array('pass' => $pass)));
return $respondent;
}
And this is the logic for saving the data to the record:
public function registreren() {
if($this->request->isPost()) {
$this->Respondent->id = $id;
if ($this->Respondent->save($this->request->data)){
$this->Flash->success(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
}
}
I thought i got my id through the function checkCodeRespondent() , but that's not working. What am i forgetting or what am i doing wrong? If i need to give more info, i'm happy to help ofcourse.
Update: I read that i need to add echo $form->input('id');, only when i debug($this->request); the id value is empty. What do i need to change in my code?
If you have added hidden field for id then just replace:
$this->Respondent->id = $id;
By:
$this->Respondent->id = $this->request->data['Respondent']['id'];
And in your view, give name="data[Respondent][id]" in the hidden field of id like:
<input type="hidden" name="data[Respondent][id]" value="value of id">
that should work fine for you if no other issues out there.

Cake php RESTfull POST method not working

This is my controller function accepting only two parameters user_id,location.
class UserLocationsController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->UserLocation->create();
if ($this->UserLocation->save($this->request->data)) {
$this->Session->setFlash(__('The user location has been saved.'));
return $this->redirect(array('action' => 'index'));
}
} else {
$this->Session->setFlash(__('The user location could not be saved. Please, try again.'));
}
}
$users = $this->UserLocation->User->find('list');
$this->set(compact('users'));
}
}
when submit the form it is successfully save to data base.but I need to use this with rest client.(without form).I tested it with user_id and location parameters and post method but not saved data to DB.
$this->request->data
is empty when try with rest client. how can I save data without form?

CakePHP: sending latest user id to admin's create_employee view

I am trying to send the latest user's id from UsersController to AdminController whose add_employee() action creates a new employee. My users and employees table are separate and what I want to do is when Admin creates a new user its entry go into users table. Then he opens create employee form and the latest user id will be assigned to the new employee the admin is creating. So when admin will open create new employee form the latest user id will be shown in the form.
My UsersController has this code for sending latest user it to AdminsController:
public function get_latest_user_id()
{
$content = $this->User->query("SELECT id FROM users ORDER BY id DESC LIMIT 0,1");
$this->set('latest_user', $content);
}
AdminsController page's add_employee contains this code:
public function add_employee()
{
$this->loadModel('Employee');
$this->set('latest_user', $this->requestAction('/Users/get_latest_user_id'));
if ($this->request->is('post'))
{
$this->Employee->create();
if ($this->Employee->save($this->request->data))
{
$this->Session->setFlash(__('The employee profile has been saved.'));
return $this->redirect(array('action' => 'list_of_employees'));
}
else
{
$this->Session->setFlash(__('The employee profile could not be saved. Please, try again.'));
}
}
}
So UserController's get_latest_user_id function sends latest user id to add_employee function of AdminController. There latest_user is set to latest user id so that when add_employee view is called it is there. But it is not showing. So I want to know that am i doing it right? Please help and thanks.
In add_employee.ctp I am displaying it like this:
echo $latest_user['User']['id'];
Move get_latest_user_id to the User model
public function get_latest_user_id()
{
$user = $this->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
if (empty($user)) {
return 0;
}
// return only the Id
return $user[0]['users']['id'];
}
In the controller:
public function add_employee()
{
$this->loadModel('Employee');
$this->loadModel('User');
$this->set('latest_user', $this->User->get_latest_user_id());
if ($this->request->is('post'))
{
// ....
}
}
cornelb is right that you should move the method to your User model. Although a more Cake-ish approach would be to use a find('first'), rather than doing a direct query():
// app/Model/User.php
public function getLatest() {
// Get the latest user
$user = $this->find('first', array(
'fields' => array('id'), // Only interested in id? Use this.
'order' => array('User.id' => 'DESC')
));
if (!empty($user)) {
return $user['User']['id'];
} else {
// Nothing was returned, this is very awkward
throw new NotFoundException(__('No users found!'));
}
}
And in your controller:
// app/Controller/AdminsController.php
public function add_employee() {
$this->loadModel('User');
$this->set('latestUser', $this->User->getLatest());
// ...
}

CakePHP saving foreignKeys not working

I have 3 tables: Computers hasMany Brands, Brands belongsTo Computers and Parts. Now i have these fields in my Brands description,computer_id,part_id. I have the code below to save my data. It will save the description and part_id....But my computer_id does not save at all.
Usually my URL written http://192.168.6.253/computers/brands/add/1 where 1 is computer_id.
How will I save it? Im still beginner in this framework
Controller
public function add($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
//Assign value to link computer_id
$data = $this->Brand->Computer->findById($id);
$this->set('computers', $data);
//assign select values to parts select
$this->set('parts', $this->Brand->Part->find('list',
array('fields' => array('description'))));
if ($this->request->is('post')) {
$this->Brand->create();
if ($this->Brand->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
$this->redirect(array('action' => 'table/'.$id));
} else {
$this->Session->setFlash(__('Unable to add your post.'));
}
}
}
View
<?php
echo $this->Form->create('Brand');
echo $this->Form->input('part_id',array('empty'=>' '));
echo $this->Form->input('description');
echo $this->Form->input('computer_id',array('type'=>hidden));
echo $this->Form->end('Save Post');
?>
If you are not requiring to send the computer id through the form since it's a url param... you can adjust your add function like this
if ($this->request->is('post')) {
$this->request->data['Brand']['computer_id'] = $id; //manually add the id to the request data object
$this->Brand->create();
if ($this->Brand->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
$this->redirect(array('action' => 'table/'.$id));
} else {
$this->Session->setFlash(__('Unable to add your post.'));
}
}
That's a very basic way of doing it without checking for data integrity, anyone could easily change the param to a 2, but it conforms with your current setup.

CakePHP check or add user id to posts

I have the following two actions in my controller:
function add()
{
if (!empty($this->data))
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been saved.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
function edit($id = null)
{
$this->Favour->id = $id;
if (empty($this->data))
{
$this->data = $this->Favour->read();
}
else
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been updated.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
1) I want to be able to add the logged in user id to the add action so that the new post is created with that user as its author id (their is a foreign key in the db table). I'm not sure how to talk to fields within the controller itself.
2) And for the edit action I want to make it so that only the author can edit the post so for example user 200 creates post 20 but user 100 cannot edit this post because his id is not 200! I'm not using ACL for my app but just simple authentication.
I've thought about doing a simple if statement in the action like:
function edit($id = null)
{
$this->Favour->id = $id;
$this->Favour->user_id = $user_id;
if($this->Auth->user('id') != $user_id)
{
$this->Session->setFlash('You do not have permission to edit that favour!');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
else
{
if (empty($this->data))
{
$this->data = $this->Favour->read();
}
else
{
if ($this->Favour->save($this->data))
{
$this->Session->setFlash('Your favour has been updated.');
$this->redirect(array('controller'=>'favours','action'=>'index'));
}
}
}
Would this be correct? BUT how do I get the user id from the favour?
function add() {
if (!empty($this->data)) {
$this->data['Favour']['user_id'] = $this->Auth->user('id');
if ($this->Favour->save($this->data)) {
//etc
This code assumes:
Your user is logged in
the user can access the add function
You are storing the id value of the logged in user in the field id
You have a foreign key in Favours table called user_id that matches the data type of the user id
As for edit; couple ways of achieving it.
I'd do:
function edit($id) {
$this->Favour->id = $id;
$favour_author = $this->Favour->field('user_id');
// get the user of this post
if($this->Auth->user('id') != $favour_author) {
$this->Session->setFlash('You do not own this post.');
$this->redirect('/someplace');
}
if (empty($this->data)) {
$this->data = $this->Favour->read();
}
// carry on.
If you use Auth Component, you can access the logged-in user record in $this->Auth->user() in controller. So to access the id: $this->Auth->user('id'). If you write your own authentication, it's up to you.
how to talk to fields within the controller itself.
What do you mean?

Categories