I have a foreach loop that saves a bunch of records into a table using cakePHP
foreach($interests as $id){
$this->data['UserInterest']['user_id'] = $user_id;
$this->data['UserInterest']['interest_id'] = $id;
$this->data['UserInterest']['other_interest'] = $other;
$UserInterest = new UserInterest;
if(!$UserInterest->save($this->data)) {
$this->Session->setFlash(__l('Failed to save Interests.') , 'default', null, 'error');
}
}
All saves fine except the other interest
UPDATE:
I've did the following
I can exho it out perfectly if I do this
$this->data['UserInterest']['other_interest'] = $other;
echo $this->data['UserInterest']['other_interest'];
$UserInterest = new UserInterest;
But somehow it saves as blank?
My database layout looks like this
CREATE TABLE IF NOT EXISTS `users_interests` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL,
`interest_id` bigint(20) NOT NULL,
`other_interest` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
)
and my model like this
<?php
class UserInterest extends AppModel
{
var $name = 'UserInterest';
var $useTable="users_interests";
//$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 $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => '',
) ,
'Interests' => array(
'className' => 'Interest',
'foreignKey' => 'interest_id',
'conditions' => '',
'fields' => '',
'order' => '',
)
);
function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->validate = array(
'user_id' => array(
'rule' => 'numeric',
'allowEmpty' => false,
'message' => __l('Required')
)
);
}
}
?>
Am I doing something wrong?
UPDATE:
I did the following
$this->data['UserInterest']['user_id'] = $user_id;
$this->data['UserInterest']['interest_id'] = $id;
$this->data['UserInterest']['other_interest'] = $other;
echo '<pre>';
var_dump($this->data['UserInterest']);
var_dump($other);
var_dump($this->data['UserInterest']['other_interest']);
$this->UserInterest = ClassRegistry::init('UserInterest');
And the var_dump results where the following, and still it did not save
array(3) {
["user_id"]=>
string(3) "659"
["interest_id"]=>
string(2) "10"
["other_interest"]=>
string(17) "Share Investments"
}
string(17) "Share Investments"
string(17) "Share Investments"
And old post but would like to add this here....
Always have
$this->Modelname->create();
in loops to save multiple records with loop. An most often this is the case which causes the error.
Related
I want to confirm user password then save the new password. I am able to validate username by this code but when i validate password, it doesn't work.
Is something i am missing or i am doing completely wrong. I am using cakephp2.5 Here is my code....
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`picture` varchar(100) NOT NULL,
`role_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
changepassword.ctp (view)
<div class="row">
<div class="col-lg-6">
<?php echo $this->Form->create('User', array('role'=>'form')); ?>
<fieldset>
<legend><h1>Change Password </h1></legend>
<?php
echo $this->Form->input('oldpassword',array('label'=>'Old Password','type'=>'password','class'=>'form-control'));
echo $this->Form->input('password',array('value'=>'password','label'=>'New Password','class'=>'form-control'));
echo $this->Form->input('password_confirmation',array('type'=>'password','class'=>'form-control','value'=>'password','label'=>'Confirm new Password'));
echo "<br>";
?>
</fieldset>
<?php
$options = array('label' => 'Submit','class' => 'btn btn-default');
echo $this->Form->end($options);
?>
</div>
UsersController.php (controller)
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function changepswrd() {
if ($this->request->is('post')) {
$this->User->create();
$data=$this->request->data['User'];
$data['id']=AuthComponent::user('id');
if ($this->User->save($data)) {
$this->Session->setFlash(__('Password changed sucessfully'));
return $this->redirect(array('controller' => 'users', 'action' => 'viewList'));
} else {
$this->Session->setFlash(__('Error!! please try again'));
}
}
}
}
?>
User.php (Model)
<?php
App::uses('AppModel', 'Model');
class User extends AppModel {
public $displayField = 'name';
public $validate = array(
'password' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
'matchPasswords'=>array(
'rule'=>array('matchPasswords'),
'message' => 'Both password must be equal',
),
),
'password_confirmation' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'oldpassword' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter old password',
),
'matching'=>array(
'rule'=>array('matching'),
'message' => 'wrong password',
),
),
);
public function matchPasswords($data){
if($data['password']==$this->data['User']['password_confirmation']){
return true;
}
$this->invalidate('password_confirmation','Both password must be equal');
return false;
}
public function matching($data){
$pswrd=AuthComponent::user('password');
if($pswrd==$this->data['User']['oldpassword']){
return true;
}
return false;
}
public function beforeSave($options = array()){
if(isset($this->data['User']['password'])){
$this->data['User']['password']=AuthComponent::password($this->data['User']['password']);
}
}
}
My Way of doing this :
function oldPasswordCheck($check){
$user = $this->find(
'count',
array('conditions' => array(
'User.id' => $this->session_id,
'User.password' => md5($this->data['User']['old_password'])
))
);
if(!$user){
return false;
}else {
return true;
}
}
Other help full link is
Click me
Hope this info helps you.
I've got the following models:
Run->hasMany ActualResult
ActualResult belongs to Status
When I view an ActualResult, Cake gets the corresponding Status without straight out of the box.
When I view a Run, I want to paginate the ActualResults. I have managed to get this to almost work with the following code in RunsController::view():
public function view($id = null) {
if (!$this->Run->exists($id)) {
throw new NotFoundException(__('Invalid run'));
}
$this->Run->contain ( 'Pack', 'User', 'Status');
$options = array('conditions' => array('Run.' . $this->Run->primaryKey => $id));
$run = $this->Run->find('first', $options);
$this->set('run', $run);
// Paginate the ActualResults
$this->paginate = array(
'contain' => array('Status'),
'order' => 'ActualResult.format',
'limit'=>5 ,
'conditions' => array('ActualResult.run_id' => $id)
);
$actualResults = $this->Paginator->paginate('ActualResult');
$this->set('actualResults',$actualResults);
}
The problem is that I get a warning:
Warning (512): Model "ActualResult" is not associated with model "Status" [CORE\Cake\Model\Behavior\ContainableBehavior.php, line 343
Something v. similar works for me in another model association, and as mentioned view() in ActualResultController works fine, so I am stumped.
Can anyone help?
Here are the model assocations:
In Run.php:
public $hasMany = array(
'ActualResult' => array(
'className' => 'actual_result',
'foreignKey' => 'run_id',
'dependent' => true,
'finderQuery' => 'SELECT ActualResult.*, Txn.name, Status.name FROM actual_results AS ActualResult, txns as Txn, codes AS Status WHERE ActualResult.run_id = {$__cakeID__$} and Txn.id = ActualResult.txn_id and (Status.code = ActualResult.status and Status.code_type = "ARS");'
)
);
In ActualResult.php
public $belongsTo = array(
'Run' => array(
'className' => 'Run',
'foreignKey' => 'run_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Status' => array(
'class`enter code here`Name' => 'Code',
'foreignKey' => 'status',
'conditions' => 'code_type = "ARS"',
'fields' => '',
'order' => ''
)
);
public $belongsTo = array(
'Hospital' => array(
'className' => 'Hospital',
'foreignKey' => 'hospital_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'Floor' => array(
'className' => 'Floor',
'foreignKey' => 'hospital_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
i have two tables hospitals and floors, i have retrieve data from hospital table and show in floor views in add floor.
You have already set up the relationship, so now you just need to create a controller action and a view.
Assuming your tables are in place, the easiest way to do this would simply be to run cake bake all on the Hospital model and Cake will generate the views for you. Cake is intelligent enough to generate a view that will show you a list of associated floors if that is what you want (it was unclear from your post).
You can retrieve the data from database like this...
mysql_select_db("users"); //your database name
$sql = mysql_query("SELECT * FROM langs"); //table name
$limit = 4;
$count = 3;
echo "<table border='1'>";
while($row = mysql_fetch_array($sql)){
$name=$row['name'];
$email=$row['email'];
$contact=$row['contact'];
if($count < $limit){
echo "<tr>";
}
............. //you can put in table and in any other field
?>
New to Cake, and trying to set up model associations. I'm creating an execution planner, to be used by multiple teams, aka 'groups' where the base unit of a plan is an 'event'. Each event is owned by one team, but it can have many supporting teams.
When I use $scaffold in the controllers, the model associations work as expected and when adding a new event I get a select box with all the groups to select who owns an event. However, when I bake the controller using console, the select box for group_id is blank. I've included the baked add() code from the controller, and from the baked add view. I also tried debug($this) in add.ctp, and found that the list of groups is indeed being passed to the view. I'm thus mostly confused about why it works with $scaffold, but not otherwise.
Any advice or pointers in the right direction would be greatly appreciated.
Tables:
CREATE TABLE IF NOT EXISTS `events` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`group_id` int(5) NOT NULL COMMENT 'Group that owns event',
`version` int(5) NOT NULL,
`type` varchar(5) NOT NULL,
`stime` time NOT NULL,
`etime` time NOT NULL,
`description` text NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `events_groups` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`event_id` int(5) NOT NULL,
`group_id` int(5) NOT NULL,
PRIMARY KEY (`id`)
) ;
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`code` varchar(4) NOT NULL,
`name` varchar(25) NOT NULL,
`liveversion` int(4) NOT NULL,
`lastupdated` date NOT NULL,
PRIMARY KEY (`id`)
);
Models:
Event:
public $belongsTo = array(
'Prigroup' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
)
);
public $hasAndBelongsToMany = array(
'Secgroup' => array(
'className' => 'Group',
'joinTable' => 'events_groups',
'foreignKey' => 'event_id',
'associationForeignKey' => 'group_id',
)
);
Group:
public $hasMany = array(
'Prievent' => array(
'className' => 'Event',
'foreignKey' => 'group_id',
)
);
public $hasAndBelongsToMany = array(
'Secevent' => array(
'className' => 'Event',
'joinTable' => 'events_groups',
'foreignKey' => 'group_id',
'associationForeignKey' => 'event_id',
)
);
EventsController Snippet:
public function add() {
if ($this->request->is('post')) {
$this->Event->create();
if ($this->Event->save($this->request->data)) {
$this->Session->setFlash(__('The event has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The event could not be saved. Please, try again.'));
}
}
$prigroups = $this->Event->Prigroup->find('list');
$secgroups = $this->Event->Secgroup->find('list');
$this->set(compact('prigroups', 'secgroups'));
}
Add view:
<?php echo $this->Form->create('Event'); ?>
<fieldset>
<legend><?php echo __('Add Event'); ?></legend>
<?php
echo $this->Form->input('group_id');
echo $this->Form->input('version');
echo $this->Form->input('type');
echo $this->Form->input('stime');
echo $this->Form->input('etime');
echo $this->Form->input('description');
echo $this->Form->input('comment');
echo $this->Form->input('Secgroup');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Add HTML Output
<div class="input select"><label for="EventGroupId">Group</label><select name="data[Event][group_id]" id="EventGroupId">
</select></div>
Can u try something for me please? Rename the $prigroups variable to "groups" and pass it to the view. See if this is working. Otherwise use this one with your old code:
echo $this->Form->input(
'group_id',
array(
'options' => $prigroups
)
);
I also recommend you to use camel case for all those PriGroups and SecGroups. Those are two words in english so camel case advisable.
Greetings
func0der
When a user enters data into my form it isn't saving to the database, this is the structure of my tables
Invoice - id, sender_id, receiver_id, template_id
Field - id, name, description, default_value, template_id
fields_invoices - id, invoice_id, field_id, entered_value
here is the invoice model
class Invoice extends AppModel{
var $name='Invoice';
var $hasMany = array(
'FieldsInvoice');
here is the field model
var $hasMany = array(
'FieldsInvoice'
);
and here is the fieldsInvoice model
<?php
class FieldsInvoice extends AppModel {
public $belongsTo = array(
'Field' => array(
'className' => 'Field',
'foreignKey' => 'field_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Invoice' => array(
'className' => 'Invoice',
'foreignKey' => 'invoice_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
here is the create function in the invoices controller
public function create($id)
{
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
if (!is_numeric($id)) throw new BadMethodCallException('I need an ID');
$this->Invoice->id = $id;
if (!$this->Invoice->exists()) throw new NotFoundException('Invalid ID');
$this->set('invoice_id',$id);
$names = $this->Invoice->find('list',array(
'fields'=>array('template_id'),
'conditions'=>array('id'=>$id)));
$fields = $this->Field->find('all', array(
'conditions'=>array(
'template_id'=>$names)));
$this->set(compact('fields'));
$this->set(compact('invoice_id'));
$this->set('name',$names);
$this->Invoice->create();
if(empty($this->data)){
$this->data= $this->Field->read($id);
}
else{
if($this->request->is('post'))
{
$this->Invoice->create();
if($this->FieldsInvoice->save($this->request->data, array('deep'=>true)));
{
$this->Session->setFlash('The field has been updated');
$this->redirect(array('controller'=>'invoices', 'action'=>'index'));
}
//else{
$this->Session->setFlash('Could not be saved');
//}
}
}
}
here is the view for the create function
<?php echo $this->Form->create('FieldsInvoice'); ?>
<?php foreach ($fields as $field): ?>
<?php echo $this->Form->hidden('Invoice.id'); ?>
<?php echo $this->Form->hidden($field['Field']['id']); ?>
<?php echo $this->Form->Input($field['Field']['name'], array('default' =>$field['Field']['default_value'])); ?>
<?php endforeach ;?>
<?php echo $this->Form->End('Submit');?>
when debugging the view this is the output received
array(
'Invoice' => array(
'id' => ''
),
'FieldsInvoice' => array(
(int) 5 => '',
'amount' => 'test',
(int) 6 => '',
'description' => 'test1',
(int) 7 => '',
'totalacctowing' => 'test2',
(int) 8 => '',
'pmtinfo' => 'test3'
)
)
Instead of:
$this->Invoice->save($this->request->data);
in your if condition use the following syntax;
$this->Invoice->save($this->request->data, array('deep' => true));
This link will guide you to save associated data.
Have you tried debugging? Try viewing your form data and see if all fields are ok. Use debug() or pr().