Thursday, June 30, 2016

APEX: Compare Old and New Values in a Trigger

// Inside your trigger handler
public static void onBeforeUpdate()
{
    try
    {
       for(Account acct : Trigger.new)
       {
           Account oldAccount = Trigger.oldMap.get(acct.Id);
    
          if(oldAccount.FirstName != acct.FirstName)
          {
               // Value Changed 
          }
       }
    }
   catch(Exception ex)
   {
       system.debug(ex.getMessage() + '  ' + ex.getStackTraceString()); 
   }
}

Monday, June 27, 2016

SUGAR CRM 7: Bulkified POST Service using a custom API

1. Please take a look at the previous Post: http://programmersrealm.blogspot.com/2016/06/sugar-crm-7-creating-custom-api.html

2. Change reqType to 'POST'

3. Change path to array("Accounts", "PostExample")

4. Change method to 'MyPost'

5. Create mehtod MyPost()
public function MyPost($api, $args) 
{
    if (empty($args)) 
    {        
      return false; 
    } 
    $results = array(); 
    foreach ($args as $module => $records) 
    {        
      if (is_array($records)) 
      { 
        foreach ($records as $fieldsArray) 
        {                
          $sugarBean = 
           $this->create($module, $fieldsArray);                
          $results[$module][] = $sugarBean->id; 
        } 
      } 
    } 
    return $results; 
}

private function create($module, $fieldsArray) 
{    
    $sugarBean = BeanFactory::newBean($module);
    if (is_null($sugarBean)) 
    {        
      return null; 
    }    
    foreach ($fieldsArray as $field => $data) 
    {        
      $sugarBean->$field = $data; 
    }    
    $sugarBean->save(); 
    return $sugarBean; 
}

6. Add your url to Postman with the new endpoint (i.e. http://<my path>/rest/v10/Accounts/PostExample) with POST as the service

7. Add Authorization Token to Postman (if noauthorizationrequired is set to true, there's no need to add a token)

8. Create JSON data and put it under Body in Postman
{
"Accounts":
    [
        {
            "id" : "edf5e66e-6a2a-ccb3-d0bc-577142ee65ca",
            "name":"Testing10",
            "billing_address_city" : "ELP"
        },
        {
            "id" : "682d8dce-d397-85ce-7cc3-57714287c485",
            "name":"Testing3",
            "billing_address_city" : "PHX"
            
        },
        {
            "id" : "7de85759-0203-7a1c-240e-57714241b289",
            "name":"Testing2",
            "billing_address_city" : "LA"
            
        }
    ]
}

SUGAR CRM 7: Creating a Custom API

1. Add your php class under custom/modules/<module>/clients/base/api for specific module extensions or clients/base/api for custom api calls

2. Override registerApiRest() and add your API customization.
public function registerApiRest() 
{   
    return array(       
           'MyGet' => array(           
              'reqType' => 'GET',
              'path' => array('Accounts', 'GetExample'),
              'pathVars' => array('', ''),           
              'method' => 'MyGet',           
              'shortHelp' => 'An Example of a GET endpoint',
              'longHelp' => '',        )
    );
}
 
3. Add your MyGet method
public function MyGet($api, $args){
    return "Hello World!";}
 
4. Final Code
<?php
if(!defined('sugarEntry') ||
!sugarEntry) die('Not A Valid Entry Point');

class MyEndpointsApi extends SugarApi
{
   public function registerApiRest()
   {
     return array(            
       'MyGet' => array(                
         'reqType' => 'GET',                
         'path' => array('Accounts', 'GetExample'),                
         'pathVars' => array('', ''),                
         'method' => 'MyGet',                
         'shortHelp' => 'An Example of a GET endpoint',                
         'longHelp' => '',
       )
     );
   }
 
   public function MyGet($api, $args)
   {return "Hello World!";}

5. Test your API call (I suggest POSTMAN for Chrome)
    

Friday, June 24, 2016

SUGAR CRM 7: Updating Model inside Ajax

var self = this;
// more logic here
$.ajax({
    beforeSend: function (request) {
        request.setRequestHeader("OAuth-Token", your token);
    },
    type: "PUT",
    data: JSON.stringify({"status": "Closed"}),
    dataType: "json",
    url: 'your url',
    success: function (data)
    {
        // more logic here
        self.model.set('status', 'Closed');
    }
}); 

jQuery AJAX: HTTP API Requests requiring OAuth Token

$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("OAuth-Token", your token);
    },
    type: "PUT",
    data: JSON.stringify({
        "status": "Closed"
    }),
    dataType: "json",
    url: 'your url',
    success: function(data) {
     // your logic here
    }
});

Friday, June 3, 2016

PHP: External Service Sends JSON Format to your API Method

If you have an external service sending information over to your PHP server as JSON or XML, you can capture the response as follows:

$postResult = file_get_contents('php://input');
$payload = json_decode($postResult, true);

PHP: XML File Reading using Simple XML

The simplest solution is to load the file and process the xml nodes as follows:

$xml = simplexml_load_file('myfile.xml');

$node1 = $xml->child1;

$node2 = $xml->child2;


However, in some instances the resulting xml is either blank or empty. In this case, we need to call the following method:

$xml = simplexml_load_file('myfile.xml');

echo $xml->asXML();


If none of the above steps work, we need to create a Simple XML Element as follows:


$content = file_get_contents($fileName);

$xml = new SimpleXMLElement($content);
$node1 = $xml->child1;

If you still have issues after all this, typecast the node values:

$node1 = (string)$xml->child1;


Sample XML: myfile.xml
<root>

   <child1>Child 1</child1>

   <child2>Child 2</child2>

</root>

Wednesday, June 1, 2016

GIT: HTTPS Repository Error

If you get the following error while pushing to a specific remote repository: The requests URL returned error: 401 Unauthorized while accessing https:...

Try adding the repository as follows first then push:

git remote add origin https://yourname@bitbucket.org/yourorg/yourrepository
......
git push -u origin

GIT: Remove Origin from Git Repository

In case you accidentally added an incorrect remote or you want to switch from ssh to https or vice versa, you can try the following command:

git remote rm origin

GIT: Configure Global User

In case you need to set up both the global user name and email in git, you need to provide the following commands:

git config --global user.name "Your Name"

git config --global user.email you@example.com

Please be careful when executing the above commands as these will override the current settings.

In case you want to commit/push as a different user without affecting the global settings, you can try:

git commit --amend --author='Your Name <you@example.com>'

For more information on git Commands: https://git-scm.com/docs

GIT: From an Existing Project

cd /path/to/my/repogit remote add origin git@bitbucket.org:myorg/myrepository.git(or git remote add origin https://bitbucket.org/myorg/myrepository) in case you use httpsgit push -u origin --all # pushes up the repo and its refs for the first timegit push origin --tags # pushes up any tags
More info from BitBucket

GIT: Creating a GIT Repository From Scratch

Set up your local directory

mkdir /path/to/your/projectcd /path/to/your/projectgit initgit remote add origin git@bitbucket.org:myorg/myrepository.git (or git remote add origin https://bitbucket.org/myorg/myrepository) in case you use https

Create your first file, commit, and push

echo "My Text" >> contributors.txtgit add contributors.txtgit commit -m 'Initial commit with contributors'git push -u origin master

You can also find this information when creating a new repository from BitBucket [1].[1] https://bitbucket.org