CakePHP HABTM add/edit problems - cakephp

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;
}
}

Related

An internal error for view and edit view in 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,
)
);
}
?>

CakePHP $this->Auth->login() return false

I created a User with the hash provided by the Cake .. But when I go to log in, says 'Invalid username or password'. But it's all right.
The $this->Auth->login(); always returns false...
Crontroller
class MastersController extends AppController{
public function login(){
if ($this->request->is('post')) {
debug($this->Auth->login());
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}}
AppController
class AppController extends Controller {
public $components = array('Session', 'Cookie', 'Auth');
function beforeFilter() {
$this->loadModel('Master');
$this->Auth->userModel = 'Master';
$this->Auth->allow('*');
// Action da tela de login
$this->Auth->loginAction = array(
'masters' => false,
'controller' => 'masters',
'action' => 'login'
);
// Action da tela após o login (com sucesso)
$this->Auth->loginRedirect = array(
'masters' => true,
'controller' => 'masters',
'action' => 'index'
);
// Action para redirecionamento após o logout
$this->Auth->logoutRedirect = array(
'masters' => false,
'controller' => 'pages',
'action' => 'login'
);
$this->Auth->authorize = array('controller');
if (!isset($this->params['masters']) || !$this->params['masters'])
$this->Auth->allow('*','login');
$this->Auth->loginError = __('Usuário e/ou senha incorreto(s)', true);
$this->Auth->authError = __('Você precisa fazer login para acessar esta página', true);
}
public function isAuthorized($masters){
return TRUE;
}}
VIEW login.ctp
echo 'Formulário de login';
echo $this->Session->flash('auth');
echo $this->Session->flash();
echo $this->Form->create('Master', array('controller'=>'masters','action'=>'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Entrar');
Model
class Master extends AppModel{
public $name = 'Master';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Usuario requerido.'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Senha requerida.'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
I don't know why it is giving this error .. This all seems ok!
I changed one letter of Security.salt, as he asked ..
Help me :)
I need it for work
debug($this->Auth->login());
if ($this->Auth->login()) {}
is a bad idea.
the first will log you in,
the second call will then - of course - return false (since you are already logged in).
If you really need to test this way, halt the code:
debug($this->Auth->login()); die();
I had the same problem and what fixed it for me was changing $this->alias to User, so beforeSave() now looks like
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}

linking tables cakephp

Hi all I finally got my validation for my invoices model working 100% but now its thrown off my validation in relationship model(which was working) because now it references everything in the wrong table.
The relationship model is supposed to make sure that a user exists in the users table before you can send them a request.
The invoice model is supposed to make sure that a user has a column with another user in the the relationship table.
how can I change it to make it work properly? At the moment the code completely throws off my entire relationship side of the website.
-relationship model
class Relationship extends AppModel
{
var $name = 'Relationship';
public $useTable = 'relationships_users';
public $primaryKey = 'id';
public $hasMany = array(
'Invoice' =>
array(
'className' => 'Invoice',
'joinTable' => 'invoice',
'foreignKey' => 'invoice_id'));
public $belongsTo = array(
'User' =>array(
'className' => 'User',
'foreignKey' =>'partyone','partytwo',
'associationForeignKey' => 'username',
));
var $validate = array(
'date' => array(
'rule' => array(
'datevalidation',
'systemDate'
),
'message' => 'Current Date and System Date is mismatched'
),
'partytwo' => array(
'userExists' => array(
'rule' => array(
'userExists',
),
'message' => 'That username doesnt exist.'
),
),
);
function datevalidation($field = array(), $compare_field = null)
{
if ($field['date'] > $compare_field)
return TRUE;
else
return FALSE;
}
function userExists($check)
{
$userExists = $this->User->find('count', array('conditions' => array('User.username'=>$check)));
if ($userExists == 1) {
return TRUE;
}
else
return FALSE;
}
-user model
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel{
public $name = 'User';
public $hasMany = array(
'Relationship' =>
array(
'className' => 'Relationship',
'joinTable' => 'relationships_users',
'foreignKey' => 'id',
'unique' => false,));
public $useTable = 'users';
public $primaryKey = 'id';
public $validate = array(
'username'=>array(
'The username must be between 5 and 15 characters.'=>array(
'rule'=>array('between', 5, 15),
'message'=>'The username must be between 5 and 15 characters.'
),
'That username has already been taken'=>array(
'rule'=>'isUnique',
'message'=>'That username has already been taken.'
)),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'password'=>array(
'Not Empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password'
)
),
'Match passwords'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match'
)
,
'password_confirmation'=>array(
'Not Empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password'
)));
public function matchPasswords($data){
if ($data['password']==$this->data['User']['password_confirmation']){
return true;
}
$this->invalidate('password_confirmation','Your passwords do not match');
return false;
}
public function beforeSave(){
if(isset($this->data['User']['password'])){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
invoice model-
class Invoice extends AppModel{
var $name='Invoice';
//public $useTable = 'invoices';
//public $primaryKey = 'id';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists',
),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
var $validateTwo = array(
'datecreated'=>array(
'dateHasntExpired' => array(
'rule'=>array(
'dateHasntExpired',
),
'message'=> 'sorry but your relationship has expired.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone <>' => current($check),
'Relationship.partytwo' => current($check),
// 'Relationship.active'==true,
// get the value from the passed var
)
));
if ($relationshipExists == true) {
return TRUE;
}
else
return FALSE;
}
public function dateHasntExpired($check){
$dateHasntExpired=$this->Relationship->find('count', array(
'conditions'=>array(
'DATE(Relationship.expirydate) > DATE(Invoice.datecreated)',
)));
if ($dateHasntExpired == true) {
return TRUE;
}
else
return FALSE;
}
}
here is the error that comes up when trying to view current relationship requests
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Invoice.invoice_id' in 'field list'
SQL Query: SELECT `Invoice`.`id`, `Invoice`.`to`, `Invoice`.`biller`, `Invoice`.`subject`, `Invoice`.`description`, `Invoice`.`amount`, `Invoice`.`datecreated`, `Invoice`.`duedate`, `Invoice`.`invoice_id` FROM `pra_cake`.`invoices` AS `Invoice` WHERE `Invoice`.`invoice_id` IN (97, 98, 99, 101, 104, 105)
Notice: If you want to customize this error message, create
app\View\Errors\pdo_error.ctp
and here is the error i get when trying to view the relationship requests ive sent
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Invoice.invoice_id' in 'field list'
SQL Query: SELECT `Invoice`.`id`, `Invoice`.`to`, `Invoice`.`biller`, `Invoice`.`subject`, `Invoice`.`description`, `Invoice`.`amount`, `Invoice`.`datecreated`, `Invoice`.`duedate`, `Invoice`.`invoice_id` FROM `pra_cake`.`invoices` AS `Invoice` WHERE `Invoice`.`invoice_id` IN (97, 98, 99, 101, 104, 105)
Notice: If you want to customize this error message, create app\View\Errors\pdo_error.ctp
needed to use the unbind method in my controllers, here is an example of the unbind method I used throughout my relationship controller.
public function approve($id=null){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
$this->Relationship->unbindModel(array('hasMany'=>array('Invoice')));
if ($this->request->is('get')) {
$this->request->data = $this->Relationship->read(NULL, $id);
} else {
//sets active to 1
$this->Relationship->read(null, $id);
$this->Relationship->set(array('active' => true,));
if ($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
and because this threw errors in my invoice controller I used unbind there as well and here is an example of the unbind I used in invoicescontroller
public function viewInvoice($id = NULL){
$this->set('title_for_layout', 'View invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->Invoice->unbindModel(array('belongsTo'=>array('Relationship')));
$this->set('invoice', $this->Invoice->read(NULL, $id));
}

CAKEPHP: Inner joins and Controller Issues

http://webdesign4.georgianc.on.ca/~100141468/comp2084/todo/clients
http://bin.cakephp.org/view/1402280124
The first link- where add is- it is working fine, but the inner join is not working. The SQL is correct, just not the code in the controller. Another issue I am having is the undefined action views. I am certain it has to do with what's inside the controller.
<?php
class ClientsController extends AppController
{
var $name = 'Clients';
function index()
{
$this->set('Clients', $this->Client->find('all'));
}
function add()
{
if ($this->request->is('post')) {
if ($this->Client->save($this->request->data)) {
$this->Session->SetFlash('Client has been saved');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash('Nope');
}
}
}
public function view($id = null)
{
$this->Client->id = $id;
$this->set('Client', $this->Client->read(null, $id));
}
public function edit($id = null)
{
$this->Client->id = $id;
if ($this->request->is('get')) {
$this->request->data = $this->Client->read();
} else {
if ($this->Client->save($this->request->data)) {
$this->Session->setFlash('Client has been updated.');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash('Unable to update Client.');
}
}
$this->loadModel('Employee');
$this->set('Employees', $this->Employee->find('list', array(
'order' => array(
'Employee.name'
)
)));
$this->set(compact('Employees'));
}
public function delete($id = null)
{
if ($this->request->is('/Clients/delete/{id}')) {
throw new MethodNotAllowedException();
}
if ($this->Client->delete($id)) {
$this->Session->setFlash('The Client with id: ' . $id . ' has been deleted.');
$this->redirect(array(
'action' => 'index'
));
}
}
}
?>

form action linking to wrong controller

I have a a controller referral_medium_controller.php with the following content
<?php
class ReferralMediumsController extends AppController
{
var $name = 'ReferralMediums';
function admin_index()
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Referral Mediums');
$this->ReferralMediums->recursive = 0;
$this->set('ReferralMediums', $this->paginate());
}
function admin_view($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Referral Mediums?');
if (is_null($id)) {
$this->cakeError('error404');
}
$referralMedium = $this->ReferralMediums->find('first', array(
'conditions' => array(
'ReferralMedium.id = ' => $id
) ,
'fields' => array(
'ReferralMedium.id',
'ReferralMedium.created',
'ReferralMedium.modified',
'ReferralMedium.referral_medium',
'ReferralMedium.is_active',
) ,
'recursive' => -1,
));
if (empty($referralMedium)) {
$this->cakeError('error404');
}
$this->pageTitle.= ' - ' . $referralMedium['ReferralMedium']['id'];
$this->set('ReferralMediums', $referralMedium);
}
function admin_add()
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Add Referral Medium');
if (!empty($this->data)) {
$this->ReferralMedium->create();
if ($this->ReferralMedium->save($this->data)) {
$this->Session->setFlash(__l('Referral Medium has been added') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__l('Referral Medium could not be added. Please, try again.') , 'default', null, 'error');
}
}
}
function admin_edit($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
$this->pageTitle = __l('Edit Referral Medium');
if (is_null($id)) {
$this->cakeError('error404');
}
if (!empty($this->data)) {
if ($this->ReferralMedium->save($this->data)) {
$this->Session->setFlash(__l('Referral Medium has been updated') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__l('Referral Medium could not be updated. Please, try again.') , 'default', null, 'error');
}
} else {
$this->data = $this->ReferralMedium->read(null, $id);
if (empty($this->data)) {
$this->cakeError('error404');
}
}
$this->pageTitle.= ' - ' . $this->data['ReferralMedium']['id'];
}
function admin_delete($id = null)
{
//Checking that only super administrators can actually add new interest options
if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
$this->cakeError('error404');
}
if (is_null($id)) {
$this->cakeError('error404');
}
if ($this->ReferralMedium->del($id)) {
$this->Session->setFlash(__l('Referral Medium deleted') , 'default', null, 'success');
$this->redirect(array(
'action' => 'index'
));
} else {
$this->cakeError('error404');
}
}
}
?>
a model referral_model.php with the following content
<?php
class ReferralMedium extends AppModel
{
var $name = 'ReferralMedium';
var $useTable="referral_mediums";
//$validate set in __construct for multi-language support
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $hasOne = array(
'UserProfile' => array(
'className' => 'UserProfile',
'foreignKey' => 'referral_medium_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'UserProfile' => array(
'className' => 'UserProfile',
'foreignKey' => 'referral_medium_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->validate = array(
'referral_medium' => array(
'rule' => 'notempty',
'allowEmpty' => false,
'message' => __l('Required')
) ,
);
}
}
?>
a add view referral_mediums/admin_add.ctp with the following code
<?php /* SVN: $Id: $ */ ?>
<div class="referralMedium form">
<?php echo $form->create('ReferralMedium', array('class' => 'normal'));?>
<fieldset>
<h2><?php echo __l('Add Referral Medium');?></h2>
<?php
echo $form->input('referral_medium');
echo $form->input('is_active');
?>
</fieldset>
<div class="submit-block clearfix">
<?php echo $form->submit(__l('Add'));?>
</div>
<?php echo $form->end();?>
</div>
Now all works fine except if I click on the add button in the add form I get redirected to admin/referral_media/add instead of admin/referral_medium/add and I can't find the problem. I would be greatful I someone could help me with this.
the plural of medium is media, not mediums. The controller name is plural, so it's referral_media. So you'll need to change your controller name (and the file name).
Or change Config/bootstrap.php so it won't make controller names plural anymore.

Resources