Popup alert does not display when triggered by logic hook

Hello everyone,

I'm trying to do a simple thing in sugar : check if the assigned user already have a meeting when saving a new one on the same date/hours.

So, i've got a before_save logic hook which check if the assigned user already have meetings. It works well.

Now, i want to throw an alert to the user, it seems that the Confirm one is good : if confirmed, save the meeting. If cancelled, then go back to it and change the date.

I wrote this inside my logic hook, if the user is not available, then $isavailable is false.

if ($isavailable == false) { // User already has a meeting at this time => error    
 echo "<script type='text/javascript'>
 app.alert.show('message-id', {
level: 'confirmation',
messages: 'Confirm?',
autoClose: false,
onConfirm: function(){
alert('Confirmed!');
},
onCancel: function(){
alert('Cancelled!');
}
});</script>";

}
                                                                  
But the alert does not show.
And how can i make the cancel => go back to the current meeting. and the confirm => save the current meeting??

Can you please help me on that?

Thanks.
Gaëlle
  • logic hooks do not have ability to return javascript back to the browser.
  • @Jeff : Oh! That's why! Thank you Jeff! Do you have any idea on how i could achieve this? Because i need the user to stay on the meeting to complete it after, i can't just quit the edition (or the user will have to rewrite every info)
    Maybe overriding the view, with an Ajax call, which lead to my php hours verification, and then display an alert or nothing?
  • Problem SOLVED!
    So, for those who were wondering : Jeff is totally right, and well, it's good to know : You can't return Javascript to the browser by logic hook (using eg
    echo "<script>alert('ETC');</script>" ;
    won't work).

    But i've achieved a way to do this : include a js file to your view, trigger an event (like a click), do an ajax call to a php file (personnally, i pass by an entryPoint) which has the sql queries/function for you. echo your datas and then manage the datas back in the ajax, like if success : alert(data);


  • Hi!!

    I need to implement the same functionality. Could you put the code you used? I'm new to SugarCRM and I'm a little lost. 
    Thanks in advance.
  • It was made for a BWC module (Meetings), so i'm quite sure it won't work for modules totally in 7 version.

    In custom/modules/<YourModule> create a folder named whatever you want. i named mine "js". Then, inside this folder, create a js file named whatever you want (i named mine "customjs.js").

    So, in custom/modules/<YOURMODULE>/js/customjs.js , you will have this code :

    function check_form(formname) {
    /* custom function overriding check_form to check the form then save */
    /* launching standard fields validation*/
    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;
    }
    }
    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:"<YOURSUGARROOT>/index.php?entryPoint=validateAvailability",
    async : false,   type: "POST",
       data: { userid : user_id, beanid : bean_id, date : date_start, h : duration_h, m : duration_m},
       success: function(data){
        if(data > 0){//remember : data is the count of rows aka number of meetings other than this one which are set this same day this same time.
         alert("L'utilisateur "+user_name+" already has other Meeting!");
        }
       },
       error: function(){
        //console.log(data);
        console.log("SQL Failure");
       }
      });
      return ajax.responseText;
    }
    }
         
    You will have to create your custom php file :
    custom/modules/<YOURMODULE>/customPHP/validateAvailability.php
    (name the folder and the file whatever you want) :

    <?php//GFE 24/06/2014
    if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
    global $sugar_config, $dbhost, $db_user_name, $db_password, $db_name, $dbport; 
    global $db;
      //this one is for validate user's availability
      $user_id = $_POST['userid'];
      $date_start = $_POST['date'];
      $duration_h = $_POST['h'];
      $duration_m = $_POST['m'];
      $bean_id = $_POST['beanid'];
      $isavailable = checkUserIsAvailable($user_id,$bean_id,$date_start,$duration_h,$duration_m);
      $GLOBALS['log']->info("assigned user available for current meeting? ".$isavailable);
      //on envoie le résultat à l'ajax
      echo $isavailable;
      function checkUserIsAvailable($user_id, $bean_id = null, $date_start, $duration_hours, $duration_minutes)
      {
    $query = '';
    //All your code/request to your database to know if the user is available
    $result = $db->query($query);//exécution de la requête 
    return $db->getRowCount($result);// get the number of the rows 
    }
         
    In my case, the number of rows in my query's result gives me the number of meetings the assigned user does have on this day at this time.

    Finally, you'll have to create a custom entryPoint into custom/Extension/application/Ext/EntryPointRegistry/customEntryPoint.php (name this file whatever you want).
    Inside of this, you'll have this php code :

    <?php
    $entry_point_registry['validateAvailability'] = array(    'file' => 'custom/modules/<YOURMODULE>/customPHP/validateAvailability.php',
        'auth' => true);
    ?>

    Now, include the customjs.js in your metadata file :
    custom/modules/<YOURMODULE>/metadata/editviewdefs.php

    <?php$viewdefs['Meetings'] = 
    array (
      'EditView' => 
      array (
        'templateMeta' => 
        array (
          'includes' => 
          array (
            0 => 
            array (
              'file' => 'custom/modules/<YOURMODULE>/js/customjs.js',
            ),
          ),
          'maxColumns' => '2',
          'form' => 
          array (
    //all your metadata already existing

    Run a Quick Repair and Rebuild and you'll be fine.

  • Hi GaelleFernandez,
          Thanks Jeff Bickart. I was also trying to show prompt box using javascript. But now I knew that it is not possible using logic hook. So, Can I get any help here.
          Scenario is, when user log in to the system, after  loading the homepage, I want a prompt box to show. So, I am confused  here, please guide me soon. Thank you.


  • Here is a way I found from joining other's comment and Published data.

    Add a bean factory for User to Logichook

    $user = BeanFactory::getBean('Users', $current_user->id);

    Add Function:

        function NotifyOnError($focus,$message, $usr ){
            throw new SugarApiExceptionInvalidParameter($message);
            $notifyBean = BeanFactory::getBean('Notifications');
            $notifyBean->assigned_user_id = $usr;
            $notifyBean->severity = 'warning'; // Check notifications_severity_list for available option
            $notifyBean->parent_type = $focus->opportunities;
            $notifyBean->parent_id = $focus->id;
            $notifyBean->created_by = $GLOBALS['current_user']->id;
            $notifyBean->name = translate('LBL_KEEP_ATTENTION', $focus->module_name);
            $notifyBean->save();
            return true;
        }

    Add Call to Error control

    $rtnerr = $this->NotifyOnError($this, 'OOPS - Something Bad Happened - Have an Admin check the log', $user->id);


    Bill Lefkoski

  • You can override save onclick action by applying your condition first and than return (return check_form) function.
  • Hi, Gaelle Fernandez

    I want to do same solution in Sugarcrm 9.x EP version how i can do.? any idea !!

    Thanks