An internal error for view and edit view in cakePHP - cakephp

I follow a tutorial to add Full Calendar to my application . With the controller EventTypes, the index and the add view works , i've no problem .
For the view and edit view i get an error :
An Internal Error Has Occurred
Error: An Internal Error Has Occurred.
I'm using Cakephp 2 and PHP 5.4 .
This my controller :
<?php
class EventTypesController extends AppController {
var $name = 'EventTypes';
var $paginate = array(
'limit' => 15
);
public function admin_index() {
$this->EventType->recursive = 0;
$this->set('eventTypes', $this->paginate());
}
public function admin_view($id = null) {
if(!$id) {
$this->Session->setFlash(__('Invalid event type', true));
$this->redirect(array('action' => 'index'));
}
$this->set('eventType', $this->EventType->read(null, $id));
}
public function admin_add() {
if (!empty($this->data)) {
$this->EventType->create();
if ($this->EventType->save($this->data)) {
$this->Session->setFlash(__('The event type has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The event type could not be saved. Please, try again.', true));
}
}
}
public function admin_edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid event type', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->EventType->save($this->data)) {
$this->Session->setFlash(__('The event type has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The event type could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->EventType->read(null, $id);
}
}
public function admin_delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for event type', true));
$this->redirect(array('action'=>'index'));
}
if ($this->EventType->delete($id)) {
$this->Session->setFlash(__('Event type deleted', true));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Event type was not deleted', true));
$this->redirect(array('action' => 'index'));
}
}
?>
My model :
<?php
class EventType extends AppModel {
var $name = 'EventType';
var $displayField = 'name';
var $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
);
var $hasMany = array(
'Event' => array(
'className' => 'FullCalendar.Event',
'foreignKey' => 'event_type_id',
'dependent' => false,
)
);
}
?>

Related

About Model CakePHP

i have 2 table in database.there are categories and posts.
categories have id , name
posts have id , category
and i have 2 files.
PostsController.php
edit.ctp
i edit category by edit.ctp when i save its
image >> http://s704.photobucket.com/albums/ww41/018115496/edit.png
It is not save category's name but save a category's id into Posts.
image >> http://i704.photobucket.com/albums/ww41/018115496/index.png
This is my code
PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public $uses = array('Post','Category');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->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;
}
}
}
and edit.ctp
<?php
echo $this->Form->create('Post');
echo $this->Form->input('category', array('options' => $categories));
echo $this->Form->end('Save Post');
?>
i think i because find("list") but i don't know how to solve.
Thank you.
I have fixed your problem, You need to replace this
//PostsController.php
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name','Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->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;
}
}
When calling find('list'), the fields passed are used to determine what should be used as the array key and value, and optionally what to group the results by. By default, the primary key for the model is used for the key, and the display field (which can be configured using the model attribute displayField) is used for the value. Some further examples to clarify:
$justCategories = $this->Category->find('list', array(
'fields' => array('Category.name')
));
$Categories = $this->Category->find('list', array(
'fields' => array('Category.name', 'Category.name')
));
With the above code example, the resultant vars would look something like this:
$justCategories = Array
(
//[id] => 'name',
[1] => 'Books',
[2] => 'Baby',
[3] => 'Business & Industrial'
)
$Categories = Array
(
//[name] => 'name',
['Books'] => 'Books',
['Baby'] => 'Baby',
['Business & Industrial'] => 'Business & Industrial'
)
Read find(‘list’) in CakePHP

CakePHP HABTM add/edit problems

I have the following relationship:
Edition:
public $hasAndBelongsToMany = array(
'Band' => array(
'className' => 'Band',
'joinTable' => 'bands_editions',
'foreignKey' => 'edition_id',
'associationForeignKey' => 'band_id',
'unique' => true,
)
);
Band:
public $hasAndBelongsToMany = array(
'Edition' => array(
'className' => 'Edition',
'joinTable' => 'bands_editions',
'foreignKey' => 'band_id',
'associationForeignKey' => 'edition_id',
'unique' => true,
)
);
BandsController:
public function add()
{
if($this->request->is('post'))
{
$this->Band->create();
if($this->Band->save($this->request->data))
doSomething();
else
doSomethingElse();
}
}
public function edit($id = NULL)
{
$this->Band->id = $id;
if(!$this->Band->exists())
throw new NotFoundException(__('Not found'));
if($this->request->is('post') || $this->request->is('put'))
{
if($this->Band->save($this->request->data))
doSomething();
else
doSomethingElse();
} else {
$this->request->data = $this->Band->read(NULL, $id);
}
}
When I try to populate Bands with add(), everything goes well, but as soon as I call edit(), Cake stops with this error:
Fatal error: Call to a member function schema() on a non-object
Debugging, I found that the error is fired when the parser reaches the check about the type of the request.
Which is my error?
Try this , I didn't see if it works
public function edit($id = null){
if(!$id){
throw new NotFoundException(__("Invalid Post"));
}
$band = $this->Band->findById($id);
if (!$band) {
throw new NotFoundException(__('Invalid Post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Band->id = $id;
if ($this->Band->save($this->request->data)) {
doSomething();
}
else {
doDomething();
}
}
if (!$this->request->data) {
$this->request->data = $Band;
}
}

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

cakephp insert data in two table within one model and control

I have Two Table ones and twos I have A Foreign Key in 'two' table two_one_id
I Want to insert data in both table at a time , means insert data within one form, so how to manage controller and model, can I make one model and one controller for this ? then How To Create The Model And Controller For This
Which Type Of Relation Should Have I Prefer For Both Table?
I Have Made Two Different Tabele One.php and Two.php
and I Have Made Two Controller OnesController.php and twosController.php
Can I Use Scaffold In Both Of Them And Using Scaffold Can I Insert Data In Two Table Within A Controller And Model, If It Is Possible Using Scaffolding , Then How Done It, Or In This Code I Have Tried Without Scaffolding , Manual Manage View */
/*One.php File
public $displayField = 'name';
public $hasOne = array(
'Two' => array(
'className' => 'Two',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//Two.php
<?php
App::uses('AppModel', 'Model');
class Two extends AppModel {
public $displayField = 'sname';
public $belongsTo = array(
'One' => array(
'className' => 'One',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//OnesController.php
<?php
App::uses('AppController', 'Controller');
/**
* Ones Controller
*
* #property One $One
* #property PaginatorComponent $Paginator
*/
class OnesController extends AppController {
/**
* Helpers
*
* #var array
*/
public $helpers = array('Html','Form');
public $uses = array('One','Two');
public $components = array('Paginator');
public function index() {
$this->One->recursive = 0;
$this->set('ones', $this->Paginator->paginate());
}
public function view($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->set('one', $this->One->find('first', $options));
}
public function add() {
if ($this->request->is('post')) {
$this->One->create();
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->request->data = $this->One->find('first', $options);
}
}
public function delete($id = null) {
$this->One->id = $id;
if (!$this->One->exists()) {
throw new NotFoundException(__('Invalid one'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->One->delete()) {
$this->Session->setFlash(__('The one has been deleted.'));
} else {
$this->Session->setFlash(__('The one could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
You may want to look into: $this->One->saveAll($this->request->data)
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
You Just Set Following Code to Your Controller
OnesControllers.php
public function add() {
if ($this->request->is('post')) {
$this->One->create();
}
if (!empty($this->request->data)) {
// We can save the User data:
// it should be in $this->request->data['User']
$one = $this->One->save($this->request->data);
// If the user was saved, Now we add this information to the data
// and save the Profile.
if (!empty($one)) {
// The ID of the newly created user has been set
// as $this->User->id.
$this->request->data['Two']['two_one_id'] = $this->One->id;
// Because our User hasOne Profile, we can access
// the Profile model through the User model:
$this->One->Two->save($this->request->data);
}
}
And Set This in Your View
view/one/add.ctp
<div class="ones form">
<?php echo $this->Form->create('One'); ?>
<fieldset>
<legend><?php echo __('Add One'); ?></legend>
<?php
echo $this->Form->input('name',array('rows' => '10'));
echo $this->Form->create('Two');
echo $this->Form->input('sname');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

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