Saving data to database - php

I'm quite new to CakePHP so my question is hopefully quite easy to answer.
I want to create a form for adding a new recipe and recipeitem at the same time. How do I do that?
I have three tables in my database: recipes, recipeitems and recipes_recipeitems;
eg. Recipe.title
Recipe.cookingtime
Recipeitem.name
I tried the following but it only created a Recipepart without setting it's name or recipe_id.
Form:
<?php echo $this->Form->create('Recipe'); ?>
<fieldset>
<legend><?php echo __('Create recipe'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('cooking_time');
echo $this->Form->input('RecipeitemName');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
RecipeController:
App::import('model','RecipeItem');
class RecipesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->request->data['Recipe']['user_id'] = $this->Auth->user('id');
$this->request->data['RecipeItem']['name'] = $this->request->data['Recipe']['RecipeitemName'];
$newRecipeItem = new RecipeItem();
$this->Recipe->create();
if ($this->Recipe->save($this->request->data)) {
$this->Session->setFlash(__('The recipe has been saved'));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The recipe could not be saved. Please, try again.'));
}
$this->request->data['RecipeItem']['recipe_id'] = $this->Recipe->id;
if ($newRecipeItem->save($this->request->data)) {
$this->Session->setFlash(__('The recipeItem has been saved'));
$this->redirect(array('action' => 'index'));
} else{
$this->Session->setFlash(__('The recipeItem could not be saved. Please, try again.'));
}
}
}

$newRecipeItem = new RecipeItem();
This line is not doing what you think. It creates an instance of the RecipeItem class. But it does not make an INSERT in the database. So this line:
$newRecipeItem->save($this->request->data)
does nothing. You could use:
$this->Recipe->RecipeItem->create();
then do a save.
create() function doc

Related

Cannot Edit the data saved in the database

I'm using cake php for project, but i cannot edit the data i saved in the database. The edit function i used in the controller looks like below.
public function edit($id = null) {
if (!$this->Seller->exists($id)) {
throw new NotFoundException(__('Invalid seller'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Seller->save($this->request->data)) {
$this->Session->setFlash(__('The seller has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The seller could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Seller.' . $this->Seller->primaryKey => $id));
$this->request->data = $this->Seller->find('first', $options);
}
}
My edit.ctp file looks like below.
<div class="sellers form">
<?php echo $this->Form->create('Seller'); ?>
<fieldset>
<legend><?php echo __('Edit Seller'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email');
echo $this->Form->input('phone_no');
echo $this->Form->input('address');
echo $this->Form->input('latitide');
echo $this->Form->input('longitude');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('product_type');
echo $this->Form->input('product_description');
echo $this->Form->input('approval');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('Seller.id')), array(), __('Are you sure you want to delete # %s?', $this->Form->value('Seller.id'))); ?></li>
<li><?php echo $this->Html->link(__('List Sellers'), array('action' => 'index')); ?></li>
</ul>
</div>
I can save and delete data in the database, but when i edit the saved data, saved changes are not getting saved. Please help me with this. Thanks in advance.
You need this :
$this->Seller->primaryKey= $id;
just before the first if .
edited - code working
public function edit($id = null) {
$this->Category->id = $id;
if (!$this->Category->exists()) {
throw new NotFoundException(__('Invalid category'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('Catégorie modifiée avec succès'),array('action' => 'index'));
} else {
$this->flash(__('Categorie pas modifiée...Réessayer Plus tard'),array('action' => 'index'));
}
} else {
$this->request->data = $this->Category->read(null, $id);
}
}
The reason you are able to add/delete, and not edit is because the primary key is not being submitted with the form. $id will only be there on initial page load, not when the form is submitted, since it then relies on the id being in $this->request->data. A good way to check if this is the case is to look in the database table you are saving to. If there is a new inserted record with the data you are trying to save, then this is it.
public function edit($id = null) {
$this->Seller->id = $id
if (!$this->Seller->exists($id)) {
throw new NotFoundException(__('Invalid seller'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Seller->save($this->request->data)) {
$this->Session->setFlash(__('The seller has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The seller could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Seller->read(null, $id);
}
}
#may was correct, only he was referring to a different Model name than what you were using: it should be Seller not Category.
I would also change your find() call to use read() instead:
$this->request->data = $this->Seller->read(null, $id);

Assigning current user_id as foreign value in a different table

I have the following tables users(id, name, email), articles(id, user_id, title, body). I can't seem to populate the user_id in articles table with the logged in user_id. This is my code.
//articles controller
public function add() {
if ($this->request->is('post')) {
$this->Article->create();
$this->request->data['Article']['user_id'] = $user_id;
if ($this->Article->save($this->request->data)) {
$this->Session->setFlash(__('The article has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
}
}
$users = $this->Article->User->find('list');
$this->set(compact('users'));
}
The above method returns a null value for user_id in articles
I also tried retrieving from the view:
echo $this->Form->hidden('user_id', arrray('value' => $userAuth['id']));
I get the following error
syntax error, unexpected '=>' (T_DOUBLE_ARROW)
echo $this->Form->hidden('user_id', arrray('value' => $userAuth['id']));
Should be,
echo $this->Form->hidden('user_id', array('value' => $userAuth['id']));
Typo in arrray (3 times a R).
try this:
public function add() {
if ($this->request->is('post')) {
$this->Article->create();
if ($this->Article->save($this->request->data)) {
$this->Session->setFlash(__('The article has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The article could not be saved. Please, try again.'));
}
else{
$this->set('user_id', $userAuth['id']);
$users = $this->Article->User->find('list');
$this->set(compact('users'));
}
}
in the view
echo $this->Form->hidden('Article.user_id', arrray('value' => $user_id));
But I don't know where you set $userAuth, be secure that you assign this variable before get its value

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.

how to return an ajax request response(data ) to client in cakephp 2.3

i am trying to add to database using ajax in cakephp 2.3, but don't know how to set the response but to the user with additional data which i would have used
$this->set()
for a normal request
the view file :
echo $this->Form->create(); echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('message');
echo $this->Js->submit('Send Enquiry', array(
'before' => $this->Js->get('#sending')->effect('fadeIn'),
'success' => $this->Js->get('#sending')->effect('fadeOut'),
'update' => '#success',
'async' => true
));echo $this->Form->end();?>
and the controller function is:
public function add() {
if ($this->request->is('post')) {
$this->Contact->create();
if ($this->Contact->save($this->request->data)) {
if($this->request->isAjax()){
$this->autoRender = false;
echo 'successful';
}else{
$this->Session->setFlash(__('The contact has been saved'));
$this->redirect(array('action' => 'index'));
}
} else {
$this->Session->setFlash(__('The contact could not be saved. Please, try again.'));
}
}
}
sorry is if my question was wrongly phrased but i found the solution to my problems
i used the snippet below to grab the validation errors.
if($this->request->isAjax()){
$this->autoRender = false;
if($this->Contact->validates()){
}else{
$error = implode($this->Contact->validationErrors;
echo $error;
}
}
thanks all the same

MVC undrestandig

i research about mvc and n-tier architecture different. but i can't understand how model pass data to view in mvc?
for example in cakephp I have an controller and action like this:
function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid user', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The user has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
in this section:
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid user', true));
$this->redirect(array('action' => 'index'));
}
we check that id passed or not. if have not be set we redirect user. than:
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The user has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
if submitted data from view we update row in db. then :
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
and if id have been set and if not data submitted its mains the page early opened and data in relation this id will be read from db and displayed in view.
now I can't understanding how and where model pass data to view in this cakephp's standard mvc????
thanks for help.
Models do not send data to the view. controllers do, by calling the set method. controllers use models to get data from database and then send it to the view:
$this->set('myVariable','myValue');
or you can use compact to send complex data at once like in your example:
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));

Categories