This cakephp form used to edit a mysql record needs to load the state of a radio button from a mysql database.
The mysql payment_type is enum('Account', 'Credit').
All of the other non-radio-button form inputs reload from the database and payment_type is correctly displayed on another form using this:
<?php echo h($purchaseOrder['PurchaseOrder']['payment_type']); ?>
Why doesn't this correctly set the radio-button from payment_type?
$options = array('account' => 'Account', 'credit' => 'Credit');
$attributes = array('legend' => false, 'value' => 'payment_type');
echo $this->Form->radio('payment_type', $options, $attributes);
In your attribute array, you should assign value which you want to keep selected by default .
For example you want account to be selected by default then in value you should assign 'account'. So your final attribute will be:
$attributes = array('legend' => false, 'value' => 'account');
Related
here is code of dropdownlist.. but when I select multiple values it gives validation error "task must be string"
how to save multiple values (array)?
<?php echo $form->field($model, 'task')->widget(Select2::classname(), [
'data' => $companiesList,
'options' => ['placeholder' => 'Select company...','multiple' => true],
'pluginOptions' => ['allowClear' => true,],
]);?>
how to give checkbox for each value in list?
you have to save multiple values in many-to-many tabels ,
after changing the rules to [['task'], 'safe'] from Mr Skull answer , you have to get all data like this :
foreach ( $model->task as $single_task){
$task = new _many_to_many_model();
$task->side_1_id = single_task;
$task->side_2_id = $model->id;
$task->save();
}
after this comment :
all selected value should go in single column
you don't need to use many-to-many !
I use "-" as delimiter,
$all_taskes = "";
foreach ( $model->task as $single_task){
$all_taskes .= single_task."-";
}
$model->task = all_taskes;
Hi there ,
$model->save();
foreach ($model->task as $cat) {
$m = new \common\models\_many_to_many_model();
$m->ads_id = $model->id; // change in to yorr base model ID and use it's put after $model->save
$m->category_id = $cat; // category_id is your many to many model filed id
$m->save();
}
I learned here how one can save the data to the fields of join table CoursesMemberships while adding or editing a student in CakePHP 3.x. In order to add grades for many courses I can do this in my add and edit forms:
echo $this->Form->control('courses.0.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.1._joinData.grade');
echo $this->Form->control('courses.2.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.2._joinData.grade');
...
but this form:
has a fixed number of courses for each student;
requires to select the course id from the list ('type' => 'select');
adds all courses to the student record even if not attended (well, the corresponding grade field can be kept empty, but still).
Is there a way to have a simpler form, where all courses are listed and one can only checkbox the course attended and enter the corresponding grade? I found it very challenging using control...
EDIT:
After #ndm suggested a very nice method below, I implemented it in the add.ctp:
foreach ($courses as $key => $course) {
echo $this->Form->control('courses.'.$key.'.id', ['type' => 'checkbox', 'hiddenField' => false, 'value' => $key,
'label' => $key]);
echo $this->Form->control('courses.'.$key.'._joinData.grades');
}
and corrected StudentsTable.php accordingly. And it runs with no problems.
However, if I do the same in edit.ctp, the previously saved records (e.g. for 1, 3, 5 and 7 courses are now listed as 1, 2 and 3 showing the grades for former 3rd 5th and 7th courses and the form forces me to check those three boxes. I understand that the first record disappeared because my courses start with id=1 (and so does the $key in the loop) and 'courses.0.id' is thus missing, but the general problem is that the empty fields removed by beforeMarshal function are no longer recognized in edit.ctp form and I cannot find a reasonable way to edit the student's record.
There is no build in support for what you are trying to achieve, you'll have to come up with a custom solution, which will likely either require a mixture of form and marshalling logic, or JavaScript.
You could create for example a list of checkboxes, and use the id value (wich will be zero in case the checkbox isn't checked, or the ID in case it is checked) to remove unchecked entries from the submitted data before marshalling, something like this:
echo $this->Form->control('courses.0.id', [
'type' => 'checkbox',
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', [
'type' => 'checkbox',
'value' => $courses[1]->id,
'label' => $courses[1]->title
]);
echo $this->Form->control('courses.1._joinData.grade');
// ...
// in the `StudentsTable` class
public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)
{
forach ($data['courses'] as $key => $course) {
if (empty($course['id'])) {
unset($data['courses'][$key])
}
}
}
Alternatively you could use JavaScript to disable the controls related to the checkbox so that they aren't being submitted in the first place. For this to work properly you'll need to make sure that you disable the hidden field that is by default being generated for checkboxes (see the hiddenField option), as otherwise zero will be sent for unchecked checkboxes.
Here's a quick, untested jQuery example to illustrate the principle:
echo $this->Form->control('courses.0.id', [
'class' => 'course-checkbox',
'data-join-data-input' => '#course-join-data-0',
'type' => 'checkbox',
'hiddenField' => false, // no fallback, unchecked boxes aren't being submitted
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade', [
'id' => 'course-join-data-0',
'disabled' => true
]);
// ...
$('.course-checkbox').each(function () {
var $checkbox = $(this);
var $joinDataInput = $($checkbox.data('join-data-input'));
$checkbox.on('change', function () {
$joinDataInput.prop('disabled', !$checkbox.prop('checked'));
});
});
See also
Cookbook > Database Access & ORM > Saving Data > Modifying Request Data Before Building Entities
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Options for Control
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Creating Checkboxes
I'm trying to query posts whose ACF field "show_on_frontpage" value is equal to "yes" (see definition of this field in screenshot below). As prescribed in ACF docs here's my code:
$args = array(
'posts_per_page' => -1,
'meta_key' => 'show_on_frontpage',
'meta_value' => 'yes'
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
if (get_field('show_on_frontpage')) the_field('show_on_frontpage'); ?>
endwhile;
}
This returns/displays nothing. If I used instead simply $args = array('posts_per_page' => -1); then I get all my posts and "yes" shows up for those that have "yes" as the value of their "show_on_frontpage" field.
What's wrong with my code?
According to this question/answer on the ACF forum:
https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/
It would be better to switch your checkbox field to a True/False field instead, since it appears that your checkbox group field only contains a single option.
Checkboxes are stored as serialized data and you’re not going to be able to use WP_Query to filter by a checkbox field.
If you use a true/false field then you can use WP_Query, the values of
a true/false field are 0 (zero) for false and 1 for true.
So if you switched your checkbox field to a True/False field, you would rewrite your code as follows:
$args = array(
'posts_per_page' => -1,
'meta_key' => 'show_on_frontpage',
'meta_value' => 1 /* or true */
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
/* My content for each post with the checkbox checked goes here */
endwhile;
}
This should work if you use the more recent meta_query => array() syntax:
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'show_on_frontpage',
'value' => 'yes',
'compare' => 'LIKE',
)
),
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
echo get_the_title();
// Post stuff
endwhile;
/* Restore original Post Data */
wp_reset_postdata();
}
Note that you need to give the post ID to the ACF helper functions get_field() & the_field() within the while loop.
See https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
On a wider note, this article calls into question the wisdom of using post_meta keys for this purpose and is worth a read: https://tomjn.com/2016/12/05/post-meta-abuse/. The article suggests using a custom taxonomy to achieve what you need - being better for performance.
i have a problem with the checkbox field that does not save me the data in the database . In the database I have the ' conditions ' field ( chekbox field ) as boolean . when sending the form I do not save as checked ( 1 ) .
my model
Rules
return[
'condizioniRequired' => ['conditions','required'],
'condizioniType' => ['conditions','boolean'],];
My view
<?= $form->field($model, 'conditions')->checkbox(array('label'=>'Offerted')); ?>
all other fields are saved.
You have to do like this :
<?= $form->field($model, 'conditions')->checkBox(['uncheck' => '0', 'checked' => '1'])->label('label'=>'Offerted') ?>
I hope this will help!!.
I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.