Show selected option in HTML Select menu after page has been reloaded in CakePHP - cakephp

I'm building a non-javascript version of a website, as there are a number of customers who don't have javascript enabled. On this site, the customer selects what country they will be visiting and then displays the data related to that country accordingly.
I've managed to get this to work. They use a HTML drop down menu to select the country, click on Submit, and the page reloads with the data related to the selected country. However, it does not change the country displayed in the HTML drop down menu, so when the page reloads it reverts back to "Select A Country".
What I would like to have happen is that if you clicked on United Kingdom from the drop down box for example, when the page reloads the drop down should display United Kingdom.
Here is the code I am currently using for the view file:
<form name="countryselect" action="/selected-country/" method="post">
<select id="country-list" name="countryselected">
<?php foreach($countries as $coun) { ?>
<option value="<?php echo $coun['Tariff']['countryslug']; ?>"><?php echo $coun['Tariff']['countryname']; ?></option>
<?php } ?>
<input type="submit" value="Submit" />
</select>
</form>
And in my controller file I am using this:
$countries = $this->Tariff->find('all', array('conditions' => array('Tariff.gsmid' => '1')));
$this->set('countries', $countries);
if (!isset($_POST['countryselected'])) {
} else {
$countryselect = $_POST['countryselected'];
$tarcounselect = $this->Tariff->find('first', array('conditions' => array('Tariff.countryslug' => $countryselect)));
$this->set('tarcounselect', $tarcounselect);
}
Cheers!

If you use Cake, you should not build the form and the select manually but use the Cake FormHelper instead. It will then keep the selected country automatically:
Controller:
$this->set('countries', $this->Tariff->find('list', array('conditions' => array('Tariff.gsmid' => '1'), 'fields' => array('countryslug', 'countryname'))));
View:
<?php
echo $this->Form->create();
echo $this->Form->select('Tariff.countryslug', $countries);
echo $this->Form->end(__('Submit'));
?>
And then to retrieve the selected country in the controller:
if($this->request->is('post'))
{
$countryslug = $this->request->data['Tariff']['countryslug'];
}

Related

How to get the data of a "multiselect option" coming from a cell

I created a cell to assemble a "multiple selection option" and inserted it into a view for the user.
Fill in the fields like this:
<select class="form-control" multiple id="product">
<?php foreach ($json["data"] as $product):?>
<option value="<?php echo $product["id"]; ?>"><?php echo $product["name"]; ?></option>
<?php endforeach; ?>
</select>
I added this cell to a user registration form along with other fields!
<?= $this->cell('Products');?>
How can I get the information selected by the user and send it to the controller after submitting the form?
Can I solve this using the cell?

Retrieve WordPress Database Info and display in form

Sorry I am new to WordPress and still having difficulty to retrieve my data from my custom database. So far this is my code for submitting data to my wp_datareg table.
<?php
/*
Template Name: Data-Register
*/
get_header();
?>
<?php
If($_POST['Submit']) {
global $wpdb;
$Data1=$_POST['Data1'];
$Data2=$_POST['Data2'];
if($wpdb->insert(
'wp_datareg',
array(
'Data1' => $Data1,
'Data2' => $Data2
)
) == false) wp_die('Database Insertion Failed');
else echo '<h2>Database Insertion Succesful</h2><p />';
?>
<?php
}
else // else we didn't submit the form so display the form
{
?>
<
<h4>Data Registration Form</h4>
<form action="" method="post" id="addcourse">
<p><label>Put Data1:<input type="text" name="Data1" size="30" /></label></p>
<p><label>Put Data2: <input type="text" name="Data2" size="30" /></label></p>
</div>
<input type="submit" name="Submit" id="addcoursesubmit" value="Submit" />
</form>
What I want to add is put another text form and search button where user can search a data of Data1 and edit its value on the form, (please see the image)
Sorry for being such a noob.
PLEASE SEE THIS IMAGE
Thank you.
br
We can fetch data from wp_datareg table using this code, however putting back the data to the form is my problem.
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM wp_datareg" );
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->Data1;?></td>
</tr>

CakePHP 2.x HABTM saveAll with Add view associated model optgroups

I have a CakePHP Add Photo View that is using optgroups so that the HABTM related Tag model's data is shown in grouped fashion in the view. In the Photo controller I send the related Tag model data as follows to get the optgroups grouping of Tags by Tag Category:
//fields shown to create optgroups eg group tags by category
$this->set('tags', $this->Photo->Tag->find('list', array(
'fields' => array('Tag.id', 'Tag.tagname', 'Tag.category'),
'conditions' => array(
'Tag.account_id' => $this->Session->read('Auth.User.account_id')))));
}
The view shows the Tags nicely grouped by Category. So that part works perfectly.
However, after adding a new Photo and selecting one or more Tags to assign to it, it does save the Photo properly but not the assigned Tags.
I believe that CakePHP saveAll is expecting a data array as would be delivered without the optgroup Category > Tag hierarcy, and is therefore not saving Tag data when new Photo is added and Tags are assigned to the Photo.
What do I need to do to give it the proper array to save the related Tags? Will it be in the controller after Create() where I 'remove' the Category grouping?
A bit of background on this from CakePHP http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
"If you would like to generate a select with optgroups, just pass data in hierarchical format. This works on multiple checkboxes and radio buttons too, but instead of optgroups wraps elements in fieldsets:"
$options = array(
'Group 1' => array(
'Value 1' => 'Label 1',
'Value 2' => 'Label 2'
),
'Group 2' => array(
'Value 3' => 'Label 3'
)
);
echo $this->Form->select('field', $options);
Output:
<select name="data[User][field]" id="UserField">
<optgroup label="Group 1">
<option value="Value 1">Label 1</option>
<option value="Value 2">Label 2</option>
</optgroup>
<optgroup label="Group 2">
<option value="Value 3">Label 3</option>
</optgroup>
</select>
Ok so this problem had nothing to do with the array structure.
It turns out I had 'Photo.Tag' instead of just 'Tag' in the Add Photo View. Here is the old Add Photo View code that didn't work:
<div class="photos form">
<p><?php echo $this->element('admin_nav'); ?></p>
<?php echo $this->Form->create('Photo'); ?>
<fieldset>
<legend><?php echo __('Add Photo'); ?></legend>
<?php
echo $this->Form->input('account_id', array('type'=>'hidden'));
//echo $this->Form->input('filename', array('type'=>'hidden'));
echo $this->Form->input('filename', array('type' => 'file', 'label' => 'Upload photo'));
echo $this->Form->input('desc');
echo $this->Form->input('Photo.Tag' , array('label'=>'Tags', 'multiple'=>'checkbox'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
Here is the new Add Photo View code which now saves the new photo with the tags selected:
<div class="photos form">
<p><?php echo $this->element('admin_nav'); ?></p>
<?php echo $this->Form->create('Photo'); ?>
<fieldset>
<legend><?php echo __('Add Photo'); ?></legend>
<?php
echo $this->Form->input('account_id', array('type'=>'hidden'));
//echo $this->Form->input('filename', array('type'=>'hidden'));
echo $this->Form->input('filename', array('type' => 'file', 'label' => 'Upload photo'));
echo $this->Form->input('desc');
echo $this->Form->input('Tag' , array('label'=>'Tags', 'multiple'=>'checkbox'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
While the Cakephp documentation on Saving Data makes references to how the array should be formatted, this appears to refer to all of the other relationships excluding HABTM. HABTM relationships can be saved in one action with the save on the parent model, in this case the Photo model eg:
$this->Photo->save($this->request->data)
will save the new Photo being added, plus any of the selected Tags, and they will be saved in the join table photostags.
What is a bit unusual, is that $this->Photo->save($this->request->data) appears to work same as $this->Photo->saveAll($this->request->data).

CakePHP 2.0 $this->Form->input()

This is my add.tcp
...
<?php
echo $this->Form->create('Group');
echo $this->Form->input('group_id', array('label' => 'ID'));
echo $this->Form->input('group_desc', array('label' => 'Group Description'));
echo $this->Form->end('Save');
?>
Table name: groups
Table fields: group_id, group_desc
PK: group_id
This is my controller
...
class GroupsController extends AppController {
public $helper = array('Html', 'Form', 'Session');
public $components = array('Session');
public function add() {
if ($this->request->is('post')) {
if ($this->Group->save($this->request->data)) {
$this->session.setFlash('');
$this->redirect(array('action' => 'index'));
}
}
}
}
When I display this view on the browser, there was nothing for the field group_id but there was for the group_desc, the HTML source for the look like this
...
<form action="/cakephp/index.php/groups/add" id="GroupAddForm" method="post" accept-charset="utf-8" name="GroupAddForm">
<div style="display:none;">
<input type="hidden" name="_method" value="POST">
</div><input type="hidden" name="data[Group][group_id]" id="GroupGroupId">
<div class="input text">
<label for="GroupGroupDesc">Group Description</label><input name="data[Group][group_desc]" maxlength="15" type="text" id="GroupGroupDesc">
</div>
<div class="submit">
<input type="submit" value="บันทึก">
</div>
</form>
Why it was hidden?
CakePHP automagically determines that you do not want a user to manually enter an ID, as such hides it for you.
If you would like to force ID field to be shown, set the type to text:
echo $this->Form->input('group_id', array('type' => 'text', 'label' => 'ID'));
Because primary key inputs are hidden by default.
CakePHP creates the primary key for you on add as auto increment INT or uuid CHAR
Manually creating your primary keys is not recommended.
you can change the hidden type to text:
echo $this->Form->input('group_id', array('label' => 'ID', 'type' => 'text'));
As per your database structure I want to suggest something:
Your group table has group_id as primary key
make it auto_increment from database and there is no need to put that id manually on add form, it will be saved automatically. Form fields generate as per model structure.

How can I display CakePHP input validation errors in a different spot the default?

Let's say I have field that looks like this in the view:
<li class="bigfield">
<?php echo $form->input('phone', array(
'placeholder' => 'Phone',
'label' => false,
'between' => '<br />'
)); ?>
</li>
If I have a validation rule on this field and validation fails, I see the following HTML:
<li class="bigfield">
<div class="input text required error">
<br>
<input name="data[Appointment][email]" type="text" placeholder="Email"
maxlength="45" value="" id="AppointmentEmail" class="form-error">
<div class="error-message">Please enter a valid email address</div>
</div>
</li>
I'm like to do something like move the error message div to an entire different part of the page rather then have it inside with the same <li> as the field itself. What would be the most straight forward way of doing this?
Just updating an old post.
The validations errors are automatically passed on to view (as pointed out by #Angel S. Moreno)
$this->validationErrors
In you controller:
$this->set('validationErrorsArray', $this->ModelName->invalidFields());
You will have $validationErrorsArray in your views.
UPDATE (Sept. 2014):
From the view
From CakePHP 2.3 you can access validation errors array from the view:
$this->validationErrors;
From the controller
If you tried to save data in the controller you can access validation errors this way:
$this->ModelName->validationErrors;
If you want to validate data before saving do it this way:
$this->ModelName->set($this->request->data);
if ($this->ModelName->validates()) {
$this->ModelName->save();
} else {
$errors = $this->ModelName->validationErrors;
// handle errors
}
Validating Data from the Controller
From controller you can use:
$this->Modelname->validationErrors['TheFieldYouWantToDisplay'] = 'This is not correct'
In your case it would be like this in your controller:
$this->Appointment->validationErrors['email'] = 'Error message'
This code is just to make a custom error message on the fly. But you can also define $validate in the model and do it like how brancer has described it.

Resources