Date validation for custom field - SuiteCRM Version 7.10.4 Sugar Version 6.5.25 (Build 344) - sugarcrm

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,
),

Related

Customize select option on subpanel in SuiteCrm

I wanted to know if there's a way to customize the select option from the subpanel men in Suitecrm.
All one-to-many relationships for a module's subpanel are to be removed whereas for many to many need to rename it to "Associate Module 1 to Module 2 ".
Can I achieve this and this is to be done for all modules.
To remove buttons:
Assume that Target module and Lead module has one to many Relationshipship. Now Leads will be shown under the Traget Record Detailview. So if we want to remove selection and creation of Lead from Subpanel of Lead. Then we can hide this two buttons from following code:
Find The relation ship file in
custom/Extension/modules/Prospects/Ext/Layoutdefs/prospects_leads_1_Prospects.php
Remove Commented code as commented in this relationship code as Below,
And then Repair and Rebuild.
$layout_defs[“Prospects”][“subpanel_setup”][‘prospects_leads_1’] = array (
‘order’ => 100,
‘module’ => ‘Leads’,
‘subpanel_name’ => ‘default’,
‘sort_order’ => ‘asc’,
‘sort_by’ => ‘id’,
‘title_key’ => ‘LBL_PROSPECTS_LEADS_1_FROM_LEADS_TITLE’,
‘get_subpanel_data’ => ‘prospects_leads_1’,
‘top_buttons’ =>
array (
/*
0 =>
array (
‘widget_class’ => ‘SubPanelTopButtonQuickCreate’,
),
1 =>
array (
‘widget_class’ => ‘SubPanelTopSelectButton’,
‘mode’ => ‘MultiSelect’,
),
*/
),
);
moreover, you can check labelvalue and then change label in language file accordingly.
To Rename button at system level:
Place following language label in custom/include/language/en_us.lang.php
$GLOBALS['app_strings']['LBL_SELECT_BUTTON_LABEL'] = 'your label';
This will change the label for all but if you want to change it via some logic then see file: include\generic\SugarWidgets\SugarWidgetSubPanelTopSelectButton.php, it has public function getDisplayName() where you can add some logic to change that label in a specific condition. Hopefully, you will write that logic your own. Also, you can return empty html in those cases where you don't need button.

How to create floating point validation with two decimals in Yii2?

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);
}

ZF2 refresh input filter after dynamicly adding elements to form

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.

ZendFramework: Changing a form element after failed validation

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.

Drupal select list only submitting first character

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.