overriding Save button : after ajax validation save editView form

Hello everybody!!

You may have noticed that this thread is a duplicate one of Sugar 7 bwc overriding Save button to add ajax but i don't know why but the forum did a mess with it and repeated everything several times (Hey @Sugar Staff, i didn't find somewhere to talk about it).

So, here is again my problem, with better construction and further precision.

What i want :

I want sugar to check if the assigned user already have meetings planned WHEN the current user clicks on Save button.

What i did :
I've overrided the Save button by doing this custom code under custom/modules/Meetings/editviewdefs.php :

array (            'customCode' => '<input title="{$APP.LBL_SAVE_BUTTON_TITLE}" id ="SAVE_HEADER" accessKey="{$APP.LBL_SAVE_BUTTON_KEY}" class="button primary" onclick="SUGAR.meetings.fill_invitees();return validationPlanification();document.EditView.action.value=\'Save\'; document.EditView.return_action.value=\'DetailView\'; {if isset($smarty.request.isDuplicate) && $smarty.request.isDuplicate eq "true"}document.EditView.return_id.value=\'\'; {/if} formSubmitCheck();" type="button" name="button" value="{$APP.LBL_SAVE_BUTTON_LABEL}">',
          ),

you can see it is calling a js function, which is below and is defined under customjs.js (this last is included in editviewdefs too)

function validationPlanification(){ if($("#status").val()=="Planned"){
  var user_id = $("#assigned_user_id").val();
  var user_name = $("#assigned_user_name").val();
 
  var duration_h = $("#duration_hours").val();
  var duration_m = $("#duration_minutes").val();
  var date_start = $("#date_start_date").val()+" "+$("#date_start_hours").val()+":"+$("#date_start_minutes").val();
 
  var href = $(".moduleTitle").find('h2 a').attr('href');//trouver le lien du record
  if (href != undefined){
   var idx = href.indexOf('record');//trouver où se situe le mot "record"
   var bean_id = href.substr(idx+7);//chopper l'id
  }else{
   var bean_id = '';
  }

  var ajax = $.ajax({
   url: "http://&lt;Sugarbase&gt;/index.php?entryPoint=validateAvailability",
   type: "POST",
   data: { userid : user_id, beanid : bean_id, date : date_start, h : duration_h, m : duration_m},
   success: function(data){
    //console.log(data);
    if (data === "false"){
     console.log("nok");
     alert("L'utilisateur "+user_name+" a déjà d'autres rendez-vous de prévus sur cette plage horaire!");
     //on ne peut pas sauvegarder
     return false;
    }
    if (data === "true"){
     console.log('ok');
     //return true;
     return check_form('EditView');
    }
   },
   error: function(){
    //console.log(data);
    console.log("SQL Failure");
   }
  });
}
}

you can see this function is doing an ajax call to a custom entrypoint. this works (tested it by setting some log at the beginning of the entry point) this entrypoint is querying the base to know if the assigned user already have a meeting set. It returns $is_available = true if the user does not have a meeting. else, it returns$is_available = false.
This works, i've set some console.log(data) when the ajax call is a success.

Then, you can see i'm testing the data retrieved. if data is true, so Sugar must save the current editview form. and if it is false, i think i'll throw an alert.

What is not working :
Everything works fine until i try to save the editview form : my return check_form('EditView') does not work, neither a simple "return true".

Do you have any idea on that?

Thanks a lot for the long reading, and your time.
Gaëlle


  • Don't bother with the  $.getScript

    Just try

    if(typeof(siw)!='undefined'&&siw&&typeof(siw.selectingSomething)!='undefined'&&siw.selectingSomething)return false;
          if ( validate_form(formname) == false ) return false;

    It should work
  • infortunately, it does not work..

    function check_form(formname) {/* custom function to check the form then save */

       /* launching standrad fields validation*/
       if(typeof(siw)!='undefined'&&siw&&typeof(siw.selectingSomething)!='undefined'&&siw.selectingSomething)return false;
          if ( validate_form(formname) == false ) return false;

       /*launching assigned_user availability validation*/
       if (validationPlanification() > 0){
            return false;
       }else{ 
            return true;
       }
    }

    what is juste the "siw" alone between two &&s? is it to check if siw exists?
  • not sure what the siw stuff does just copied it fro sugar

    try just putting 

    if(typeof(siw)!='undefined'&&siw&&typeof(siw.selectingSomething)!='undefined'&&siw.selectingSomething)return false;
          if ( validate_form(formname) == false ) return false;

    return false //stop it saving 

    then see if there are javascript errors
  • i've edit earlier, but maybe the forum didn't save it correctly : 

    THANK YOU A LOT @Mike Solomon, you're the hero of this friday!

    I got it, i'll just edit the code solution for anybody with the same problem.

    i've seen the check_form function, just copied what was inside (maybe by copying dumbly from the forum, i made some mistake, do'nt know), and that was all.

    Many thanks again!!

    I wish you a wonderful sunny week end, full of BBQs and laughs, because you fully deserve it :)
  • this is my best try to redefine the function, is not complete yet!

      this.findRequired = function(callback) {
                    $(".validation-message").remove()
                    requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
                    var mybool = false;
                    var ids_tmp = [];
                    $("#EditView_tabs div").each(function(index) {
                        $(this).find('table tbody tr td span').each(function(index2) {
                            if ($(this).hasClass("required")) {
                                var ids = $(this).parent().attr('id');
                                ids = ids.replace("_label", "");                                             
                                //console.log(ids);
                                if ($("#" + ids).val() === '') {
                                    if( $.inArray(ids, ids_tmp) < 0){
                                         add_error_style("EditView",ids,requiredTxt,true);   
                                    }
                                        ids_tmp.push(ids);                               
                                   
                                    console.log(ids_tmp); 
                                    mybool = true;
                                                                 
                                }                       
                            }
                        });

                    });
                    callback(mybool);
                }



  • Hi GaelleFernandez,

    Why are you doing an synchronous request when you can do an async one instead?
    It would be a hassle for your end user and in some ways degrade your user experience.
    Also if memory serves me right if async is set to false then this freezes the screen until the result comes back. So here is my attempt at revising your code, just outlined the methods not copy all your code:

    var isProcessing = false;
    function check_form(formname){
        if(isProcessing === true){
           alert('form validation still in progress');        //replace with a custom alert you want
        }
        //do your validation here
        validationPlanification();
       return false;
    }
    function validationPlanification()
    {      isProcessing = true;
          //do some more validation
          // show a loading message here
         $.ajax({
            url: "your url",
            type: POST | GET,
            data: {some data here}
            success: function(data){             isProcessing = false;
                //remove loading message
                if(data == true){
                      submitForm();
                }
            },
            error: function(error)
             {                  isProcessing = false;
                    //display error message
             }
         })
    }
    function submitForm()
    {
            //use jquery to submit your form here
    }

    this is just a suggestion for when using ajax asynchronously.

    Hope this helps
  • Hello Gaelle, 

    I followed your instructions, but I thing I missed something. I don't understand this : 

    In fact, before launching your own custom validation function, you have to copy/paste the snippet of code present into the check_form(form_name) function under the file ./include/javascript/sugar_3.js.

  • Hello EL HADJI DEM

    Well, what i meant by "before launching your own custom validation function, you have to copy/paste the snippet of code present into the check_form(form_name) function under the file ./include/javascript/sugar_3.js."

    is that you have to copy/paste the code i've wrote into the check_form function into the file sugar_3.js.
    So, you'll have to write

    function check_form(formname) {
    /* OLD VERSION : not making required fields required states. */
       if (validationPlanification() > 0){
            return false;
        }else{
             return true;
       }
    /* END OLD VERSION*/
    /*NEW VERSION so cool!*/
        if (typeof(siw) != 'undefined' && siw  && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
           return false;
        return validate_form(formname, '');

        /*launching assigned_user availability validation*/
        if (validationPlanification() > 0){
             return false;
        }else{ 
             return true;
         }
    /*END NEW VERSION*/
    }

    under the file ./include/javascript/sugar_3.js.

    But because this work was made some time ago, i can't advise you to use this code.

    Also check what EvilPeri EvilPeri wrote below, i think it would be a better practice than mine.

    Hope this helps !

    Have a nice day.

    Gaëlle