Field validations in sugarcrm - sugarcrm

I just started using SugarCRM CE for the first time (Version 6.5.15 (Build 1083)). I'm quite impressed with the ease of use when adding new fields or modules, but there's one quite indispensable thing that seems to be missing: Validation of user input.
I would for example like to check a lot of things:
Check if a emailadres has a valid format, using some regular expression
Check if a postalcode exists (maybe do a webswervice call to validate it)
Do a calculation to see if a citizen service number is valid
etc.
The only thing I seem to be able to do in studio is make a field required or not, there doesn't seem to be any standard way to execute a validation on a field.
All I can find when I google on it is lots of ways to hack into the source code, like this one: http://phpbugs.wordpress.com/2010/01/22/sugarcrm-adding-javascript-validation-on-form-submit/ And even then I don't find any examples that actually do a validation.
Am I just missing something? Or is editing source code the only way to add this?

I don't think the "standard" validations are available in the CE edition.
What surprises me is that you can't define a validation somewhere and attach it to a field. I kind of expected this, since the rest of the system is very well structured (modules, packages, etc..)
I now for instance created a 11-check, this is a very specific check for a dutch bank account number. to get this to work, I did the following (based upon examples I found googling around):
I added the bank account to contacts in studio and after that edited \custom\modules\Contacts\metadata\editviewdefs.php
I added the following snippets:
'includes'=> array(
array('file'=>'custom/modules/Contacts/customJavascript.js')),
array (
0 =>
array(
'customCode' =>
'<input title="Save [Alt+S]" accessKey="S" onclick="this.form.action.value=\'Save\'; return check_custom_data();" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL']>',
),
1 =>
array(
'customCode' =>
'<input title="Cancel [Alt+X]" accessKey="X" onclick="this.form.action.value=\'index\'; this.form.module.value=\''.$module_name.'\'; this.form.record.value=\'\';" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL'].'">'
)
),
And in customJavascript.js i placed this code:
function check_custom_data()
{
if (!eleven_check(document.getElementById("bankaccount_c").value)){
alert ('Bank account not valid');
return false;
} else {
return check_form('EditView');
}
function eleven_check(bankaccount) {
bankaccount=bankaccount.replace(/\D/, "");
charcount=bankaccount.length;
var som=0;
for (i=1; i<10; i++) {
getal=bankaccount.charAt(i-1);
som+=getal*(10-i);
}
if (som % 11==0 && charcount==9) {
return true
} else {
return false
}
}
}
This check now works the way I want it to work, but I'm wondering if this is the best way to add a validation. this way of adding a validation doesn't however accommodate PHP validations, for instance, if I want to validate against some data in the database for one or another reason, I would have to use ajax calls to get that done.

Email validation is in the pro edition, I had assumed it was in CE as well but I'm not 100% sure.
The other 2 are a lot more specific - postcode validation would depend upon your country so would be difficult to roll out. For these you will need to write your own custom validation.

I know its late, but maybe still someone needs this.
You can just add your custom javascript validation as a callback in your vardefs like this:
'validation' =>
array (
'type' => 'callback',
'callback' => 'function(formname,nameIndex){if($("#" + nameIndex).val()!=999){add_error_style(formname,nameIndex,"Only 999 is allowed!"); return false;}; return true;}',
),
I documented it here as its not well documented elsewhere:
https://gunnicom.wordpress.com/2015/09/21/suitecrm-sugarcrm-6-5-add-custom-javascript-field-validation/

You can add custom validation code to the following file: ./custom/modules/.../clients/base/views/record/record.js
There you can add validation code. In this example, I will validate if the phone_number is not empty when an accounts has a customer-type:
EXAMPLE CODE IN RECORD.JS:
({
extendsFrom: 'RecordView',
initialize: function (options) {
app.view.invokeParent(this, {type: 'view', name: 'record', method: 'initialize', args:[options]});
//add validation
this.model.addValidationTask('check_account_type', _.bind(this._doValidateCheckType, this));
},
_doValidateCheckType: function(fields, errors, callback) {
//validate requirements
if (this.model.get('account_type') == 'Customer' && _.isEmpty(this.model.get('phone_office')))
{
errors['phone_office'] = errors['phone_office'] || {};
errors['phone_office'].required = true;
}
callback(null, fields, errors);
}
})
Don't forget to repair en rebuild!
The full documentation can be found here

Related

ReferenceInput Select Input for Filter component Form

I built a custom Filter component for my List View and Im having trouble populating a Select Input of ALL available options for a property. for instance
<Form onSubmit={onSubmit} initialValues={filterValues} >
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<ReferenceInput label="Ring Id" source="ringid" reference="candidates">
<SelectInput optionText="ringid" />
</ReferenceInput>
</form>
)}
</Form>
Without building a "getMany" dataProvider Im told that I can access all of the (2,000+ ids) "ringid"s pulled in from the "getList" provider and list every ID into the SelectInput field and search in my custom Filter component.
Issues presented:
I have to hard code amount of results I can have (Default 25)
When I submit the form to Search through the filter component "Associated reference no longer appears to be available." appears and the search fails.
The "getMany" component is only half way built but it seems that ReferenceInput only wants to use "getMany"(Im told that building the backend and building code to use getMany is not an priority to build so I cant build it myself)
25 Populated IDs Screenshot
Form Error when Filter is submitted ScreenShot
So I would like some help in the right direction to populate a SelectInput of all available ids in the getList dataProvider and be sure that I can even use this input in my Filter form component. Thank you in advance for any feedback.
1: Yes, i think there's no option to add pagination to ReferenceInput, you must hardcode it, but, if your backend already supports text search, you can use an AutocompleteInput as child, allowing users to filter results:
<ReferenceInput
label="Ring Id"
source="ringid"
reference="candidates"
filterToQuery={searchText => ({ paramNameThatYourBackendExpects: searchText })}
>
<AutocompleteInput optionText="ringid" />
</ReferenceInput>
2 & 3: 2 happens because of 3. ReferenceInput only "wants" to use getMany because it also support SelectManyInput as child, for such case, it's better to get all selected options at once, than calling one by one, so, to make code simpler, ReferenceInput always use getMany. If you can't implement backend part of getMany, but can add code to your dataProvider, you can implement getMany by making multiple getOne calls:
Assuming a v3 dataProvider:
this.getMany = async (resource, params) => {
const response = {data: []}
for (const id of params.id) {
response.data.push(await this.getOne(resource, {id}))
}
return response
}
v2 is implementation-dependant, just follow the same principle.
If you can't change the dataProvider, e.g, a third-party available dataProvider, you can wrap it:
v3
const fakeGetManyDataProvider = dataProvider => ({
...dataProvider,
getMany: async (resource, params) => {
const response = {data: []}
for (const id of params.id) {
response.data.push(await dataProvider.getOne(resource, {id}))
}
return response
}
})
v2
import { GET_MANY, GET_ONE } from 'react-admin'
const fakeGetManyDataProvider = dataProvider => async (verb, resource, params) => {
if (verb === GET_MANY) {
const response = {data: []}
for (const id of params.id) {
response.data.push(await dataProvider(GET_ONE, resource, {id}))
}
return response
}
return dataProvider(verb, resource, params)
}
Please note that error handling is omitted for simplicity, react admin expects rejecteds promise instead of unhandled expections, so you must handle errors.

How to stop the user from entering the duplicate record on default save

I have a custom module where there is an email field. Now i want to stop the user if the email is already in the database.
I want to stop the user on save button and show the error. Like when a required field goes empty.
I tried to get some help but was not able to understand it.
Note: I realized after posting this that you are using suitecrm which this answer will not be applicable toward but I will leave it in case anyone using Sugar has this question.
There are a couple of ways to accomplish this so I'll do my best to walk through them in the order I would recommend. This would apply if you are using a version of Sugar post 7.0.0.
1) The first route is to manually create an email address relationship. This approach would use the out of box features which will ensure your system only keeps track of a single email address. If that would work for your needs, you can review this cookbook article and let me know if you have any questions:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_the_Email_Field_to_a_Bean/
2) The second approach, where you are using a custom field, is to use field validation. Documentation on field validation can be found here:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/index.html
The code example I would focus on is:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/#Method_1_Extending_the_RecordView_and_CreateView_Controllers
For your example, I would imagine you would do something like this:
Create a language key for your error message:
./custom/Extension/application/Ext/Language/en_us.error_email_exists_message.php
<?php
$app_strings['ERROR_EMAIL_EXISTS_MESSAGE'] = 'This email already exists.';
Create a custom controller for the record creation (you may also want to do this in your record.js):
./custom/modules//clients/base/views/create/create.js
({
extendsFrom: 'RecordView',
initialize: function (options) {
this._super('initialize', [options]);
//reference your language key here
app.error.errorName2Keys['email_exists'] = 'ERROR_EMAIL_EXISTS_MESSAGE';
//add validation tasks
this.model.addValidationTask('check_email', _.bind(this._doValidateEmail, this));
},
_doValidateEmail: function(fields, errors, callback) {
var emailAddress = this.model.get('your_email_field');
//this may take some time so lets give the user an alert message
app.alert.show('email-check', {
level: 'process',
title: 'Checking for existing email address...'
});
//make an api call to a custom (or stock) endpoint of your choosing to see if the email exists
app.api.call('read', app.api.buildURL("your_custom_endpoint/"+emailAddress), {}, {
success: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//analyze your response here
if (response == '<email exists>') {
errors['your_email_field'] = errors['your_email_field'] || {};
errors['your_email_field'].email_exists = true;
}
callback(null, fields, errors);
}, this),
error: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//throw an error alert
app.alert.show('email-check-error', {
level: 'error',
messages: "There was an error!",
autoClose: false
});
callback(null, fields, errors);
})
});
},
})
Obviously, this isn't a fully working example but it should get you most of the way there. Hope this helps!

Double registration form in moodle

I'm editing a site based on moodle, and i need to create a double registration form. The first is already set (for schools), i need to create another one for private user. What would be the best way to do it?
Would be worth to copy the main signup files (signup.php and signup_form.php) and then make changes there?
Really thanks
I think the best solution would be to create a new authentication plugin.
https://docs.moodle.org/dev/Authentication_plugins
Maybe copy the code from here /auth/email into /auth/newname - replacing email with newname in the code.
Possibly extend the class? so something like this in /auth/newname/auth.php
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/auth/email/auth.php');
class auth_plugin_newname extends auth_plugin_email {
...
function can_signup() {
return true;
}
...
Then copy /login/signup_form.php into /auth/newname/signup_form.php
The next bit I'm not too sure about but you will probably need to modify /login/signup.php
Around the lines
if (empty($CFG->registerauth)) {
print_error('notlocalisederrormessage', 'error', '', 'Sorry, you may not use this page.');
}
$authplugin = get_auth_plugin($CFG->registerauth);
Change to
if (optional_param('newname', false, PARAM_BOOL)) {
$authplugin = get_auth_plugin('newname');
} else {
if (empty($CFG->registerauth)) {
print_error('notlocalisederrormessage', 'error', '', 'Sorry, you may not use this page.');
}
$authplugin = get_auth_plugin($CFG->registerauth);
}
Then for private registrations use
http://www.yoursite.com/login/signup.php?newname=1
Replace 'newname' with the name of your new authentication plugin.

Interaction between two forms in a single controller

I'm trying to work with two forms in a single controller in Symfony2. The page is displaying a list of e-mail addresses with checkboxes to select them.
The first form is a research form and the second is used to remove e-mail addresses. There is also a pagination in my page.
My problem is that I can't remove an e-mail address with a research when the e-mail address is not displayed in the first page.
public function emailsAction(Request $request, $paginationParams)
{
$searchForm = $this->createForm(new SearchFormType(), null, array());
$searchForm->handleRequest($request);
if ($searchForm->isValid()) {
// FETCH E-MAILS WITH SEARCH
} else{
// FETCH E-MAILS WITHOUT SEARCH
}
// here I slice the result depending on the pagination params
$removeForm = $this->createForm(new RemoveFormType(), null, array(
'emails' => $emails
));
$removeForm->handleRequest($request);
if ($removeForm->isValid())
{
$formData = $removeForm->getData();
// here I remove the e-mails
}
...
$params['remove_form'] = $manageSubscribersForm->createView();
$params['search_form'] = $searchAbonneActuForm->createView();
return $this->renderView('my_template.html.twig', $params);
}
If I understand it correctly, the problem is that my removeForm is created with the spliced array and without the search applied when handling the removeForm.
When I search for a name, say johnsmith, it displays me on page 1, one result which is johnsmith#email.com.
If johnsmith#email.com is on page 2 without search, the removeForm handling my request is created with a spliced array not containing johnsmith, so the removeForm is not considered valid.
How should I do to create my removeForm, taking account of the search done before when submitting the removeForm? Or maybe I'm doing this wrong ?
I'm not a native english speaker so if anything is not clear, feel free to ask.
You can use a hidden field with the current page index, that will help you make your search again.
Or you can use an event listener to modify the form field before the submission for the validation.

How to validate and handle a form in Express (NodeJS)

Is there a preferred form handling and validation library for Express?
I'm really looking for a similar level of abstraction as is found in Django forms - i.e. validation and error reporting in the template.
If the same validation could be used on the client side, that would be great.
Has anyone used, or written, anything good?
It looks like there's a module for this located at https://github.com/caolan/forms. I've never used it, but it seems fairly full featured.
This also looks viable and is still being developed: https://github.com/ctavan/express-validator
Here's an example of validating a form submission (login post request):
exports.login.post = function(req, res){
req.assert('username', 'Enter username').notEmpty();
req.assert('password', 'Enter password').notEmpty();
res.locals.err = req.validationErrors(true);
if ( res.locals.err ) {
if ( req.xhr ) {
res.send(401, { err: res.locals.err });
} else {
res.render('login', { err: res.locals.err });
}
return;
}
//authenticate user, data is valid
};