Search code examples
phpajaxvalidationsugarcrmsuitecrm

SugarCRM 6.5 CE how to properly validate form data using ajax?


I need to check the field phone_mobile for duplicate into the database. If a field value is not a duplicate then continue saving. And if such a phone already exists in the database, then show the alert message and stop the process(form submission).

My actions:

In the file ./modules/Contacts/metadata/editviewdefs.php connected custom js file:

$viewdefs['Contacts']['EditView'] = array(
'templateMeta' => array(
    'includes' => array (
            array (
                'file' => 'custom/include/javascript/custom_contact.js'
            ),
        ),
    'form'=>array(
    ...

Works great.

In custom_contact.js file overload check_form(formname) function:

function check_form(formname)
{
    if(formname === 'correct')
    {
       // This part does not work right for me
        var _form = document.getElementById('EditView');
        _form.action.value='Save'; 
        SUGAR.ajaxUI.submitForm(_form);
        return false;
    }
    if(formname === 'EditView')
    {
        // Ajax query works perfectly
        $.ajax({
            url : '/',
            method : 'POST',
            data : {},// some data
            success : function(data) {
                data = JSON.parse(data);
                if(!data.success)
                {
                    var text = 'The phone already exists';
                    return false;
                }
                check_form('correct');
            }
        });
    }
    return false;
}

But the if(formname === 'correct') ... block does not work correctly.

I need to stop the work of the form_save and include when necessary.

Please help to solve the problem correctly.I'm new to SugarCRM.


Solution

  • This is something related to javsacrip/jquery error handling and you can find many logics on google as well.

    Try following code:

    // DOM Ready 
    $('input#PHONE_FIELD_ID').on('change', function () {      
        handlePhoneValidation();
        return false;
    });
    
     var clickAttr = $("#SAVE_BUTTON_ID").attr("onclick"); 
     $("#SAVE_BUTTON_ID").attr("onclick","return handlePhoneValidation(); "+clickAttr);
    
    
    function handlePhoneValidation(){
    
        clear_all_errors();
    
        var node = $('input#PHONE_FIELD_ID');
            current_val = node.val();
    
       /*
        * Your validation will go here
        * if condition fail then return false otherwise true 
       */
    
        return false;
    }