which method of model to update the row in cakephp - cakephp

i have trouble in creating method in controller of cakephp to update the my existing row in a table, can anyone suggest me appropriate model method to update the row in table
<?php
class UsersController extends AppController
{
public function update($id)
{
if(isset($_REQUEST['update']))
{
// method of model to update the row
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}
}
?>

http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array
$this->User->id = $id;
$this->User->save($this->request->data);

Try the code.......
<?php
class UsersController extends AppController {
public function update($id = null) {
if ($id) {
if ($this->request->is('post')) {
$this->User->id = $id;
$this->User->save($this->request->data);
} else {
$this->set('user', $this->User->find('first', array('conditions' => array('id' => $id))));
}
}
}
}
?>

#burzum after reading the tutorial which link provide by you i found the solution to the my problem, in model updateAll() method available in model by using this i have update row of the table.
public function update($id)
{
if(isset($_REQUEST['update']))
{
$this->User->id=$id;
if($this->User->updateAll(array('User.fname'=>"'".$_REQUEST['fname']."'",'User.lname'=>"'".$_REQUEST['lname']."'",'User.email'=>"'".$_REQUEST['email']."'"),array('id'=>$id)))
echo '<script>alert("update successfully")</script>';
else
echo '<script>alert("failes to update ")</script>';
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}

Related

Deleting database rows using cakephp

I'm currently making a newsletter that let users subscribe and unsubscribe. Subscribing is a success but not on unsubscribing. can you help me out guys, here's my codes...
Controller
class AddsController extends AppController {
public $helpers = array('Html','Form','Session','Flash');
public $components=array('Session');
public function index() {
if($this->request->is('post')) //posting to db
{
$this->Add->create();
$this->Add->save($this->request->data);
$this->Flash->set('The user has been saved.', array('element' => 'success'));
return $this->redirect('index'); //redirects to index.ctp
}
}
/*public function delete($email = null) {
if($this->request->is('post')) {
$this->Add->exists($email) {
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
return $this->redirect('index');
}
}
function delete(){ //delete html
$email = $this->request->data['email'];
if($this->Add->exists($email)){
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
//$this->Flash->set('Unsubscribed', array('element' => 'danger'));
return $this->redirect('index');
}
} */
function delete() {
$email = $this->request->data['email'];
if($this->Add->exists($email)){
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
//$this->Flash->set('Unsubscribed', array('element' => 'danger'));
return $this->redirect('index');
}
}
}
View
<?php echo "<section>";
echo $this->Form->create('Add'); //<form > 'modelname'
echo "<label>E-mail:</label>";
echo $this->Form->input('email',array('label'=>false , 'placeholder'=>'your email')); //email input
echo $this->Form->submit('Subscribe'); //subscrib button
echo $this->Form->end();//</form>
echo "</section>";
echo "<section>";
echo $this->Form->delete('Add',array('action'=>'delete')); //<form >
echo "<label>E-mail:</label>";
echo $this->Form->input('email',array('label'=>false , 'placeholder'=>'your email')); //email input
echo $this->Form->submit('Unsubscribe',array('action'=>'index'),array('style'=>'background:red'));
echo $this->Form->end();//</form>
echo "</section>";
My view is just "entering data into db and deleting existed data out the db
Model
<?php
App::uses('AppModel' , 'Model');
class Add extends AppModel
{
public $name = "Add";
public $useTable = 'request';
public $primaryket = 'id';
public $useDbConfig = 'default';
}
db tablename: request; Just the delete row
Thank you in advance!!!
try to use below method (pass unique id of user) hope it will work:
$user = $this-> Add->findByEmail($email);
$this-> Add->delete($user['User']['id'], false);
Alternative way
$userId = $this->User->field('id', array('User.email' => $email));
if($userId) {
$this->User->id = $userId;
$this->User->delete();
$this->log('User of '.$email.' record deleted successfully');
} else {
$this->log('There is no record present of particular email = '. $email);
}

How to save a variable in database in cakephp?

I have two tables in database and two controllers in cakephp, UsersController and DatasController. I wanna save authenticated user`s id in datas table.
Here is my code ...
class DatasController extends AppController{
public function adddam(){
$uid=$this->Auth->user('id');
$datas = $this->Datas->newEntity();
if ($this->request->is('post')) {
$datas = $this->Datas->newEntity();
$this->request->data['user_id'] =$uid;
$datas = $this->Datas->patchEntity($datas, $this->request->data);
$this->Datas->save($datas);
}
}
}
But it does not work correctly.Are there somethings else that I forget?
I gather that you're using CakePhp3 then try this structure to Add 'Datas'
class DatasController extends AppController {
public function adddam() {
$uid = $this->Auth->User()['id'];
$datas = $this->Datas->newEntity();
if ($this->request->is('post')) {
$datas = $this->Datas->patchEntity($datas, $this->request->data);
$datas['user_id'] = $uid;
if($this->Datas->save($datas))
{
$this->Flash->success(__('The datas has been saved.'));
return $this->redirect(['action' => 'adddam']); //Redirect when you want
} else {
$this->Flash->error(__('The datas could not be saved. Please, try again.'));
}
}
$this->set(compact('datas'));
$this->set('_serialize', ['datas']);
}
}

CakePHP 3 - beforeSave callback not working on edit

I have a beforeSave-callback which is called just fine whenever I create a new entity. However when I am editing, it's not called at all.
Could not find anything in the documentation that could be helpful.
Here's my edit function:
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid article'));
}
$article = $this->Articles->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your article.'));
}
$this->set('article', $article);
}
The beforeSave function will be triggered only if the data you post/edit is modified.
//triggers only if an entity has been modified
public function beforeSave(Event $event, Entity $entity)
{
if($entity->isNew()) {
//on create
} else {
//on update
}
}
I also had the problem that the tutorial got stuck on this point, but I used the bin/cake bake command to autogenerate the ArticlesTable code and it added this validator:
$validator
->scalar('slug')
->maxLength('slug', 191)
/*->requirePresence('slug', 'create')*/
->notEmptyString('slug')
->add('slug', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
When I commented the requirePresence() it solved this issue for me. If you have requirePresence('fieldName', 'create') for validation, you will get an error if you don't have that field on a post when creating the new Article entity.
Yes, your need use Event and Entity object:
check this example:
// src/Model/Table/ArticlesTable.php
use Cake\Event\Event;
use Cake\ORM\Entity;
public function beforeSave(Event $event, Entity $entity) {
if ($entity->isNew()) {
return true;
}
// edit code
}
Another way to write the same code:
public function beforeSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options){
if($entity->isNew()) {
// on create
} else {
// on update
}
}

cakephp2.0 Appcontroller function calling

i have created one function in cakephp appcontrollet.php file. that retrive me the detail on that record from that id
the function is mentioned below
function getDetail($id = null) // to check that user is valid or not
{
$data = $this->ModelName->find('first',array('conditions'=>array('ModelName.is_active'=>'Y','ModelName.is_deleted'=>'N','ModelName.primaryKey'=>$id)));
if($data !=array())
{
// return true;
return $data;
} else {
$data = array();
return $data;
//return false;
}
}
Now i want to call this function from any controlller to get detail of the record like i will call this function fron Userscontroller,adminscontroller, marketscontroller etc. and it will return me the related data
my issue is that how should appcontroller know that request is come from which controller and which model to user ?
can anyone help me to solve this
thanks in advance
Put this function to AppModel and call it from each controller with the related model. The function then looks like:
class AppModel extends Model
{
public function getDetail($id = null) {
$data = $this->find('all', array(
'conditions' => array($this->name.'.id' => $id)
));
// ...
Depending on your call from the model it will automatically use the right model. Such a call may look like this:
class UsersController extends AppController
{
public $uses = array('User', 'Market');
public function index()
{
// Fetch data from markets database
$this->Market->getDetail($id);
// Fetch data from users database
$this->User->getDetail($id);
// ...
In this case, the model Market will be used to fetch the details from the database.

Updating a row in cakephp

I need to update a particular row. This doesn't seem to work. Any help is appreciated.
View updated:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Post');
?>
Controller updated:
public function index($id = 0){
$this->Setting->id = $id;
if (empty($this->request->data)) {
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->request->data['Setting']['id'] = $id;
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Edit:
blog_state is a boolean, and works fine. It loads the value from the DB normally and saves it to the new row normally. (I need it to update the existing row it is being pulled from, which is where my problem is)
Update your view:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Page');
?>
You will also need to make sure you set the id in the function so it will populate the value correctly. The record cannot be updated unless it knows the PK ID it is updating.
The way you can accomplish this is by setting it in the request data:
$this->request->data['Setting']['id'] = $id;
Then it will automatically be set in the view.
UPDATE
It looks like your logic may be flawed. The form will not necessarily pass the ID back on the URL. So update you form like so and check again if it works. It looks like the way you currently have it it will set ID to null which will create a new record.
public function index($id = 0){
if (empty($this->request->data)) {
$this->Setting->id = $id;
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Well you need to know what row it is effecting (this will usually be argument to your function).
public function index() {
// Things here
}
This will create the index page for that controller.
Create an edit function like
public function edit($id = null) {
$this->Setting->id = $id;
if (!$this->Setting->exists()) {
// Exception.
}
if ($this->Setting->save($this->request->data)) {
$this->Session->setFlash(__('Saved'));
}
}
Then you can access it like http://example.com/setting/edit/45
Make sure you have primary key id column in your DB if not override the your chosen primary key in model like below.
<?php
class Test extends AppModel{
public $primaryKey = 'primarykey column name';
}
?>

Resources