Drupal validation for nested field element - php

I have a drupal form for save details, I wrote validation for each element in the form. Following method is using for display errors. Then it automatically highlighted the required fields.
form_set_error('field_athletes_male', 'Athletes Male field is required.');
My problem is there is nested element names like as follows
field_coaching_programme[und][0][field_organisation_delivered_by][und][0][value]
Validation message is shown successfully but element is not highlighted

The answer you are looking for may already be in the documentation.
Here is the relevant part:
$name: The name of the form element. If the #parents property of your
form element is array('foo', 'bar', 'baz') then you may set an error
on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error
for every element where the #parents array starts with 'foo'.
Therefore you should try to do the following:
form_set_error("field_coaching_programme][field_organisation_delivered_by", t("Error Message"))

Tried following code and working as expected
form_set_error('field_coaching_programme][und][0][field_organisation_delivered_by', 'Organisation delivered by field is required.');

Related

Yii2 / Kartik Select 2 Tags - form field submitting data in extra array brackets

Hopefully this makes sense to someone.
I'm using Kartik-V Select2 widgets in a ActiveForm, with 'multiple' and 'tags' enabled. I'm using this elsewhere in my application and it is working fine there, and on submission the array data is sent as I would expect in the appropriate form field. From there I can easily implode the array and save to database in the controller action.
However in a different section of my app, with exactly the same configuration in the view, model and controller, the array is being posted as an additional form field (as can be seen watching the post event in the firefox console).
What I'm seeing in the firefox console is:
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to]"
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to][]"
admin
-----------------------------366976194315951562394252057249
Content-Disposition: form-data; name="Notes[notes_to][]"
kennettm
So where I would expect to receive the array in Notes[notes_to], it is actually coming through in Notes[notes_to][] but I can't for the life of me figure out how to access and handle these values in my controller, or how to get the array of tags submitted in Notes[notes_to] where I want it.
Thanks in advance.
***** EDIT *******
Thanks #Muhammed. I am expecting to received an array ['admin','kennettm'] (as with other areas of my app where I've used this setup), however in this instance that is not what is happening.
I've got the model and CRUD generated by Gii for the Notes section, so it does have its own MVC setup however the notes _form file in this case is rendered on the site index, so in this case the model is being loaded in the Site controller and is handled there. I can confirm that the same issue is occurring regardless of where I render the _form file, be it in the index or in the Notes section view.
I would expect that the data be returned in $notesmodel->notes_to as an array as mentioned above, which is then easily imploded and saved to db. However the data is not there on form submission, and "Public" is being saved every time. For the sake of testing, I removed the if statement, set the controller to implode the array and ensure that I add tags (so the array is sure to be there), however then I am receiving an error exception "implode(): Argument must be an array".
Snippet of my intended controller code is below. The controller checks to see if any tags have been added to the field. If tags are present, there should be an array which can be imploded and saved. Otherwise if no tags are present, it will revert back to a simple string "Public' and save that instead.
$notesmodel = new Notes();
if ($notesmodel->load(Yii::$app->request->post())) {
$notesmodel->notes_user = Yii::$app->user->identity->username;
$notesmodel->notes_created = date("Y-m-d H:i:s");
if (!empty($notesmodel->notes_to)) {
$notesmodel->notes_to = implode($notesmodel->notes_to);
} else {
$notesmodel->notes_to = 'Public';
}

How to show a field after validateForm() is called in Drupal 8?

Inside a hook_form_FORM_ID_alter() function I show or hide a field based on another checkbox field is checked or not with the following code in Drupal 8.
$form['field_my_url']['#states'] = [
'visible' => [
':input[name="field_my_checkbox[value]"]' => ['checked' => TRUE],
],
];
In case user checks field_my_checkbox checkbox, enters an invalid URL in field_my_url and decides to uncheck field_my_checkbox checkbox, the field_my_url will then be hidden with the invalid URL remaining. It will fail the validation because the enter URL is not valid.
The user will then be redirected back with the error message. But because the field_my_checkbox checkbox was not checked, the field_my_url field will be hidden with the error message and the user cannot see that.
In this case, how can I show the field_my_url field if it failed the validation because it contains invalid URL in Drupal 8?
I have found a solution. It might not be efficient. But it solves the problem for now, since there is no one come up with any solution on this moment. If the validation failed. I just unset the '#states' from the field. By doing this, no #states visible will be applied and the field_my_url will be show as normal.
unsert($form['field_my_url']['#states']);

Moodle display moodle_exception Error on form post

I am new to moodle and trying to customize my course creation in moodle.
I validated by moodle_form data in a function and from there I need to throw an error which will be displayed after the form (course/edit_form.php) is submitted. I tried the moodle way, as they have done:
throw new moodle_exception('refresher_value_less_than_one', '', '', $data->refresh_value);
I expected it to receive the error at the form page. It showed be the error string but not inside the form, but on a blank page.
Any idea, how to catch this exception in form.?
If you want to show an error within the form, then you need to create a function within your form class called 'validation($data, $files)'. Within this form, you need to check the values in the array $data, then return an array of error messages, indexed by the form field that the error should display beside.
For example, if you had a field called 'myfield', you could check the contents of $Data['myfield'] and, if there was a problem, return array('myfield' => get_string('myfielderror', 'myplugin')).
Throwing an exception will immediately halt the execution of the page and output only that error message.

How to customize validation message in the form in zend framework 2?

I have just started zend framework 2. I just want to know how to customize message in form for elements having require ON(true). Right now its showing "Please fill out this field" (If the particular textbox is empty and I click the submit button).
I just want to change this message. Initially I thought this message is coming from library
but I was wrong. Can this possible?
Please provide the method how you are creating your form. Ultimately you should simply overwrite the messages of the Validators. Each validator has the option to overwrite messages. The basic syntax is as follows:
// This assumes to be INSIDE a Validator
'options' => array(
'messages' => array(
\Zend\Validator\NotEmpty::IS_EMPTY => "Dude, it's empty. It shouldn't be!"
)
)
The example overwrites the NotEmpty validator message if no input is given. Furthermore you should know, that if you use the HTML5 Attribute required then some browsers will add a pre-submit-validation to your form and the error-message displayed by the browser cannot be changed.
$username = $this->createElement('text', 'username');
$username->addErrorMessage('The username is required!');

How do I remove unnecessary options from a select field in a Drupal form?

I'm using the better_exposed_filters module to create a set of exposed filters for a view. One of the filters is being displayed as a select field, and I would like the field to only display options that are actually associated with content in the database.
Currently, I am doing this using the hook_form_alter() method. For simplification, in the following example the field is called 'foo' and the content type with that field is called 'bar':
function my_module_form_alter(&$form, $form_state, $form_id) {
// Get all the values of foo that matter
$resource = db_query('select distinct field_foo_value from {content_type_bar}');
$foo = array();
while($row = db_fetch_object($resource)) {
$foo[$row->field_foo_value] = $row->field_foo_value;
}
$form['foo']['#options'] = $foo;
}
This works great -- the form displays only the options I want to display. Unfortunately, the view doesn't actually display anything initially and I also get the following error message:
An illegal choice has been detected. Please contact the site administrator.
After I filter options with the form once, everything seems to work fine.
Does anyone know how I can solve this problem? I'm open to an entirely different way of weeding out filter options, if need be, or a way that I can figure out how to address that error.
Under your view argument there should be a section called "Validator options" with ""Action to take if argument does not validate under it. Depending on what you want shown, you should be able to display all values or display an empty page.
I found a solution that works, but it's somewhat hackish. I force the form to think that it's validated, and it doesn't complain anymore, with the following line at the bottom of the function:
$form['foo']['#validated'] = true;

Categories