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']);
}
Related
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();
So I have a company based system and I am keeping all data within the one database and I separate the data by using a site_id field which is present in all tables and in the users table.
Now at the moment I am doing a condition on every single find('all'). Is there a more global way to do this. Maybe in the AppController? Even for saving data I am having to set the site_id every single save.
Something like
public function beforeFilter() {
parent::beforeFilter();
$this->set('site_id', $this->Auth->user('site_id'));
}
Any direction would only help. Thanks
TLDR:
Create a Behavior with a beforeFind() method that appends a site_id condition to all queries.
Example/Details:
Create a behavior something along the lines of the below. Note, I'm getting the siteId from a Configure variable, but feel free to get that however you want.
<?php
class SiteSpecificBehavior extends ModelBehavior {
public function setup(Model $Model, $settings = array()) {
$Model->siteId = Configure::read('Site.current.id');
}
public function beforeFind(Model $Model, $query = array()) {
$siteId = $Model->siteId;
$query['conditions'][$Model->alias . '.site_id'] = $siteId ;
return $query;
}
}
Then on any/all models where you want to make sure it's site-specific, add:
public $actsAs = array('SiteSpecific');
This can be tweaked and improved up certainly, but it should give you a good idea.
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(...);
//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.
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.