Cakephp use saveAll and specify which models only - cakephp

Im new to relatively new to cakephp, right now I'm trying to use saveall() and save individual models depending on the role the user chose for the register.
Here is my View:
<?php echo $this->Form->create('User', array('type' => 'file')); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->file('User.user_image');
echo $this->Form->input('User.name', array( 'label' => 'Nombre'));
echo $this->Form->input('User.last_name', array( 'label' => 'Apellidos' ));
echo $this->Form->input('User.email', array( 'label' => 'E-Mail' ));
echo $this->Form->input('User.password', array( 'label' => 'Contraseña' ));
echo $this->Form->input('User.phone', array( 'label' => 'Telefono' ));
//echo $this->Form->input('created_ip_connection');
//echo $this->Form->input('last_ip_connection');
echo $this->Form->input('User.group_id', array('empty' => 'Elige un rol', 'label' => 'Rol de Usuario'));
?>
<div style="display: none;" id="companyAdd">
<legend><?php echo __('Datos de Compañia'); ?></legend>
<?php
echo $this->Form->input('Address.exterior_number', array( 'label' => 'Numero Exterior', 'required' => false ));
echo $this->Form->input('Address.internal_number', array( 'label' => 'Numero Interior', 'required' => false ));
echo $this->Form->input('Address.street', array( 'label' => 'Calle', 'required' => false ));
echo $this->Form->input('Address.suburby', array( 'label' => 'Colonia', 'required' => false ));
echo $this->Form->input('Address.country_id', array('empty' => 'Selecciona País', 'label' => 'Pais', 'required' => false));
echo $this->Form->input('Address.state_id', array('empty' => 'Selecciona País', 'label' => 'Estado', 'required' => false));
echo $this->Form->input('Address.city_id', array('empty' => 'Selecciona Estado', 'label' => 'Municipio', 'required' => false));
echo $this->Form->input('Company.name', array( 'label' => 'Nombre de Compañia', 'required' => false ));
echo $this->Form->input('Company.description', array( 'label' => 'Descripción de Compañia', 'required' => false ));
echo $this->Form->input('Company.bank_acc', array( 'label' => 'Cuenta de Banco', 'required' => false ));
echo $this->Form->input('Company.rfc', array( 'label' => 'RFC', 'required' => false ));
?>
</div>
<div style="display: none;" id="userAdd">
<legend><?php echo __('Datos de Comprador/Proveedor'); ?></legend>
<?php
echo $this->Form->input('Buyer.company_id', array('empty' => 'Elige Comapñia', 'label' => 'Compañia', 'required' => false));
?>
</div>
</fieldset>
<?php echo $this->Form->end(__('Registrar')); ?>
Here is my controller:
public function register(){
$this->layout = 'generalLayout';
if ($this->request->is('post')) {
if($this->request->data['User']['group_id'] == 1){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data['User'])) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 2){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 3){
$this->Session->setFlash(__('Group 3 Happened'));
return $this->redirect(array('action' => 'register'));
}
/*$this->Session->setFlash(__('Nothing Happened'));
return $this->redirect(array('action' => 'register'));*/
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
$companies = $this->User->Company->find('list');
$this->set(compact('companies'));
}
And my models relations
public $hasOne = array(
'Buyer' => array(
'className' => 'Buyer',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Company' => array(
'className' => 'Company',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Provider' => array(
'className' => 'Provider',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
I want to either send only the information needed (Meaning the models depending on the group chosen.) through the form to the controller. or in the controller use only the models sent to save the models that I want. How could I make this work. saveAll does not work cause Im sending other models with no information through the form as well. How could I make this work ?
Also how do I get the id of the user I just saved?

Ok I found out how to do it. I used the Saving Related Model Data method. I just use the information I want from the data send by the form depending on the type of the user being created. I left the view and the model untouched. I only changed the controller for the parts of when the group_id is 2(Normal User) and 3(Semi-Admin User). Using the model relations and the information being sent I could use the save() method with each model depending on the information I was given. Here is the code I hope It helps someone:
$this->layout = 'generalLayout';
if ($this->request->is('post')) {
if($this->request->data['User']['group_id'] == 1){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data['User'])) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 2){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->save($this->request->data['User'])) {
//Obtener el Id de user guardado
$userId = $this->User->id;
$this->request->data['Buyer']['user_id'] = $userId;
$this->request->data['Provider'] = $this->request->data['Buyer'];
if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 3){
/*echo print_r($this->request->data);
return false;*/
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
//Save the user
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->save($this->request->data['User'])) {
//Get the id of the user I just saved
$userId = $this->User->id;
if ($this->User->Company->Address->save($this->request->data["Address"])) {
$addressId = $this->User->Company->Address->id;
$this->request->data['Company']['user_id'] = $userId;
$this->request->data['Company']['address_id'] = $addressId;
$this->request->data['Company']['permision'] = true;
if ($this->User->Company->save($this->request->data["Company"])) {
$companyId = $this->User->Company->id;
$this->request->data['Buyer']['user_id'] = $userId;
$this->request->data['Buyer']['company_id'] = $companyId;
$this->request->data['Provider'] = $this->request->data['Buyer'];
if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The Address could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
/*$this->Session->setFlash(__('Nothing Happened'));
return $this->redirect(array('action' => 'register'));*/
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
$companies = $this->User->Company->find('list');
$this->set(compact('companies'));

Related

cakephp 2, edit record in modal by bootstrap

How to edit a record with Cakephp and modal bootstrap?
Because when I edit a contact, I get the error 500?
missing view The view for UserContactsController:: admin_modal_edit()
was not found.
In to controller admin_modal_edit() I have set $this->layout = NULL;
These are the files of the app.
File: user/view.ctp with list of contact and the modal for add or edit.
BUTTON FOR EDIT OR DELETE
<?php echo $userContact['UserContactType']['title']; ?>: <?php echo $userContact['contact']; ?>
<?php echo __('Edit'); ?>
BOOTSTRAP MODAL
<?php
echo $this->Form->create('UserContact', array('url' => array('admin' => true, 'prefix' => 'admin', 'plugin' => 'user', 'controller' => 'user_contacts', 'action' => 'modal_edit')));
?>
<?php echo $this->Form->input('UserContact.id', array('class' => 'form-control')); ?>
<?php echo $this->Form->input('UserContact.user_id', array('default' => $user_id, 'type' => 'hidden')); ?>
<?php echo $this->Form->input('UserContact.user_contact_type_id', array('class' => 'form-control', 'empty' => true)); ?>
<?php echo $this->Form->input('UserContact.contact', array('class' => 'form-control')); ?>
<?php echo $this->Form->submit(__('Save'), array('div' => false, 'class' => 'btn btn-success')); ?>
<?php echo $this->Form->end(); ?>
File: controller/UsersController.php that generates view.ctp
public function admin_view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$user_id = $id;
$options = array(
'contain' => array('UserContact' => 'UserContactType', 'UserGroup', 'UserState', 'UserGender', 'UserAddress' => 'UserAddressType', 'UserPaymentType', 'Item', 'Comment'),
'conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
// blocco find list
$userContactTypes = $this->UserContactType->find('list');
$userAddressTypes = $this->UserAddressType->find('list');
$this->set(compact(array('userContactTypes', 'userAddressTypes', 'user_id')));
}
File: controller/UserContactsController.php for the modal
public function admin_modal_edit() {
$id = $this->request->query('id');
$this->layout = NULL;
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}
Your issue is that CakePHP is trying to render the 'admin_modal_edit.ctp' View template.
If you don't want CakePHP to render anything set autoRender to false:-
public function admin_modal_edit() {
$this->autoRender = false;
}
This will prevent CakePHP from looking for a View template to render.
$this->layout = null does not stop Cake from attempting to render templates. Which I suspect is what you're trying to achieve.
This error is showing because cakephp is complaining about the function admin_modal_edit for not having a view since it cannot find the admin_modal_edit.ctp in the view folder of your controller.
To fix this, add this
$this->autoRender = false
to your function admin_modal_edit to disable the rendering of view for that function.
So your function should look like this.
public function admin_modal_edit() {
/** -------------- **/
$this->autoRender = false;
/** -------------- **/
$id = $this->request->query('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}

Undefined index: images.jpg [APP\Controller\PostController.php, line 19]

<!-- File: /app/View/Posts/add.ctp -->
<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->file('Post.Image');
echo $this->Form->input('Post.name', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>
<!-- File: /app/Controler/PostControler.php -->
public function add() {
if ($this->request->is('post') ) {
$filename=$this->request->data('Post.Image');
$filename = "app/webroot/img/uploads/".$_FILES[$filename]['name'];(line 19)
$tempname=$this->request->data('Post.Image');
if((move_uploaded_file($_FILES[$tempname]['tmp_name'],$filename))){ (line 21)
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('save images successful.'));
redirect();
$this->redirect('/posts/upload');
}}else{
$this->Session->setFlash(__('not save images.'));}
}
}
the code above 2 error
Undefined index: images.jpg [APP\Controller\PostsController.php, line 19]
Undefined index: images.jpg [APP\Controller\PostsController.php, line 21]
I was getting same error, but I solved it. Here is my view and controller code related to image. The column name in my database table is "picture".
view file form input tag
<?php
echo $this->Form->file('picture', array('class'=>'form-control'));
?>
controller file :: PostController.php
public function addNewPost() {
$this->layout = false;
if ($this->request->is('post')) {
$data = $this->request->data; //echo '<pre>'; print_r($data); die;
if (!empty($data['Post']['picture']['name'])) {
$file = $data['Post']['picture'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
if (in_array($ext, $arr_ext)) {
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/postimages/' . $file['name']);
$this->request->data['Post']['picture'] = $file['name'];
//echo '<pre>'; print_r($data); die;
}else{
$this->Session->setFlash(__('Please upload a valid image.'), 'default', array('id' => 'flashMessage', 'class' => 'alert alert-danger'), 'error');
}
}
$path = $data['Post']['picture']['name'];
if(isset($path)){
$data['Post']['picture'] ='postimages/' . $path;
}
$data['Post']['picture'] ='postimages/default.jpg';
//echo '<pre>'; print_r($data); die;
if ($this->Post->save($data)) {
$this->Session->setFlash(__('Congrats !!! Post Published to our blog. Thanks for posting.'), 'default', array('id' => 'flashMessage', 'class' => 'alert alert-success'), 'success');
return $this->redirect(array('controller' => 'dashboard', 'action' => 'addNewPost'));
} else {
$this->Session->setFlash(__('The Post could not be published. Please, try again.'), 'default', array('id' => 'flashMessage', 'class' => 'alert alert-danger'), 'error');
}
}
}

form data not saving and not update image files and filed name in multiple tables

in this editdrprofile.ctp file not retrieves gender field value and when am click save Drprofile link in editprofile page no action donne page refreshing no image uploaded nothing changed
app/Controller/DashboardsController.php
public function index() {
$this-> loadModel('Drprofile');
$this->set('variable', $this->Drprofile->find('all', array('conditions' => array('Drprofile.user_id' => $this->Auth->user('id')))));
}
public function editdrprofile($id = null) {
$this-> loadModel('Drprofile');
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Drprofile->findByuser_id($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('Drprofile', 'put'))) {
$this->Drprofile->user_id = $id;
// $this->set('posts', $this->carrier->find('all'));
if($this->request->is('post')){
Configure::read();
// pr($this->data);
$this->Carrier->create();
$filename = null;
if (
!empty($this->request->data['Drprofile']['image']['tmp_name'])
&& is_uploaded_file($this->request->data['Drprofile']['image']['tmp_name'])
) {
// Strip path information
$filename = basename($this->request->data['Drprofile']['image']['name']);
move_uploaded_file(
$this->data['Drprofile']['image']['tmp_name'],
WWW_ROOT . DS . 'documents' . DS . $filename
);
//$this->data['Carrier']['Resume'] = $filename;
}
//pr($filename);
// Set the file-name only to save in the database
$this->request->data['Drprofile']['image'] = $filename;
pr($this->data);
if ($this->Drprofile->save($this->request->data)) {
// ...
/*if ($this->Carrier->save($this->request->data)) {
if ($this->Carrier->save($this->data)) {
*/
$this->Session->setFlash(__('Your Details has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add your Details'));
}
}
/*pr_('$this->Drprofile->user_id = $id');
if ($this->Drprofile->save($this->request->data)) {
//$this->Drprofile->save($this->request->data);
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));*/
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
in model
app/model/Drprofile.php
<?php class Drprofile extends AppModel {
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
in view/dashboards/index.ctp
<?php
foreach ($variable as $post1):
?>
<table>
<tr><h3>Doctor Profile</h3></tr>
<tr> <td>TTTTTTTTTTTTTTTTTTTTTTTTTTTT</td> <td><table>
<tr><td>Name</td><td><?php echo $post1['User']['fullname'];?></td></tr>
<tr><td>Email</td><td><?php echo $post1['User']['email'];?></td></tr>
<tr><td>Mobile</td><td><?php echo $post1['User']['contactnumber'];?></td></tr>
<tr><td>Gender</td><td><?php echo $post1['User']['gender'];?></td></tr>
<tr><td>D.O.b</td><td><?php echo $post1['Drprofile']['dob'];?></td></tr>
<tr><td>Experience</td><td><?php echo $post1['Drprofile']['exp'];?></td></tr>
</table></td></tr>
</table>
<?php
echo $this->Html->link(
'Edit Profile', array('action' => 'editdrprofile', $post1['Drprofile']['user_id'])
);
?>
<?php
endforeach; ?>
app/view/editdrprofile.ctp
<h1>Edit Post</h1>
<?php
echo $this->Form->create('Drprofile');
?>
<table>
<tr><h3>Edit profile</h3></tr>
<tr><td>Name</td><td><?php echo $this->Form->text('User.fullname'); ?></td></tr>
<tr><td>Email</td><td><?php echo $this->Form->text('User.email'); ?></td></tr>
<tr><td>Mobile</td><td><?php echo $this->Form->text('User.contactnumber'); ?></td></tr>
<tr><td>Gender</td><td><?php
$options=array('M'=>'Male','F'=>'Female');
$attributes=array('legend'=>false);
echo $this->Form->radio('User.gender',$options,$attributes);
?></td></td></tr>
<tr><td>D.O.b</td><td><?php echo $this->Form->text('dob'); ?></td></tr>
<tr><td>Experience</td><td><?php echo $this->Form->select('exp', array('options' => array('1 year','2 years ','3 years','4 years','5-10 years'))); ?></td></tr>
<tr><td><?php echo $this->Form->input('drprofile.Resume', array('between'=>'<br />','type'=>'file'));?></td></tr>
<tr><td><?php echo $this->Form->end('Save Drprofile');?></td></tr>
<?php /*?><?php echo $this->Form->input('id', array('type' => 'hidden'));?><?php */?>
</table>
First thing you are doing this in Dashboards controller, and you are creating data for Drprofile. If you in the end you want to do it in DashboardsController then you should change your from to this:
echo $this->Form->create('Drprofile', array(
'url' => array('controller' => 'dashboards', 'action' => 'editdrprofile')
));
This way you are telling form what action to use. But I would suggest you move that to DprofilesController and edit that data there.
One more thing, you closed your form there and you place $this->Form->input for id after it, change that.

CakePHP Edit Not Loading foreign Table Data

I am trying to get my edit to work I need the contact detail data to load when the user data loads. I have set the data in a similar manner to how I am retrieving the list of roles. I also don't know how to retrieve according to the model currently I was hard-coding it to retrieve 28. Would greatly appreciate any help provided.
public function edit($id = null) {
//Populate roles dropdownlist
$data = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set('roles', $data);
$data2 = $this->User->ContactDetail->find('first', array(
'conditions' => array('ContactDetail.id' =>'28')));
$this->set('contactdetails', $data2);
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
my view is set up in the following manner
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Edit User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role_id');
echo $this->Form->input('ContactDetail.name');
echo $this->Form->input('ContactDetail.surname');
echo $this->Form->input('ContactDetail.address1');
echo $this->Form->input('ContactDetail.address2');
echo $this->Form->input('ContactDetail.country');
echo $this->Form->input('ContactDetail.email');
echo $this->Form->input('ContactDetail.fax');
?>
<label>Are you interested in buying property in Malta?</label>
<?php
$interest_buy = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE));
?>
<label>Are you interested in renting property in Malta?</label>
<?php
$interest_rent = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE));
echo $this->Form->input('ContactDetail.mobile');
echo $this->Form->input('ContactDetail.phone');
echo $this->Form->input('ContactDetail.postcode');
echo $this->Form->input('ContactDetail.town');
echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,));
?>
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
User Model
public $primaryKey = 'id';
public $displayField = 'username';
public function bindNode($user) {
return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']);
}
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password(
$this->data['User']['password']
);
return true;
}
public $belongsTo = array(
'Role' => array('className' => 'Role'));
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id'));
public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['role_id'])) {
$roleId = $this->data['User']['role_id'];
} else {
$roleId = $this->field('role_id');
}
if (!$roleId) {
return null;
} else {
return array('Role' => array('id' => $roleId));
}
}
}
ContactDetail Model
public $primaryKey = 'id';
public $displayField = 'name';
If I get you right, you have 1 contact details row for each user. In this case, you need to define in your User model:
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id',
),
);
Like this, your ids will be synced in both tables. If you don't want to make the id a foreign key, you don't have to, it's just a suggestion.
Next, when you retrieve your data in the controller, you can do:
$this->User->Behaviors->load('Containable');
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('ContactDetail'),
));
Now I don't know if there is an automated way to do this, but I sort my data manually to fill in the inputs. I am guessing you will get a structure like array('User' => array(), 'ContactDetail' => array()).
$user['User']['ContactDetail'] = $user['ContactDetail'];
unset($user['ContactDetail']);
$this->request->data = $user;
Then in your view just set the fields as the input array:
$this->Form->create('User');
$this->Form->input('User.some_user_field');
$this->Form->input('User.ContactDetail.some_contact_detail_field');
This should fill in your fields. When you go save your data, if your array is structured like this, you can use saveAssociated():
$this->User->saveAssociated($this->request->data, array('deep' => true));
EDIT
In case your relation is defined as User hasMany ContactDetail, then you need to structure your data like this:
$this->request->data = array(
'User' => array(
// user data
'ContactDetail' => array(
[0] => array(
//contact data
),
),
),
);
And in your view:
$this->Form->input('User.ContactData.0.field')
This is for 1 row only, If you need more rows on the child table with 1 input, do your logic accordingly.
Once your User model hasOne ContactDetail, you don't need retrieve the information twice, since you've done in $this->request->data line, all association model will retrieve too.
So, your Controller looks like this:
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
// Roles
$roles = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set(compact('roles');
if ($this->request->is(array('post', 'put'))) {
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
}
And your View, for ContactDetail's fields looks like this:
echo $this->Form->input('ContactDetail.name');
And so for all the fields related to the model ContactDetail. You can find more details here: Saving Your Data.
User model:
public $hasOne = array(
'ContactDetail' => array(
'className' => 'ContactDetail',
'foreignKey' => 'user_id',
'dependent' => true
)
);
The best solution I have found is by setting
public $belongsTo = array(
'Role' => array('className' => 'Role')
, 'ContactDetail' => array('className' => 'ContactDetail'));
This way the contact detail data loads. Although the data once saved does not update contactdetails.
For me to save I used
$this->User->saveAll($this->request->data)
this worked fully

Issue deleting items with filter search

I am developing a plugin for CakePHP 2.
My problem is below:
I have a view with a filter search, where users can search by category:
<div>
<?php echo $this->Form->create('Permission'); ?>
<fieldset>
<?php echo $this->Form->input("permissionCategory", array('label' =>
__d('permission_manager','Categoría'), 'options' => $categorias, 'empty' =>
__d('permission_manager','-- Categorías --'), 'default' => '','class' => 'select-cat', 'onchange' => 'this.form.submit()')); ?>
</fieldset>
<?php //echo $this->Form->end(__d('permission_manager','Aceptar')); ?>
</div>
When I do click over delete button, it shows the confirm message, but when I push yes, the item is not deleted.
I realized it has relation with the action. Maybe with the request type.
The action code:
public function index() {
$this->paginate = array('order' => 'Permission.category asc, Permission.code asc');
$this->Permission->recursive = 2;
if($this->request->is('post')) {
if(empty($this->request->data['Permission']['permissionCategory'])) {
$conditions = null;
} else {
$cat = $this->Permission->findById($this->request->data['Permission']
['permissionCategory']);
$conditions = array('Permission.category ' => $cat['Permission']['category']);
}
$this->Paginator->settings = array(
'conditions' => $conditions );
}
$this->set('categorias', $this->Permission->find('list', array('fields' => 'category',
'group' => 'category')));
$this->set('permissions', $this->Paginator->paginate());
}
Edit:
My delete button:
(I have one like this for row in DB)
<?php echo $this->Form->postLink($this->Html->image('PermissionManager.cross.png',
array('title' =>
__d('permission_manager','Borrar'))),'delete/'.h($permission['Permission']['id']),
array( 'escape' => false), __d('permission_manager','Are you sure... ?'));
?>
My delete action:
public function delete($id = null) {
$this->Permission->id = $id;
if (!$this->Permission->exists()) {
//throw new NotFoundException(__d('permission_manager','Permiso inexistente'));
$this->Session->setFlash(__d('permission_manager','Permiso inexistente'), 'default', array('class'=>'error'));
return $this->redirect(array('action' => 'index'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Permission->delete()) {
$this->Session->setFlash(__d('permission_manager','El permiso ha sido borrado correctamente.'), 'default', array('class'=>'success'));
} else {
$this->Session->setFlash(__d('permission_manager','El permiso no ha podido borrarse. Por favor, inténtelo de nuevo.'), 'default', array('class'=>'error'));
}
return $this->redirect(array('action' => 'index'));
}

Resources