Multiple select in input Cakephp - php

WHen i have an input field with the multiple options concerning 'customer_id' the data request generated is
$request->data containing array(CompanysCustomer => array('id' => '1', 'uid' => 'fhs32hrqwr8wfsdiof', 'customer_id' => array('0' => '5', '1' => '8', '2' => '9')).
I dont undestand how to use or make use of this array. It Works well when i dont use multiple, because then i dont get array at 'customer_id'. I have an idea to manipulate the array and list them out ond do the save pr foreach, but that seems unefficient, it has to be some other way?
And im having trouble saving this to the db. I managed to make it when i have one single record to save. I cant make it save many records at once.
Version 2.4.1
public function add($id) {
if ($this->request->is('post')) {
$this->CompanysCustomer->create();
if ($this->CompanysCustomer->save($this->request->data)){
$this->Session->setFlash(__('The Companys Customer has been saved.'));
return $this->redirect(array('action' => 'index'));
}
else{
$this->Session->setFlash(__('The Companys Customer could not be saved. Please, try again.'));}
}
$customers = $this->CompanysCustomer->Customer->find('list');
$this->set(compact('customers'));
}
Model CompanysCustomer
<?php
App::uses('AppModel', 'Model');
/**
* CompanysCustomer Model
*/
class CompanysCustomer extends AppModel {
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
View: CompanyCustomer\add.ctp
<div class="companysCustomers form">
<?php echo $this->Form->create('CompanysCustomer'); ?>
<fieldset>
<legend><?php echo __('Add Companys Customer'); ?></legend>
<?php
$company_id = $id;
echo $this->Form->input('company_id', array(
'type' => 'hidden',
'value' => $id,
));
$uid = uniqid("", $more_entropy = true);
echo $this->Form->input('uid', array(
'type' => 'hidden',
'value' => $uid,
));
//echo $this->Form->input('company_id');
echo $this->Form->input('customer_id',array('type' => 'select', 'multiple' => 'checkbox','size' => '20'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

Reading the documentation helps
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::select
'multiple' => true
for example.
For saving use
saveMany()

Related

CakePHP - saving to more than two models using save associated

I am trying something more complicated. I have an Item which stores all general items, I have a Product which is an item and I have a Good which is a product and a item. So I have a form for entering value for the good and it shall save to all model related tables (items, products, goods). The reason for so many tables is because all tables shall have an id which is used later, example: product shall have its id which is used later for selling. Here is the controller:
public function add() {
$this->load();
if ($this->request->is('post')) {
$this->Item->create();
$this->request->data['Item']['code'] = $finalCode;
$this->request->data['Item']['is_deleted'] = false;
$item = $this->Item->save($this->request->data);
if(!empty($item)){
$this->request->data['Product']['item_id'] = $this->Item->id;
$this->request->data['Good']['item_id'] = $this->Item->id;
debug($this->request->data['Product']['item_id']);
debug($item);
$this->Item->Product->save($this->request->data);
$this->request->data['Good']['pid'] = $this->Product->id;
$this->Item->Good->save($this->request->data);
}
if($this->Good->validationErrors || $this->Item->validationErrors || $this->Product->validationErrors){
//ERRORS
}
else{
//FAILS
}
}
}
EDIT: I have changed the controller and now the Item is never saved but Product and Good is saved and they are all mapped well, ids are ok but Item is not even in the db, althrough Product and Good have item_id set to a value which should be next in the db.
class Good extends AppModel {
public $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_id',
),
'Product' => array(
'className' => 'Product',
'foreignKey' => 'pid',
)
);
}
class Product extends AppModel {
public $hasOne = array(
'Good' => array(
'className' => 'Good',
'foreignKey' => 'pid',
'dependent' => false,
),
);
}
class Item extends AppModel{
public $hasMany = array(
'Good' => array(
'className' => 'Good',
'foreignKey' => 'item_id',
'dependent' => false,
),
'Product' => array(
'className' => 'Product',
'foreignKey' => 'item_id',
'dependent' => false,
),
);
}
Even the debugged $item looks ok but is not saved:
array(
'Item' => array(
'name' => 'Microcontrollers',
'description' => 'Wire Jumpers Female-to-Female 30 cm',
'weight' => '22',
'measurement_unit_id' => '7',
'item_type_id' => '29',
'code' => 'GOD-34',
'is_deleted' => false,
'modified' => '2019-10-22 12:37:53',
'created' => '2019-10-22 12:37:53',
'id' => '120'
),
'Good' => array(
'status' => 'development',
'hts_number' => '8473 30 20',
'tax_group' => '20%',
'eccn' => 'EAR99',
'release_date' => array(
'month' => '10',
'day' => '22',
'year' => '2019',
'hour' => '10',
'min' => '10',
'meridian' => 'am'
),
'is_for_distributors' => '1'
),
'Product' => array(
'project' => 'neqwww'
)
)
I think the problem is with your code at the lines where you are saving the data.
$this->Item->create();
$this->Good->create();
$this->Product->create();
What is $this? If you create a item with "$this" and later try to create a "product", "$this" will not have the item_id.
Try using something like this to save the item created.
$item = $this->Item->create();
Then, with that $item created, you could create a $product with the $item->id
Update:
From cakephp documentation.
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
You must use $this->Item->save($data) to save the information into database.
https://book.cakephp.org/2.0/en/models/saving-your-data.html
Maybe the method create() is a bit unclear. It is used to restart the model state.
So, it would be
$item_saved = $this->Item->save($data['Item']);
$data['Product']['item_id'] = $this->Item->getLastInsertId();
$product_saved = $this->Product->save($data['Product']);
Edit 2:
Maybe it is because you didn't use create() before save the Item. Try this please:
$this->Item->create();
$item_saved = $this->Item->save($data['Item']);
$data['Product']['item_id'] = $this->Item->getLastInsertId();
$product_saved = $this->Product->save($data['Product']);

Creating a User who has-and-belongs-to-many existing Courses with a CakePHP form

I have an app with two associated models: User and Course, which are related by a HABTM association.
There is a registration form where a new user may enter a username and select the courses that they are a part of (from a list of existing courses in the database), only the form only saves the new users - it doesn't save anything to the join table.
The join table (courses_users) has columns course_id and user_id, and the two models look like this:
// User.php
class User extends AppModel {
public $name = 'User';
public $hasAndBelongsToMany = array(
'Courses' => array(
'className' => 'Course',
'joinTable' => 'courses_users',
'foreignKey' => 'user_id',
'associatedForeignKey' => 'course_id'
)
);
}
// Course.php
class Course extends AppModel {
public $name = 'Course';
public $hasAndBelongsToMany = array(
'Users' => array(
'className' => 'User',
'joinTable' => 'courses_users',
'foreignKey' => 'course_id',
'associatedForeignKey' => 'user_id'
)
);
}
In addition, this is the controller action:
// IdentificationController.php
public function register() {
if ($this->request->is('POST')) {
$data = $this->request->data;
$username = $data['User']['username'];
$saved = $this->User->save($data, array('deep' => true));
//debug($data);
if ($saved) {
$this->_set_new_user_session($username);
//$log = $this->User->getDataSource()->getLog(false, false);
//debug($log);
$this->redirect(array('controller' => 'users', 'action' => 'index'));
}
}
// Not redirecting
$courses = $this->Course->find('list', array('Course.name'));
//debug($courses);
$this->set(compact('courses'));
}
And this is the form, sans container divs:
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array(
'label' => false,
'div' => false
),
'url' => '/identification/register'
));
echo $this->Form->input('username', array(
'error' => false,
'autofocus' => true,
'required' => true,
'pattern' => '[a-zA-Z0-9]{3,16}'
));
if ($this->Form->isFieldError('username')) {
echo $this->Form->error('username', null, array('wrap' => 'small', 'class' => 'error'));
}
echo $this->Form->input('Course.Course', array(
'error' => false,
'required' => true
));
if ($this->Form->isFieldError('courses')) {
echo $this->Form->error('course', null, array('wrap' => 'small', 'class' => 'error'));
}
echo $this->Form->button('Register', array(
'div' => false,
'type' => 'submit'
));
echo $this->Form->end();
?>
When I call debug($data), the right data seems to be passed from the form to the controller:
array(
'User' => array(
'username' => 'test63apd'
),
'Course' => array(
'Course' => array(
(int) 0 => '1'
)
)
)
But nothing happens to the join table, and there is no mention of the join table in the DataSource log:
array(
'log' => array(
(int) 0 => array(
'query' => 'BEGIN',
'params' => array(),
'affected' => null,
'numRows' => null,
'took' => null
),
(int) 1 => array(
'query' => 'INSERT INTO `xray2`.`users` (`username`) VALUES ('test06apd')',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 1
),
(int) 2 => array(
'query' => 'COMMIT',
'params' => array(),
'affected' => (int) 1,
'numRows' => (int) 1,
'took' => (float) 1
)
),
'count' => (int) 3,
'time' => (float) 2
)
Am I missing something really obvious here, or is there some quirk of Cake that I have yet to discover?
You're only telling Cake to save the primary model data. You need to change this line:-
$saved = $this->User->save($data, array('deep' => true));
To:-
$saved = $this->User->saveAssociated($data, array('deep' => true));
saveAssociated() tells Cake to save the current model and its associated data. You also shouldn't need to pass array('deep' => true) as you are only saving data to a directly associated model. So it would be better (and safer) to use:-
$saved = $this->User->saveAssociated($data);
Update
There is an issue with the data being saved as you are not using the alias defined in your association for the data. So when Cake attempts to save the associated data it can't see any. According to your code your User model has and belongs to many Courses (plural) but your save data uses Course (singular). Therefore, your form should be:-
echo $this->Form->input('Courses.Courses', array(
'error' => false,
'required' => true
));
It should be noted that Cake naming conventions use singular forms for model names, so it would be better to use Course in the association rather than Courses. If you change this then your association can be simplified to the following:-
public $hasAndBelongsToMany = array(
'Course'
);
Cake will understand how to handle the join table and foreign keys as they conform to the naming convention. Then you wouldn't need to change your form.

filtering cakedc search results

i'm using cakeDC's search plugin in my app. can;t seem to figure out why the results are empty if i pass no value in the username field i'm searching but have the account type filter set to either admin or user For the record, having the filter set to all with the username field empty will output all the users in the system trying to replicate the behavior of searches having the account type filter set to all with an empty username search field for having the account type filter set to either 2 user types
here's the relevant code if needed:
controller
public $components = array('Paginator', 'Session','Search.Prg');
public $presetVars = array(
array('field' => 'username', 'type' => 'value'),
array('field' => 'account_type', 'type' => 'value'));
public function admin_index() {
$this->Prg->commonProcess();
$this->paginate = array(
'conditions' => $this->User->parseCriteria($this->passedArgs));
$this->set('users', $this->Paginator->paginate(),'session',$this->Session);
model
public $actsAs = array('Search.Searchable');
public $filterArgs = array( array('name' => 'username', 'type' => 'query', 'method' => 'filterName'),
array('name' => 'account_type', 'type' => 'value'),
);
public function filterName($data, $field = null) {
$nameField = '%' . $data['username'] . '%';
return array(
'OR' => array(
$this->alias . '.username LIKE' => $nameField,
));
}
view search form
<div><?php echo $this->Form->create('User', array(
'novalidate' =>true,'url' => array_merge(array('action' => 'index','admin'=> true), $this->params['pass'])
)); ?>
<?php
$account_types = array(
'' => __('All', true),
0 => __('admin', true),
1 => __('user', true),);
echo $this->Form->input('username', array('div' => false, 'empty' => true)); // empty creates blank option.
echo $this->Form->input('account_type', array('label' => 'account_type', 'options' => $account_types));
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
?></div>
Try to put 'empty' and allowEmpty in username and account_type like this:
public $filterArgs = array( array('name' => 'username', 'type' => 'query', 'method' => 'filterName', 'empty'=>true, 'allowEmpty'=>true),
array('name' => 'account_type', 'type' => 'value','empty'=>true, 'allowEmpty'=>true),
);
I had this kind of behavior as well from CakeDC/search and this two configs saved me, hope it will do for you as well.
It's a good idea to check the queries being executed as well using DebugKit.Toolbar.

Passing non-form data before save (CakePHP)

Course HasMany Lesson.
I am trying to save a lesson in a Course view, but want to automatically assign the current course_id without them having to select it.
How do I do that?
Here is my Courses view controller:
public function view($id = null) {
if (!$this->Course->exists($id)) {
throw new NotFoundException(__('Invalid course'));
}
$options = array('conditions' => array('Course.' . $this->Course->primaryKey => $id));
$this->set('course', $this->Course->find('first', $options));
//Adding Lesson from Course View
if ($this->request->is('post')) {
$this->Course->Lesson->create();
if ($this->Course->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The lesson has been saved.'), array ('class' => 'alert alert-success'));
return $this->redirect(array('controller'=> 'lessons', 'action' => 'view', $this->Course->Lesson->id));
} else {
$this->Session->setFlash(__('The lesson could not be saved. Please, try again.'), array ('class' => 'alert alert-danger'));
}
}
$courses = $this->Course->Lesson->Course->find('list');
$this->set(compact('courses'));
}
Currently, it's saving the lesson but not passing the course_id to the new lesson.
Lesson Model:
public $belongsTo = array(
'Course' => array(
'className' => 'Course',
'foreignKey' => 'course_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Course Model:
public $hasMany = array(
'Lesson' => array(
'className' => 'Lesson',
'foreignKey' => 'course_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
This is basically a duplicate of CakePHP: Securely setting a default value on a form.
Check my answer there or read the blog article I've wrote after that answer.

Simple Acl Controlled Application - Not allowing me to add new user

I'm new to CakePHP and I'm trying to implement the Simple Acl Controlled Application tutorial, and I've reached the part where you try to add new users and groups..
I successfully added the groups but when i try and add new users I receive the "The user could not be saved. Please, try again." Part of the function.
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
I noticed that the form tries to create a drop down box of all the different groups that I created but the drop box is empty and I have created three different groups (Admin, Responder and Volunteer).
Here is a copy of the add user view..
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('group_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users'), array('action' => 'index')); ?></li>
</ul>
</div>
Model as requested:
<?php
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $belongsTo = array('Group');
public $actsAs = array('Acl' => array('type' => 'requester'));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['group_id'])) {
$groupId = $this->data['User']['group_id'];
} else {
$groupId = $this->field('group_id');
}
if (!$groupId) {
return null;
} else {
return array('Group' => array('id' => $groupId));
}
}
public $primaryKey = 'id';
public $validate = array(
'id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'username' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'group_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
//old belongs to
// public $belongsTo = array(
// 'Group' => array(
// 'className' => 'Group',
// 'foreignKey' => 'group_id',
// 'conditions' => '',
// 'fields' => '',
// 'order' => ''
// )
// );
public $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
}
Debug message:
array(
'User' => array(
'password' => '*****',
'id' => '',
'username' => 'iwanjones'
)
)
Any help would be appreciated.
Thanks
In the form within your view, you create the id field as an input field (although through Cake's automagic it should convert it to a hidden input). When creating a new user, there is no id yet. It will be determined upon saving (creating) the record. In most applications this will be done by the MySQL backend's AUTO_INCREMENT functionality, which picks the first available "free" id.
In case of adding a new user, the id field is therefor not necessary. You only need it when you want to edit an existing user and make sure Cake edits the proper user, by setting it's id.
At this moment you set the id field in your view, but it gets no value, since it's a new user. In your Model you have added a validation rule that requires the id field to be numeric. But, the value is actually empty. You should do two things to get this working:
Drop the echo $this->Form->input('id'); line from the add view.
Remove the validation rule for the id field from your model (it's pretty uncommon to validate your primary key field, as Cake already handles this the proper way).
This should allow for the user to be saved successfully.

Categories