Pages

Thursday, April 14, 2011

Logic Hooks: OnDemand Installations

Source: photosteve101/Flickr
Say that you developed a cool logic hook and are ready to put it into use on your production instance of SugarCRM. However, you are faced with the challenge of the production instance being hosted on the SugarCRM OnDemand platform. 

For those of you that are new to the world of logic hooks, the OnDemand environment presents a unique challenge in that in order for one to make use of logic hooks in general, one has place the logic hook files in specific sub-folders within the folder containing your SugarCRM installation. You would not have access to said folders for OnDemand installations. Thus, our challenge.

So how do we solve this problem?

Fortunately, we can leverage one of built-in features of SugarCRM to bypass the issue. Using the Module Loader tool, we can install or uninstall the logic hook at will.

But to do this, we must first create a Module Install package. Let us take a look at how we would prepare it for the purposes of installing the proper casing logic hook described in a previous post of mine.

From this point forward, it is assumed that you have already created the files corresponding with that logic hook and we will focus exclusively on the process required to install it via the Module Loader and in turn, apply them to an OnDemand instance.

To prepare the install package, you will first need to create a manifest.php file. This is a text file containing instructions that tell SugarCRM to perform specific tasks. For our needs, we need to instruct it to copy the code executed by the logic hook and also create the logic hook instruction file.

Below are the contents of the manifest.php file we will use:

<?php
/*************************************
Project: Logic Hooks Manifest
Original Dev: Angel Magaña, April 2011
@2009-2011 Angel Magaña
cheleguanaco[at]cheleguanaco.com

Desc: Manifest file for installing logic hook

The contents of this file are governed by the GNU General Public License (GPL).
A copy of said license is available here: http://www.gnu.org/copyleft/gpl.html
This code is provided AS IS and WITHOUT WARRANTY OF ANY KIND.
*************************************/

global $sugar_config;

$upload_dir = $sugar_config['upload_dir'];
$manifest = array(
'acceptable_sugar_versions' => array(
'regex_matches' => array(
0 => '6\.*'
),
),
'acceptable_sugar_flavors' => array(
0 => 'CE',
1 => 'PRO',
2 => 'ENT',
), 
'name' => 'Sample Logic Hook',
'description' => 'Logic Hook installation package.',
'is_uninstallable' => true,
'author' => 'Angel Magaña',
'published_date' => 'April 15, 2011',
'version' => '1.0.0',
'type' => 'module',
);
$installdefs = array(
'id' => 'CG_LogicHook',
'mkdir' => array(
array('path' => 'custom/modules/Contacts'),
), 
'copy' => array(
array(
'from' => '<basepath>/NewFiles/proper_test.php',
'to'   => 'custom/modules/Contacts/proper_test.php',
),
),
'logic_hooks' => array(
array(
'module' => 'Contacts',
'hook' => 'before_save',
'order' => 96,
'description' => 'Proper Casing',
'file' => 'custom/modules/Contacts/proper_test.php',
'class' => 'ProperText',
'function' => 'convertToProper',
),
),
);
?>

Now we need to create the actual installer package. This is a simple archive file (zip) containing the manifest.php file, along with the file containing the code executed by the logic hook. Note that we do not actually need to include or create a logic_hooks.php file. The logic_hooks section within the manifest.php file will create it for us upon installation.

To create the install package:
  1. Create a new folder named InstallerTemp
  2. Within InstallerTemp, create another new folder named NewFiles
  3. Place the file proper_test.php in the NewFiles folder
  4. Navigate one level up, to the InstallerTemp folder
  5. Save the manifest.php file to the InstallerTemp folder
Lastly, create the zip archive file.  If you are a Windows user, simply select the manifest.php file and the NewFiles folder, right-click and choose Send To > Compressed (zipped) Folder. We will assume the resulting file is named MyInstallPackage.zip

It is important that the resulting zip archive reflects a structure similar to the following:

MyInstallPackage.zip
|
|__ manifest.php (file)
|
|__ NewFiles (folder)
      |
      |__ proper_test.php (file)

If the structure does not match, the Module Installer will fail, usually with an error indicating that the manifest file could not be found.

Assuming everything is in order, you can proceed to install it by accessing SugarCRM and selecting Admin > Module Installer, browsing to and uploading MyInstallPackage.zip and clicking Install

Once the installation completes, your logic hook is ready for use!

14 comments:

  1. Hi Angel,

    Trying to use this on Sugar 5.5.4 and found that the line
    $upload_dir = $sugar_config['uploads_dir']; should be
    $upload_dir = $sugar_config['upload_dir'];

    Thanks!

    ReplyDelete
  2. You are right. That's a typo on my part. I'll correct it.

    Thanks for bringing it to my attention.

    ReplyDelete
  3. Angel, muchisimas gracias.Hacia mucho que intentaba (luchaba,ja) con logic_hook y es la primera vez que logro verlo funcionar despues de muchas frustraciones.
    Aprovecho para preguntarte. Mi idea es utilizarlo para validar algunos campos personalizados antes de salvar un registro de un modulo personalizado; ¿estoy en el camino correcto? ¿logic_hook es la opcion que me conviene? Si existiera alguna información o ejemplo te agradeceria me lo comentes. Mucha gracias por todo. Abrazo

    ReplyDelete
  4. @htony22:

    Me alegra que le pude ayudar.

    Con respecto a su pregunta, depende. Digamos, via un logic hook lo es posible validar algun dato y si no esta correcto, se puede borrar. Por ejemplo, si tiene un campo cual se le exige que incluya la letra 'A' dentro del valor, lo puede verificar via un logic hook y luego borrar o reemplazar el valor con otro al momento que el usuario intente grabar el registro.

    Ahora, la pregunta mas importante es que si desea interactuar con el usuario durante este proceso para avisarle del problema. En este caso, un logic hook no es la solucion adecuada porque no son disenados para interactuar con la interfaz. Asi que no pudiera mostrar un popup por ejemplo para decirle al usuario que tiene que corregir la informacion. Eso es me mejor hecho via javascript personalizado insertada en una vista de editar personalizada.

    ReplyDelete
  5. Since 6.3, there's another way of installing logic hooks in modules - via Ext framework. See here http://developers.sugarcrm.com/wordpress/2011/11/23/what%E2%80%99s-new-in-sugar-6-3-ext-framework-enhancements/
    This works with modules of course too - just make the module to install the file into proper Ext directory.

    ReplyDelete
  6. @php100:

    Indeed, although the technique doesn't address the core issue discussed in this post, which is to figure out a way to install logic hooks without having access to the instance's file system.

    ReplyDelete
  7. Hi Angel,
    very nice post!

    Bye,
    Antonio M.

    ReplyDelete
  8. hi angel,
    how i will do this in manifest.php
    if i have a general hook and hooks.php file place under cutom/modules
    and contest are
    $hook_version = 1;
    $hook_array = Array();
    $hook_array['before_save'] = Array();
    $hook_array['before_save'][] = Array(1, 'Google Sync', 'custom/include/Google/google_hook.php','GoogleHook', 'geventHandler');

    and google_hook.php file contents are
    class GoogleHook{
    function geventHandler($bean, $event){
    if( $bean->module_dir== 'Meetings' || $bean->module_dir== 'Calls' || $bean->module_dir== 'Tasks' )
    {
    //some code here
    }
    }
    }

    ReplyDelete
    Replies
    1. I am not sure how one would create a manifest for a general hook. The example above uses features of the manifest that seem to require a module name. I suppose you can try it without a module name value being specified, but I don't know if that'll work.

      Assuming it doesn't, one solution would be to simply use the copy feature and copy the two files into the corresponding directories.

      Delete
  9. How can I remove a logic hook that is no longer needed?

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Where do you get the base path to replace in a hosted configuration?

    ReplyDelete
    Replies
    1. I don't understand the question. The base path is a reference to the structure of the zip file's contents, not the Sugar instance.

      Delete
  12. Hola Angel, me estoy volviendo loca con algo, donde puedo modificar las horas del calendario de sugarcrm, es decir quiero agregar mas horas en la lista despegable y corregir los value que van por dejabo en las opciones de la lista

    ReplyDelete

Your comments, feedback and suggestions are welcome, but please refrain from using offensive language and/or berating others. Thank you in advance.