How to add custom validation to form fields in SugarCRM CE and SuiteCRM

I had a requirement to add custom form validation to a couple of custom fields in the meetings module.  The requirement was as follows:

When a Meeting is marked as ‘Held’ the Objective Result and Follow Up fields will be compulsory.

A quick google search revealed that as usual there are many ways to this in sugar so I opted for the one which seemed to be keeping within the sugar architecture the most. This was a post in the sugarcrm forums by eggsurplus which could be quickly adapted to suit my requirement.

I Added the following to the JavaScript section in custom/modules/Meetings/metadata/editviewdefs.php:

function checkStatusOption(M){
	if(M.options[M.selectedIndex].value == "Held") {
        	setFieldRequired("objective_result_c", true, "Objective Result is required for held status");
                setFieldRequired("follow_up_c", true, "Follow Up is required for held status");
        }
	else {
		 //no longer required
		 setFieldRequired("objective_result_c", false);
                 setFieldRequired("follow_up_c", false);
        }
}

function setFieldRequired(fieldName, req, msgStr){
	if(!msgStr){ msgStr = fieldName; }
	        for(var i = 0; i < validate["EditView"].length; i++){
                     if(validate["EditView"][i][nameIndex] == fieldName) {
                         validate["EditView"][i][msgIndex] = msgStr;
                         validate["EditView"][i][requiredIndex] = req;
                         break;
                       }
                  }
 }  

Note that to be compatible with the smarty template you have to replace all the { and } with {ldelim} and {rdelim} in the above code.

And then in the same file I added the checkStatusOption function to the onchange event of the status field:

               array (
                'name' => 'status',
                'displayParams' =>
                   array (
                    'javascript' => 'onchange="checkStatusOption(this)"',
                ),
              ),

Now when editing a meeting in sugar and the ‘Status’ drop down is set to ‘held’ the custom fields I added ‘Objective Result’ and ‘Follow Up’ are automatically added to the required fields.

This code can be easily adapted for use with any standard module and field in sugar.

Thanks eggsurplus!!

Edit:

One cavieat with this is that the validation wont work until the held status is changed therefore we need to add another snippet of JavaScript to view. This will ensure that when editing records that already have their status set to held the validation will still work. This snippet also has to be included after the rest of the page has been loaded.

First we add a new view:

custom/modules/Calls/views/view.edit.php

And then add the snippet after the rest of the page has loaded by calling the parent display function

    class CallsViewEdit extends ViewEdit
    {
 
     public function display(){
 
        parent::display();

        echo '<script type="text/javascript">
             var current_status = document.getElementById("status");
                if(current_status.value == "Held"){
                    checkStatusOption(current_status);
                }
             </script>';
     }
 
}

Further Edit:

Just to expand on this article here is an example of how to add your own custom validation Callback for specified fields in SugarCRM CE or SuiteCRM.

You can add validation to a form in SuiteCRM and SugarCRM CE by using the following call:

addToValidateCallback(formname, field_id, type, required, msg, callback)

In this example we will add a basic USA style phone number validation.

$(function()//using jquery
{
//phone number validation
    addToValidateCallback(
        'EditView', // Form Name
        'phone_office', // field name
        'text', // Field type
        false, // Is required
        "Phone Number Invalid", // Message
        function() { // Callback
            var is_valid = false;
            if(checkPhoneNumber($('#phone_office'))) {
                is_valid = true;
            }
            return is_valid;
        });
});

The callback function must return true if field is valid, otherwise it should return false::

 //generic US Phone number format check e.g: 222-055-9034
function checkPhoneNumber(m){
    var phoneNo = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

    if(m.val() != '') {
        if(m.val().match(phoneNo)) {
            return true;
        }
        return false;
    }
}   
Andy
About

Software Developer from Falkirk, Central Scotland.

Posted in SugarCRM development and customisation, Uncategorised
7 comments on “How to add custom validation to form fields in SugarCRM CE and SuiteCRM
  1. Gayon Clarke says:

    this did not work for me. I am Trying to validate that the value the user enter is in the database. I also tried creating a custom js file and adding the the following to the custom/modules//metadata/editviewdefs.php file
    ‘includes’=> array( array(‘file’=>’custom/modules/Contacts/customJavascript.js’)),

    array (
    0 =>
    array(
    ‘customCode’ =>
    ”,
    ),
    1 =>
    array(
    ‘customCode’ =>

    )
    ), .
    Then did a rebuild.

    But nothing happened on the sugar edit form. I am lost.
    I don’t know much javascript but followed the instruction i google but it does not work.
    Please help.

  2. Andy Andy says:

    Are you getting any Javascript errors showing up?

    Also if you are not developer and dont know much JavaScript this will be hard to get right.

  3. Artur Nurja says:

    It worked for me, but I am having to use it also in quickcreatedefs.php. When creating from the subpanel in another module, the files are not made required based on the condition.

    Can you suggest please?

  4. Hello Andy, I’ve been trying to figure out how to work your validation method.

    So how would I use it for this use case?

    Apartment Numbers can be in the Format of 1-9, up to 4 digits long, and can but not always with a block number attached. So for example a valid option is either apartment 324 or 26C (26th apartment in Block C).

    Or is it better for me in this case to put it as simply a validation from 1-9 up to 4 digit length and then add a new optional row of block letter?

  5. Indrasinh says:

    It works for me!! Really Nice Job!!

  6. Shiela says:

    Hi Andy. Thanks for this! I followed your article.
    I created fields Username and Password with validations in Accounts module. However the validations i created works only when editing the Account record. So when I create and save, validations aren’t working.. Any ideas why?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>