Dynamic dropdown and save cakephp code not working together - cakephp-2.0

I have three tables 'Categories' , 'Courses' and 'Subjects' with following associations
Category hasMany Course
Course BelongsTo Category, Course hasMany Subject
Subject BelongsTo Course, Subject hasMany Notes
Notes BelongsTo Subject
When I try to save the data it's giving the error
'Call to a member function create() on null'.
class SubjectsController extends AppController {
public $uses = array('Category','Course');
public function add(){
pr($this->request->data);die;
if ($this->request->is('post')) {
pr($this->request->data);die;
$this->Subject->create();
if ($this->Subject->save($this->request->data)) {
$this->Flash->success(__('The subject has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The subject could not be saved. Please, try again.'));
}
}
}
}

It has nothing to do with your Ajax. It's telling you right in the error message. You're trying to call the create function from a null object. In this case, $this->Subject.
You have $this->uses the Category and Course models, but not Subject. You can either add that to the list of what this controller uses, or you can get to it via the existing association with something you're already using: $this->Course->Subject.

Make sure that the retrieved data is correct an than do it like this:
$this->Subject->create();
$this->Subject->set(array($this->request->data);
$this->Subject->save();

Related

Cakephp 3 saving to an different table

Hi dear Stackoverflowers, im new to CakePHP 3 and if got a Problem with saving into the Database. Im using CakePHP 3. I want to save the Data of a survey into a SQL-DatabaseTable other than the one of the Controller ("First" in this case).
It works so far but i can only save data for one time. After that it shows:
"Your Feedback could not be saved. Please, try again.". If I delete the data in the sql table, it works again, but i have to be able to save multiple times.
I have created a model for "TestSurvey". It has the same content in table and entity as "First". Please notice if I use the normal model of "First" everything works fine and i can save multiple times. Thank you for your help.
(no native english speaker here)
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Network\Request;
use Cake\ORM\TableRegistry;
class FirstController extends AppController
public function index()
{
$first = $this->paginate($this->First);
$this->set(compact('first'));
$this->set('_serialize', ['first']);
}
public function localtest()
{
$testSurveyTable = TableRegistry::get('TestSurvey');
$testSurvey = $testSurveyTable->newEntity();
if ($this->request->is('post')) {
$testSurvey = $testSurveyTable->patchEntity($testSurvey, $this->request->data);
if ($testSurveyTable->save($testSurvey)) {
$this->Flash->success(__('Your Feedback has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Your Feedback could not be saved. Please, try again.'));
}
}
$this->set(compact('testSurvey'));
$this->set('_serialize', ['testSurvey']);
}

CakePHP: Limit associations in the controller

As an example lets imagine we have a simple tv show database. Show and Episode as Model.
An Episode belongsTo one Show and one Show hasMany Episodes.
In the episodes/index view we are just echoing all episodes, the same goes for the shows/index view. But I also want to echo lets say the first 5 episodes of each show (just the title). I could simply limit the episodes by setting the limit attribute for the hasMany association.
In shows/episode/x(id) view I want to echo all episodes. And therefore I can't simply use the limit attribute for the hasMany association since it is view dependent.
What solution should I choose to implement that? I could only archive that by using some "dirty workarounds/hacks" but I feel like this is an usual problem and there might be some actual solution.
I believe what you are looking for is the containable behaviour.
Read the doc:
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Then remove any limit to your associations. Below there is a way of how you can use containable behavior in your example.
class Shows extends AppModel {
public $actsAs = array('Containable');
}
class ShowsController extends AppController {
//Bring all the shows and 5 episodes
public function index(){
$this->Show->find('all', array('contain' => array(
'Episode' => array('limit' => 5)
)));
}
public function view($id){
//Bring the show
$this->Show->findById($id);
//Then bring the episodes of the show
$this->Show->Episode->findByShowId($id);
//Or you can use
$this->Show->find('all', array(
'contain' => array('Episode')),
'conditions' => array('id' => $id)
);
}
}

cakephp use another model within model

I have two models named message.php and user.php
In message.php, I have following method that counts #no of messages of verified users.
<?php
class Message extends AppModel {
...
...
...
function getInboxCount($userId) {
// Here I want to get list of ids of verified users. It means I need to use User model for this. How is it possible?
// $ids = $this->User->find('list', array('conditions' => array('User.status' => 'verified'))); Will this work?
}
}
?>
So how can I use User model in Message model?
If the two models are associated in any way (Message belongsTo User or so), you can access it simply with:
$this->User->find(...);
If they're not associated, you can import any other model at any time using:
$User = ClassRegistry::init('User');
$User->find(...);

Cakephp Model Association Not kicking in

//index.ctp, this forms points to action updateData in profilesController
$this->Form->input('User.lastname');
$this->Form->input('Profile.age');
$this->Form->input('Profile.height');
$this->Form->input('Associate.city');
$this->Form->end('Submit');
//user.php
Class User extends AppModel {
var $hasOne = array('Profile', 'Associate'};
var $primaryKey = 'user_id';
}
//profile.php
Class Profile extends AppModel {
var $belongsTo = array('User');
var $hasOne = 'Associate';
var $primaryKey = 'user_id';
}
//associate.php
Class Associate extends AppModel {
var $belongsTo = array('User');
var $primaryKey = 'user_id';
}
//profiles_controller.php
Class ProfilesController extends AppController{
function updateData(){
//output incoming request for debugging purposes
debug($this->request->data);
//here i fetch the db to get the id of user
$options =
array('conditions' => array('User.username' => $this->Auth->user('username')),
'fields' => array('User.id')
);
//find user id so we can find user in related tables
$id = $this->Profile->User->find('first', $options);
//here I modify request data so cakephp finds the users through primaryKeys
$this->request->data['Profile']['user_id'] = $id['User']['id'];
$this->request->data['Associate']['user_id'] = $id['User']['id'];
$this->request->data['User']['id'] = $id['User']['id'];
if($this->request->is('post'){
//this updates data in table no problem
$this->Profile->save($this->request->data);
//this updates data in table no problem either
$this->Profile->Associate->save($this->request->data);
//this returns false...it breaks here
$this->Profile->User->save($this->request->data);
}
}
}
Table structure:
User
|id|int|auto increment
|firstname|varchar
|lastname|varchar
|date|timestamp
Profile
|id|int|autoincrement
|user_id|int
|age|int
|height|int
Associate
|id|int|autoincrement
|user_id|int
|city|varchar
|country|varchar
Ok I know what some of you might tell me, why do I do this on the profilesController and
not on the UsersController. Well, my idea is to separate some actual important user
data from the profile data so it's my intention to write the code for profile on the ProfilesController...as I was developing I was assuming that the same Model association would have automatically updated the User.lastname field in the User table..but that is the part where my code breaks and I have tried but I can't make it work
The current association in my mind at least is as follows:
User has one Profile
User has one Associate
Profile belongs to User
Associate belongs to Profile and User
Can anyone tell me what am I doing wrong? i am following what I think is a logical approach for my application, cakephp updates Profile and Associate models but User remains unaffected.
Assuming the primaryKey of your users table is 'id', just remove all of the $primaryKey lines, and try again.
The only reason to set the primary key is if it doesn't follow the default that CakePHP has in place. I would GUESS (can't see your tables) that the primaryKey field in your 'users' table isn't 'user_id' - more likely it's just 'id', and in the other tables, it's 'user_id'. If that's the case, there's no need to specify the $primaryKey, since that's the default of CakePHP.
As it turns out after reading the cakephp documentation (and obviously being a n00b) the reason why my code was breaking is because I had a callback beforeSave in my model. I didn't know that in order to save data I had to disable the callback which was unrelated to the part of the code I presented to you. The solution in a case like this is to do as follows:
$this->Profile->User->save($this->request->data, array('callbacks' => false));
I don't know you guys but sometimes I feel the cakephp documentation is a little too simplistic, I discover this by looking at the API.

Controller not found in cakePHP

I have controller class EmployeeController in employee_controller.php file,and i have a model class Employee in employee.php ,database table is employees ,All the functions are working (such as findall() and read() are working fine),but i have add function which is like this
function add() {
if (!empty($this->data)) {
if ($this->Employee->save($this->data)) {
$this->Session->setFlash('Employee has been saved.');
$this->redirect(array('action' => 'index'));
}
When i tried to save ,An error EmployeesController not found will display and shows the following code
<?php
class EmployeesController extends AppController {
var $name = 'Employees';
}
?>
i am not able to solve this problem ,please help me out to get rid of this problem
The file should be called employees_controller.php, not employee_controller.php.
All controller files are named in the plural.
You can also learn about the naming of the tables and the conventions at http://cakeapp.com
I don't know if the question is still important, but the cakephp convention says that filenames for controllers must be in plural an without underscores, so your controller file should be named EmployeesController.php.

Resources