I have tried creating a validation for a field which stores unit price of a product, I come across validation showing how to check for integer, but I can't found one for floating point number something with a format like 2032.95 in YII2. Thanks in advance.
*
After Abilay instructions I tried
[['quantity','round_off'],'number','numberPattern'=>'[-+]?[0-9]*.[0-9]+|[0-9]+'],
but it shows error in console.
I think, redefining of numberPattern of NumberValidator class will help in your case.
If you use AJAX Validator on your form:
In Model:
[['quantity','round_off'], 'number',
'numberPattern' => '/^\d+(.\d{1,2})?$/'],
In View:
Ensure that you enabled AJAX Validation when created form
$form = ActiveForm::begin([
'id' => 'my-form',
'enableAjaxValidation' => true,
]);
and change field to default input
$form->field($model, 'quantity')
In Controller:
Include files:
use yii\web\Response;
use yii\widgets\ActiveForm;
Past this code at the beginning of action, after
$model is loaded or created
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Related
I have two fields in my module called: start_date_c & end_date_c with date datatype
These fields are not mandatory fields however when i enter data into the end_date_c field I would like to make it is not less than start_date_c
I have tried the following:
https://suitecrm.com/suitecrm/forum/suitecrm-7-0-discussion/12522-how-to-validate-start-and-end-date-in-suitecrm
http://sugarmods.co.uk/how-to-add-custom-validation-to-form-fields-in-sugarcrm/
but as i am new to suiteCRM, i am not able to find positive response
You will need 2 things
Edit the file editviewdefs.php in the module you want to add the logic. This field will be autogenerated when you add the first custom field to the edit view.
Create your custom JS logic to define when the field is valid.
This logic here will add a validation callback for your
addToValidateCallback(
'EditView', // Form Name
'end_date_c', // field name
'datetime', // Field type
false, // Is required
"End date cannot be earlier than start date", // Message
function() {
//WRITE YOUR JS VALIDATION HERE, return true when is valid
});
In the editviewdefs.php find the field definition and use the displayParams to make suite/sugar add the JS for you.
array (
'name' => 'end_date_c',
'displayParams' =>
array (
'updateCallback' => 'FUNCTIONNAME',
),
),
The last step ain't needed if you already have a global custom JS (like style.js file for a custom theme).
EDIT: javascript DisplaParams will not work, so added the updateCallback option.
Now this validation works in 2 ways.
The updateCallback will be fired onChange
The addtoValidateCallback will be fired on Save.
This will give you enough flexibility to validate the form.
Simple and one linear, try following in any JS file (added in module edit view):
addToValidateDateBefore('EditView', 'start_date_c', 'date', false,'Date Start', 'end_date_c' );
worked for me.I added the following code to the fields in modules/custom_module/vardefs.php
'audited' => true,
'enable_range_search' => true,
and added the following to the start field
'validation' =>
array (
'type' => 'isbefore',
'compareto' => 'enddate',
'blank' => true,
),
I'm not quite sure about the way of doing.
The challenge:
I call an addAction which shows a form. The point of calling the addAction gives two routing parameters, say value1 and value 2 separated by an "-".
I need value 1 and value 2 to search a pk in a table which will be saved as a foreignkey value by the addAction. I take both values give it to a method and get the key I need, that is tested and ok so far.
My problem.
In the first call of addAction I get the routing parameters and find the key. But afterwards of course it is forgotten. How can I remember the found value, so that I can use it for my saveModel method?
What would be the best way?
Idea 1:
Can I give it to the form and set it as value to the hidden keyfield?
For example:
class PadForm extends Form
{
public function __construct($name = null, $unitpartid)
{
parent::__construct('pad');
$this->add([
'name' => 'UnitPartPadID',
'type' => 'hidden',
'value' => $unitpartid,
]);
Would this be working? And would this be an accepted, proper way?
Idea 2:
Or would I try to use an instance variable in my controllerclass, like $this->smtg; ?
In both cases I get an understandable error
Trying to get property of non-object
Questions:
what would be the best way?
and
how to do it, perhaps somebody could give a short example.
EDIT:
I really would appreciate to learn about the best way. I now tried to give a variable to my form and then fill in some field, but that doesn't work.
Part of Controlleraction
(the action works if I set a constant value for the related field)
$parameter = $this->params()->fromRoute('id');
// echo $parameter;
$partnumber =substr($parameter,0,strpos($parameter,"-"));
// echo $partnumber;
$unitid=substr($parameter, strpos($parameter,"-")+1, strlen($parameter));
// echo $unitid;
$test=$this->unitparttable->getUnitPartID($unitid, $partnumber);
echo $test->UnitPartID;
$form = new PadForm(NULL, $test->UnitPartID);
Then in the Formclass:
public function __construct($name = null, $unitpartid)
{
// We will ignore the name provided to the constructor
parent::__construct('pad');
// $this->db=$db;
$this->add([
'name' => 'UnitPartPadID',
'type' => 'hidden', //hidden
]);
$this->add([
'name' => 'UnitPartID',
'type' => 'text', //hidden
'value' => $unitpartid,
]);
The question is now, how to fill the formfield UnitPartID with the value of $unitpartid given within the constructor.
I also tried $form->populate but it is unknown, I used it in ZEND1 before, but probably it doesn't exist anymore.
any help appreciated!
I have a form that triggers on event in __construct method to load some items from another modules . So far so good , a field set is loaded from the other module and added to the form and in the request->getPost() I have the data for the elements inside the fieldset , but the $form->getData() doesn't have the data for the fieldset.
I am calling $form->getInputFilter() before adding this fieldsets to the form and it seems that calling the $form->getInputFilter() dosn't creates the filters for the newly added elements . so how can i create inputfilters for the dynamic events without recreating the hole filters again ?
Or should i just delay calling $form->getInputFilter() untill all of the elemnts have been added to the form ?
I also added some elements to the form later what was ignored by the input filter.
My solution is most likely not exactly the best one, but as you haven't received any other answers yet, here's what I did:
I added
use Zend\InputFilter\Factory as InputFactory;
in the class where I'm validating the form data and then used
$factory = new InputFactory();
$form->getInputFilter()->add($factory->createInput(array(
'name' => 'title_str',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
#Afterdark017 that works and also i think it is possible to reset the filters.
protected function resetFilters(){
$this->filter = null;
$this->hasAddedInputFilterDefaults = false;
}
but i have not tested this yet.
So I have a form set up in the following manner:
In my forms directory:
Address.php
class Address extends Zend_Form{
// Creates an address input box including address/country/state/zip
// The states is created as a drop down menu
public function init() {
// relevant code to question
$this->addElements(array(
array('select', $names['state'], array(
'label' => "State",
'class' => 'state',
'multiOptions' => array('' => '') + AddressHelper::stateList(),
'required' => $this->_required,
)),
));
}
}
MyForm.php:
class MyForm extends Zend_Form {
public function init() {
//set-up some general form info
// this is the relevant part for my question
// $opt is a predefined variable
$this->addSubForms(array(
'info' => new SubForm($opts),
'mailing' => new Address($opts + array(
'legend' => 'Address',
'isArray' => false,
'required' => true,
)),
));
}
}
Survey.php
class Survey extends MyForm{
// initialize parent (MyForm) and add additional info for the Survey form
}
Okay, so when survey is submitted, if it fails validation, I need to change the Address state element from a select to an input type=text.
So in my controller, under the action that checks for validation I have the following:
public function createAction(){
if ($this->_form->isValid($post)) {
$this->_saveDraft($post, $this->_submissionType);
$this->addSessionMessage('Submission created!');
return $this->redirector->gotoRouteAndExit(array(), 'home', true);
}else{
/* IMPORTANT */
// I need to change the Address select field to a text field here!
$errors[] = 'There was a problem';
$this->view->assign(compact('form', 'errors', 'submission'));
$this->_viewRenderer->renderScript('update.phtml');
}
}
So, would I just create a method in the Address class and somehow call it to swap out. I'm just not sure how to go about this.
You would be looking at using removeElement() to remove the select element, and then addElement() to replace it with the text only version.
The problem you are going to have is that when the validation fails, the select element is changed to a text element and the form is re-displayed. Now, upon resubmission, you need to make the change again prior to calling isValid() because the form uses text input for state instead of select. So you need to make the change twice. Once after failed validation prior to re-displaying the form, and once prior to calling isValid(), but only if there was a previously failed submission.
Now why is it that if the form fails validation, you want the select element for state to be text? Can't it work just the same with a select element and you just pre-select the correct state for them?
EDIT:
You use the form object to call add/removeElement.
$removed = $form->getSubForm('mailing')->removeElement('state_select');
$form->getSubForm('mailing')->addElement($text_state_element);
That call should work to remove an element from a subform.
Without subforms, it is just:
$form->removeElement('username');
$form->addElement($someNewElement);
You can use getElement() in a similar way if you need to get an element from a form to make changes (e.g. remove/add validators, change description, set values)
$el = $form->getElement('username');
$el->addValidator($something)
->setLabel('Username:');
Hope that helps.
I have a select list I've created in a form alter, however, when I select an option and submit the value, only the first digit gets stored in the database. I know this has something to do with how the array is formatted, but I can't seem to get it to submit properly.
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
$form['field_sr_account'] = array( '#weight' => '-50',
'#type' => 'select',
'#title' => 'Select which account',
'#options' => addSR_getMultiple());
//Custom submit handler
$form['#submit'][] = 'addSR_submit_function';
}
function addSR_submit_function{
$form_state['values']['field_sr_account'] = array('0' => array('value' => $form['#field_sr_account']));
Below is the function that returns the associative array. It is returning the proper options, as I can view the correct value/option in the HTML source when the page loads
//The values returned are not the problem, however, the format of the array could be..
function addSR_getMultiple(){
$return = array();
$return['one'] = 'Choice1'
$return['two'] = 'Choice2'
return $return;
}
Update:
Drupal 6: Only inserting first character of value to MySQL
I had a similar issue with the same field. However, in that case, I knew the value I wanted to submit, and I was able to assign the value to the field in the form alter, before the form was submitted. The difference with this issue, is that I don't know the value of the field until it is submitted, so I can't "assign" it in the form alter. How can I assign it the same way in the submit handler.
Edit after question update (and discovery of root problem within the linked separate question):
As you are trying to manipulate CCK fields, and those have pretty special handling mechanisms compared to 'standard' Drupal FAPI form elements, you should probably read up on CCK form handling in general, and hook_form_alter() and CCK fields and CCK hooks in particular. Glancing at those documentations (and the other CCK articles linked in the left sidebar), it looks like there should be a straight forward solution to your problem, but it might require some digging.
As a potential 'quick fix', you could try keeping your current approach, and adjust the submitted value on validation, somewhat like so:
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
$form['field_sr_account'] = array(
'#weight' => '-50',
'#type' => 'select',
'#title' => 'Select which account',
'#options' => addSR_getMultiple()
);
// Add custom validation handler
$form['#validate'][] = 'addSR_validate_function';
}
function addSR_validate_function (&$form, &$form_state) {
// Assemble result array as expected by CCK submit handler
$result = array();
$result[0] = array();
$result[0]['value'] = $form_state['values']['field_sr_account'];
// Set this value in the form results
form_set_value($form['field_sr_account'], $result, $form_state);
}
NOTE: This is untested code, and I have no idea if it will work, given that CCK will do some stuff within the validation phase as well. The clean way would surely be to understand the CCK form processing workflow first, and manipulating it accordingly afterward.