I created a form which saves the Date and the Menu a Customer ordered. Thanks to this question: cakephp 3.x saving multiple entities - newEntities I made my own form work.
The Problem that I have now is that i need to pick for every Date and Menu a Customer. Is there way to choose the Customer only one time for all new Dates and Menus?
First my Code which is very similar to the answer i linked:
OrdersController.php
{
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$orders = $this->Orders->newEntities($this->request->getData());
debug($order);
foreach ($orders as $order)
{
$this->Orders->save($order);
}
$this->Flash->success(__('The order has been saved.'));
return $this->redirect(['action' => 'index']);
$this->Flash->error(__('The order could not be saved. Please, try again.'));
}
$customers = $this->Orders->Customers->find('list', ['limit' => 200]);
$menuItems = $this->Orders->MenuItems->find('list', ['limit' => 200]);
$this->set(compact('order', 'customers', 'menuItems'));
}
add.ctp
<fieldset>
<legend><?= __('Neue Bestellung') ?></legend>
<?php
echo $this->Form->control('0.customer_id', array('label' => __('Kunde',true)));
echo $this->Form->control('0.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('0.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('1.customer_id', array('label' => __('Kunde',true)));
echo $this->Form->control('1.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('1.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
?>
</fieldset>
I know that i need to change this
echo $this->Form->control('0.customer_id', array('label' => __('Kunde',true)));
echo $this->Form->control('1.customer_id', array('label' => __('Kunde',true)));
but i dont know into what. I first thought if i use customer_id without a number
echo $this->Form->control('customer_id', array('label' => __('Kunde',true)));
or like this
echo $this->Form->control('0.1.customer_id', array('label' => __('Kunde',true)));
it would work but i doesn't. Propably because it doesnt know where to save it cause its missing the index number in the first example and in he second example I created a new Index? I am a beginner in coding so maybe im completly wrong with that but I think thats why it doesnt work.
If I do it like I explained above, it doesnt save a value into customer. How can i choose a Customer and save multiple Dates and Menus for him?
EDIT
Because I didn't explain it precisely I try again.
My Goal is to create a Form which should save multiple Dates and Menus for a Customer. Inside the Form I want to choose 1 Customer, which I get with the customer_id. After that I want to choose multiple Dates (date) and Menus (menu_item_id) for that chosen Customer. If I press submit I want to get multiple Orders for the Customer I choose.
Example:
I choose a customer (John Sample), and now I pick for him the Date (01.01.2019) and the Menu 7. After that I pick the Date (02.02.2019) and the Menu 6. After that I pick the Date (03.02.2019) and the Menu 2.
If I save now, I want to see that the Customer I choose (John Sample) has ordered on the Dates 01.01.2019, 02.01.2019, 03.01.2019 and which menus he ordered for the Date.
Example:
Customer: John Sample | Date: 01.01.2019 | Menu: 7
Customer: John Sample | Date: 02.01.2019 | Menu: 6
Customer: John Sample | Date: 03.01.2019 | Menu: 2
The Problem that I have now is I don't know how to do that. I know that I could just pick a new Customer for every Date and Menu, like this:
<fieldset>
<legend><?= __('Neue Bestellung') ?></legend>
<?php
echo $this->Form->control('0.customer_id', array('label' => __('Kunde',true)));
echo $this->Form->control('0.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('0.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('1.customer_id', array('label' => __('Kunde',true)));
echo $this->Form->control('1.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('1.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
?>
</fieldset>
but that is not what I want to do. Because at the End I want to save up to 7 Orders and i dont want to choose the customer every time.
This brings me back to my Question how can I save one Customer, I pick in the form, and save multiple Dates and Menus for him?
I hope this made my Question a little clearer.
EDIT 2
My Order Table:
OrdersTable.php
class OrdersTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('orders');
$this->setDisplayField('id');
$this->setPrimaryKey(['id']);
$this->belongsTo('Customers', [
'foreignKey' => 'customer_id',
]);
$this->belongsTo('MenuItems', [
'foreignKey' => 'menu_item_id',
]);
$this->belongsTo('Bills', [
'foreignKey' => 'bill_id',
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmptyString('id', 'create');
$validator
->date('date')
->allowEmptyDate('date');
$validator
->boolean('bestellt')
->allowEmptyString('bestellt', false);
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['customer_id'], 'Customers'));
$rules->add($rules->existsIn(['menu_item_id'], 'MenuItems'));
$rules->add($rules->existsIn(['bill_id'], 'Bills'));
return $rules;
}
}
If you want to save the current customer_id with each Order, then I'd just set it in the controller. There is no real need to assign this task to the client-side, or even trust the client-side with this data.
Note: I am assuming that Order.customer_id is a foreign key referening User.id, if that is not the case, you need to adjust accordingly.
In your controller action:
// ...
debug($order);
// TODO: can't remember if this is the correct way - look this up.
$current_uid = $this->getRequest()->getSession()->read('User.id')
foreach ($orders as $order)
{
// actually set the `customer_id` to the required value before persisting
$order->customer_id = $current_uid;
$this->Orders->save($order);
}
In case you want to show it to your customers in a view, add $current_uid to the variables set for the view at the end of your controller action, and then:
<fieldset>
<legend><?= __('Neue Bestellung') ?></legend>
<?php
foreach($orders as $key => $value) {
echo $this->Form->control('${key}.customer_id', array('label' => __('Kunde',true), 'readonly' => true, 'value' => $current_uid ));
// ...echo other fields
}
?>
</fieldset>
I finally found my Solution!
add.ctp
<?php
/* Kunden auswählen */
echo $this->Form->control('customer_id', array('label' => __('Kunde',true)));
/* Erster Tag */
echo $this->Form->control('0.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('0.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('0.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('0.bestellt');
/* Zweiter Tag */
echo $this->Form->control('1.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('1.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('1.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('1.bestellt');
/* Dritter Tag */
echo $this->Form->control('2.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('2.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('2.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('2.bestellt');
/* Vierter Tag */
echo $this->Form->control('3.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('3.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('3.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('3.bestellt');
/* Fünfter Tag */
echo $this->Form->control('4.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('4.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('4.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('4.bestellt');
/* Sechster Tag */
echo $this->Form->control('5.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('5.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('5.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('5.bestellt');
/* Letzter Tag */
echo $this->Form->control('6.date', array('label' => __('Datum',true), ['empty' => true]));
echo $this->Form->control('6.menu_item_id', array('label' => __('Menü',true), 'empty' => true));
echo $this->Form->control('6.customer_id',['type' => 'hidden', 'empty' => true]);
echo $this->Form->control('6.bestellt');
?>
My Javascript
$('#customer-id').change(function() {
$('#0-customer-id').val($(this).val());
$('#1-customer-id').val($(this).val());
$('#2-customer-id').val($(this).val());
$('#3-customer-id').val($(this).val());
$('#4-customer-id').val($(this).val());
$('#5-customer-id').val($(this).val());
$('#6-customer-id').val($(this).val());
});
Im now copying my customer_id into the hidden fields. That way im finally only need to choose my Customer one time and can create an Order for a Week.
Maybe this isnt the cleanest way to do it but it works!
Related
i don't know how to save different values in my db at the same time. i have this in my view
<?php echo $this->Form->create('SoyaPrecioInternacional');?>
<fieldset>
<?php
echo $this->Form->input('pais', array(
'options' => array(
'CHICAGO' => 'Chicago',
'ROSARIO' => 'Rosario'
),'label'=>'Ciudad'
));
echo $this->Form->input('precio', array('label' => 'Ingrese en Dolares $us','style'=>'width:500px; height:30px;'));
echo $this->Form->input('pais', array(
'options' => array(
'CHICAGO' => 'Chicago',
'ROSARIO' => 'Rosario'
),'label'=>'Ciudad'
));
echo $this->Form->input('precio', array('label' => 'Ingrese en Dolares $us','style'=>'width:500px; height:30px;'));
echo $this->Form->submit('Agregar Cambio', array('class' => 'form-submit', 'title' => 'Presione aqui para agregar datos'));
?>
</fieldset>
and this in my controller
public function add()
{
$this->loadModel('SoyaPrecioInternacional');
if ($this->request->is('post')) {
$this->request->data['SoyaPrecioInternacional']['user_id'] = $this->Auth->user('id');
if ($this->SoyaPrecioInternacional->save($this->request->data)) {
$this->Session->setFlash(__('La Información fue Guardada.'));
return $this->redirect(array('action' => 'index'));
}
}
}
but when i put a price for option 1 and another for option 2 in my controller only get the last choice form example
if i put a price for chicago the first option and then rosario the secon option in my db only appears the rosario value
maybe
<?php echo $this->Form->create('SoyaPrecioInternacional');?>
<fieldset>
<?php
echo $this->Form->input('SoyaPrecioInternacional.1.precio', array('label' => 'Ingrese en Dolares $us','style'=>'width:500px; height:30px;'));
echo $this->Form->input('SoyaPrecioInternacional.1.pais', array('type' => 'hidden', 'value'=>'ROSARIO'));
?>
<?php
echo $this->Form->input('SoyaPrecioInternacional.2.precio', array('label' => 'Ingrese en Dolares $us','style'=>'width:500px; height:30px;'));
echo $this->Form->input('SoyaPrecioInternacional.2.pais', array('type' => 'hidden', 'value'=>'CHICAGO'));
echo $this->Form->submit('Agregar Cambio', array('class' => 'form-submit', 'title' => 'Presione aqui para agregar datos'));
?>
and
public function add()
{
$this->loadModel('SoyaPrecioInternacional');
$this->request->data['SoyaPrecioInternacional']['user_id'] = $this->Auth->user('id');
if ($this->request->is('post')) {
$count=0;
foreach($this->request->data['SoyaPrecioInternacional'] as $precios){
$count++;
$this->SoyaPrecioInternacional->create();
$this->request->data['SoyaPrecioInternacional']['precio']=$precios['precio'];
$this->request->data['SoyaPrecioInternacional']['pais']=$precios['pais'];
$this->SoyaPrecioInternacional->save($this->request->data);
}
return $this->redirect(array('action' => 'index'));
}
}
I'm using the cakephp uploader plugin by Miles Johnson. I like the plugin and I've got it working to be able to upload photos for a photo model.
The problem I'm running into is that when I try to edit an existing record, instead of replacing the photo associated with the record I'm editing a new record is created. The new record has all the same information with the exception of the new photo that's been uploaded.
Here's how the photo model looks:
'Uploader.Attachment' => array(
'imgPath' => array(
// 'name' => '', // Name of the function to use to format filenames
'baseDir' => '', // See UploaderComponent::$baseDir
'uploadDir' => 'files/uploads/', // See UploaderComponent::$uploadDir
'dbColumn' => 'imgPath', // The database column name to save the path to
'maxNameLength' => 60, // Max file name length
'overwrite' => false, // Overwrite file with same name if it exists
'stopSave' => true, // Stop the model save() if upload fails
'allowEmpty' => true, // Allow an empty file upload to continue
'transforms' => array( // What transformations to do on images: scale, resize, etc
array(
'method' => 'resize',
'width' => 50,
'height' => 50,
'append' => '_thumb',
'dbColumn' => 'imgPathThumb',
)
)
)
)
This is the photo admin edit view form:
<?php echo $this->Html->script('ckeditor/ckeditor');?>
<?php echo $this->Form->create('Photo', array('type' => 'file'));?>
<fieldset>
<legend><?php echo __('Admin Edit Photo'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('caption', array('class'=>'ckeditor'));
echo $this->Form->input('imgPath', array('type' => 'file'));
echo $this->Form->input('alt_tag');
echo $this->Form->input('type', array( 'label' => 'Choose a type of photo', 'options' => array(
'gallery'=>'gallery',
'news'=>'news',
'post'=>'post',
)));
echo $this->Form->input('active', array( 'label' => 'Make active', 'options' => array('yes'=>'yes','no'=>'no' )));
echo $this->Form->input('gallery_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is the controller admin edit code:
public function admin_edit($id = null) {
$this->layout = 'admin';
if (!$this->Photo->exists($id)) {
throw new NotFoundException(__('Invalid photo'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Photo->save($this->request->data)) {
$this->Session->setFlash(__('The photo has been saved.'), 'success');
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The photo could not be saved. Please, try again.'), 'error');
}
} else {
$options = array('conditions' => array('Photo.' . $this->Photo->primaryKey => $id));
$this->request->data = $this->Photo->find('first', $options);
}
$galleries = $this->Photo->Gallery->find('list');
$this->set(compact('galleries'));
}
Have I overlooked something obvious?
Cheers, Paul
When You editing record, You must set ID of this record.
Add to form $this->Form->input('id') or set ID in controller before save() action
In controller I have a function of updating the address
if(!empty($this->data)) {
$this->data['Address']['user_id'] = $this->Auth->user('id');
$this->data['Address']['user_address_type_id'] = $address_type_id;
if($this->Address->save($this->data)) {
if(!empty($this->data['Address']['update_all'])) {
$this->Address->updateAll($this->data);
}
$this->Session->setFlash(__('The address was successfully updated.', true), 'default', array('class' => 'success'));
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash(__('There was a problem updating the address, please correct the errors below.', true));
}
} else {
$this->data = $this->Address->find('first', array('conditions' => array('user_address_type_id' => $address_type_id, 'user_id' => $this->Auth->user('id'))));
}
$this->set('countries', $this->Address->Country->find('list',array('order' => 'Country.name ASC')));
And In edit.ctp File
<fieldset>
<legend><?php __('Update Address');?></legend>
<?php
echo $form->input('id');
echo $form->input('name', array('label' => __('Name *', true)));
echo $form->input('address_1', array('label' => __('Address (line 1) *', true)));
echo $form->input('address_2', array('label' => __('Address (line 2)', true)));
echo $form->input('suburb', array('label' => __('Suburb / Town', true)));
echo $form->input('city', array('label' => __('City / State / County *', true)));
echo $form->input('postcode', array('label' => __('Post Code / Zip Code *', true)));
echo $form->input('country_id', array('label' => __('Country *', true), 'empty' => 'Select'));
echo $form->input('state_id', array('type' => 'select','label' => __('States *', true), 'empty' => 'Select'));
echo $form->input('phone', array('label' => __('Phone', true)));
/*echo $form->input('update_all', array('type' => 'checkbox', 'label' => __('Make all your addresses this address.', true)));*/
?>
</fieldset>
I want to add state list according to the selected country. For e.g if USA is selected then USA States appears in states drop down etc.
I have a cakephp 1.3 app which get's a person's consent to participate in a study. I'm trying to link inclusion criteria and exclusion criteria for the study on the Add study page. The HABTM relationship is setup and working(If there's only one way to select them) What I'm trying to do now is display the current Inclusion Criteria as a list of checkboxes the person adding the study can select, but I also want a field where new criteria can be entered as a comma seperated list. Right now it will save the checkboxes, but I want it to also add the text entered in the field as well. Screen showing the Add study as it sits now is below. I don't really know how I would go about doing that. Is there a way to do this or will I have to take the data entered, sort through it and then add it to $this->data[inclusion field data]? An example would be nice. :) I've added the code I have so far below the image.
Controller:
/**
* Add a study.
*/
function add() {
if (!empty($this->data)) {
//get the inclusions from the text data
//Sort through the comma seperated list and add it to $this->data['Study']['Inclusions']???
$this->Study->create();
if ($this->Study->save($this->data)) {
$this->Session->setFlash(__('The study has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The study could not be saved. Please, try again.', true));
}
}
$this->set('inclusions', $this->Study->Inclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Inclusion.name',
'recursive' => 0,
)));
$this->set('exclusions', $this->Study->Exclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Exclusion.name',
'recursive' => 0,
)));
$this->set('forms', $this->Study->Form->find('list', array('order' => 'Form.name','recursive' => 0,)));
}
View:
<div class="studies form">
<?php echo $this->Form->create('Study', array('type' => 'file'));?>
<fieldset>
<legend><?php __('Add Study'); ?></legend>
<?php
echo $this->Form->input('studyname', array('label'=>'Study Name','required' => true));
echo $this->Form->input('studynumber', array('label'=>'Study Number','required' => true));
echo $this->Form->input('file', array('label'=>'Select Electronic Consent','type' => 'file'));
echo $this->Form->input('consent_form_date');
?>
<fieldset class="inclusion">
<legend><?php __('Inclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Inclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $inclusions,
'selected' => $html->value('Inclusion.Inclusion'),
));
?>
</div>
<?php
echo $form->input('Inclusion.inclusions',array(
'type' => 'text',
'label' => __('Add New Inclusions',true),
'after' => __('Seperate each new Inclusion with a comma. Eg: family, sports, icecream',true)
));
?>
</fieldset>
<fieldset>
<legend><?php __('Exclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Exclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $exclusions,
'selected' => $html->value('Exclusion.Exclusion'),
));
?>
</div>
</fieldset>
<fieldset style="width: 700px;">
<legend><?php //__('Forms'); ?></legend>
<?php /*
echo $this->Form->input('Form',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $forms,
'selected' => $html->value('Form.Form'),
));
*/ ?>
</fieldset>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
You are trying to do pretty much the same as he wanted to do: Saving tags into a database table in CakePHP
What you have to do is:
Check if the manual inclusion field is empty or not. If the field is empty ignore it and go to step 5
If the field is not empty, split it at comma or whatever sign you want to use as a seperator. You can now validate it if you want to.
Use all the inclusions of step 3 and save them in your custom or real inclusion table. You should keep track of those custom entries in some way, so you don't mess them up with those you provided. Save all the ids generated while saving within an array.
Merge the collected ids of step 3 with those you got from the form which were given by you.
Save all collected and given data to database
The answere in the post given above including the code there can be used to do that. You should get along with it pretty well if you read the whole post + code comments ;)
If you have any further questions, just ask ;)
Greetings
func0der
hi all the data from my dropdown box isn't saving correctly to the database, its saving to the foreign key template_id as null
here is the function
function add(){
$this->Session->setFlash("Please create your required fields.");
$templates = $this->Template->find('all', array('fields' => array('Template.id' )));
$this->set('templates', $templates);
if($this->request->is('post'))
{
$this->Field->create();
if ($this->Field->save($this->request->data))
{
if($this->request->data['submit'] == "type_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'fields','action' => 'add'));
}
if($this->request->data['submit'] == "type_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
}
else
{
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
here is the view
<?php
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->input('name', array('label'=>'Name: '));
echo $this->Form->input('description', array('label'=>'Description: '));
echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'options' => $templates));
echo $this->Form->button('Continue adding fields', array('name' => 'submit', 'value' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'submit', 'value' => 'type_2'));
echo $this->Form->end();
?>
sorry guys it was a long day, it is saving the correcting information.