Turn off required field validation based on query string value? - validation

I have a registration form with about 30 fields (yes.. I know.. insanity). I need some of these fields to be required by certain types of people. What I'd like to do is just use a query string like example.com/user/register/?type=notrequired. If type = notrequired then I'd like to make to make the fields not required. Is this possible? I tried using the jQuery Validate plugin but its not working.. I'm thinking the built in Drupal validation is conflicting with it :(

The required flag is set server side so I doubt you'll be able to affect it using javascript. You'll have to hook into the form and make the changes in PHP, something like this in a custom module:
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
if (isset($_GET['element_name']) && $_GET['element_name'] == 'notrequired') {
$form['element_name']['#required'] = FALSE;
}
}
Hope that helps

Related

How to disable a Dynamics CRM field when the value changes without breaking save?

We have a two state field called Primary that is set to either yes or no. When the field is set to no, the user should be able to change it to yes. When the field is set to yes, it should be disabled, so the user can no longer change it.
We have code in the onload event that handles this; that works just fine. The challenging case is the one where a user changes the field from no to yes and then saves the form. This should lock the field so the user can't change it back to no. We attempted to solve this by putting the following code in onsave event:
export function onSave() {
var primaryControl = Xrm.Page.getControl(
d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
if (primaryControl) {
if (primaryControl.getAttribute().getValue()) {
primaryControl.setDisabled(true);
}
else {
primaryControl.setDisabled(false);
}
}
}
This partly works. It does disable the field so it can no longer be changed. The save doesn't work, however, because Dynamics CRM appears not to send the values of disabled fields back to the server during the save, so the new value does not actually get saved.
Any ideas would be welcome. :)
It seems the following line solves my problem:
Xrm.Page.getAttribute(d.ConstituentAffiliation.AttributeNames.Primary
.toLowerCase()).setSubmitMode("always");
So the code now reads as follows:
export function onSave() {
var primaryControl = Xrm.Page.getControl( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
if (primaryControl) {
if (primaryControl.getAttribute().getValue()) {
Xrm.Page.getAttribute( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase() ).setSubmitMode("always");
primaryControl.setDisabled(true);
}
else {
primaryControl.setDisabled(false);
}
}
}
I should credit this blog which was very helpful: http://blogs.msdn.com/b/arpita/archive/2012/02/19/microsoft-dynamics-crm-2011-force-submit-on-a-disabled-field-or-read-only-field.aspx
Looks like you've solved it however I was curious. Have you tried using a Business Rule? This kind of basic functionality is what Business Rules in CRM 2015 can handle quite well.
For example something like this:-

Advanced Validation with Lithium PHP Framework

I'm building a pretty complex and dynamic form via the Lithium PHP framework.
I've got the form working and saving to MongoDB with little problem. But I am having trouble with validation.
Simple validations (such as checking if a field is not empty or is numeric) are working fine. But I have to do a few complex validations that rely on a number of fields in the form.
For example, I have a form where a user can enter a question and then enter an unlimited number of possible answers for this question. The field ID for each answer is listed such as "answer_1", "answer_2", "answer_3", etc. The user can add an unlimited number of answers. This happens via some fancy JavaScript that inserts extra elements to the form on the client side.
At the validation level, I want to make sure that every answer which was added is not null.
I would like to do this using the "traditional" Validator functionality built within Lithium. I am also doing this at the Model level, not the Controller level (note - I have a workaround to solve this on the Controller level, but would rather do it the "right" way at the Model)
The problem, as far as I can tell, is that you can only pass a single value to the validator rule. I just need to pass back ALL values in the form to the validator. If I could do that, I would be golden. The pseudo-code for what I'm looking to do looks like this:
Validator::add('CorrectTest', function(&$value, $format = null, array $options = array()) {
foreach ($_data as $key => $value) {
if (stristr($key, "answer_")) {
if ($value == "") {
return false;
}
}
}
return true;
});
This code doesn't work, because the $_data value is not present. If I could just figure out a way to get a fully-populated "$_data" object into the Validator function, I think I could get this to work.
Thanks in advance for the help
Take a look at what's inside $options. You should have a 'values' key in there that has all of the values from the form.
So try
$_data = $options['values'];

jQuery Validate, changing rules on the fly

I have been setting up my jQuery Validate rules in Javascript much like in this article:
http://www.raymondcamden.com/index.cfm/2009/2/10/An-Introduction-to-jQuery-and-Form-Validation-2
I store the rules in a jsony object called validationRules, then I pass the rules when I invoke the Validate plugin:
$("#myForm").validate(validationRules);
Later, I'd like to programatically change values based on user interactions, like this:
validationRules.rules.Quantity.min=10;
even though the value is updated, Validate doesn't honor the new value. I also tried, re-invoking the plugin:
$("#myForm").validate(validationRules);
but that didn't help.
I can just talk directly to the plugin:
$("#Quantity").rules("add", {min: 10});
and it behaves as one would expect. So I will use that syntax to change rules on-the-fly, but could someone shed some light on how I can tell Validate to honor the updated rules in validationRules?
I had the same problem and I have spent a lot of time trying to solve it. Finally I find a trick in the Validation Plugin creator´s GitHub account:
var $form = $('#formId'),
newRules = {rules...},
newMessages = {messages...};
$.each(newRules , function(key, value) {
newRules [key] = $.validator.normalizeRule(value);
});
$.extend( $form.validate().settings.rules, newRules );
$.extend( $form.validate().settings.messages, newMessages );
I am not quite sure about the messages, I am using it right now and seems to work fine.
This is the link where you can read more about it:
https://github.com/jzaefferer/jquery-validation/issues/214

Applying form errors manually

I have a situation where I'm editing a snippet of data within a larger context. The user submits this data to a specialized action for handling and redirects back to the parent page. Because it's a redirection, validation errors aren't getting automagically set, so I'm trying to work around that.
In the event of an error, I'm writing a validation_errors key to the session with a value of $model->validationErrors. In the form, though, I'd like to tell Cake to set each error so I can leverage my existing styles and not have to make a lot of changes to my $this->Form->input() methods.
Is something like this possible? Essentially, I'm looking to manually achieve the same result you'd get if a regular form was submitted and allowed to drop through with validation errors. I was hoping I could loop over each validation error and set the field error, but that's not making any change at all.
Thanks.
This can be achieved in the controller by
$this->Model->invalidate('fieldName', __('ErrorMessage', true));
If the values are available, you can also call
$this->Model->validates();
to validate all values with the validators defined in the model.
Save the data to the session and revalidate it.
function childAction() {
if(isset($this->data)) {
$this->Session->delete('invalid_data');
if($this->Test->save($this->data)) {
// ...
} else {
$this->Session->write('invalid_data', $this->data);
}
$this->redirect(array('action'=>'parentAction'));
}
}
function parentAction() {
if($this->Session->check('invalid_data')) {
// This will cause $this->Test->validationErrors to be populated
// Assuming your parent page has the form set up properly, the
// errors will be automagically filled. ie: $form->input('Test.field1')
$this->Test->set($this->Session->read('invalid_data'));
$this->Test->validates();
}
}
If you want to do the same with CakePHP 3, use the method "errors".

Accessing data in kohana validation

i'll try and be as clear as possible.
I'm working on some form validation using the wonderful kohana framework. However i have come at a crossroads and not sure whether the way i have taken is a wise choice.
Basically, i have a date selector using several select boxes (i toyed with the idea of using javascript date pickers but the select boxes proved to be more suitable for my purpose) and a date field in a database. I wanted to concatenate these select boxes into the date field so it can be checked to make sure its valid.
protected $_rules = array(
'mydate' => array(
'not_empty' => NULL,
'date' => NULL,
),
);
Now to me, it makes most sense to include the validation in the model, since that's where the data layer is in the MVC pattern, so i decided to create some class attributes named $_rules, $_filters and $_callbacks, each set as protected and with my basic rules applied. And then a function in the model that sets up a validation object using these attributes and returning it to whatever controller is calling it, then the controller can just run the validation and the job is done.
My problem comes when i want to concat these select boxes, to me it makes most sense to make a custom filter and pass in the post data, but with the filters rules and callbacks being attributes, i can't add any variables to them. My current solution is to manually add the extra filter in when the validation setup function is being run something similar to this:
public function setupValid($post) {
$this->_filters['mydatefield'] = array(
'MyClass::MyConcat' => array($post);
);
//creates a validation object and adds all the filters rules and callbacks
}
But i don't feel this is the cleanest solution, i'm probably nit picking as the solution works the way i require it to. However i'm not sure whether a filter was ever intended to do such a thing as this, or whether this should be a callback as the callback has access to the array by default, but then again callbacks are called last, which would mean i couldn't apply any rules like, 'not_empty' (not important in this case since they are pre populated select boxes, but might be in another case)
So i guess my question is, am i using filters as they were intended to be used?
I hope i've managed to explain this clearly.
Thanks
you need to keep in mind that you should only validate fields inside the $_rules that are very important to your database or business logic.
so for example if you would try to setup other form somewhere else in your app or you would provide a restfull api for your app, validation of the field 'day_field_(that_doesnt_exists_in_the_database_and_is_used_to_privide_a_better_ux_in_this_one_form)' => array('not_empty' => NULL) will give you a hard time to do that.
so i suggest you to keep your $_rules like they are now and provide some logic to your values() method:
// MODEL:
public function values($values)
{
if ( ! empty($values['day']) && ! empty($values['month']) && ! empty($values['year']))
{
$values['mydate'] = $values['year'].'-'.$values['month'].'-'.$values['day'];
}
return parent::values($values);
}
// CONTROLLER:
if ($orm->values($form['form_array'])->check())
{
$orm->save();
}
else
{
$this->template->errors = $orm->validate()->errors('validation');
}

Resources