Sunday 19 June 2016

Visualforce - create an event record using a custom button and visualforce page

visual force page to create event record

requires
visualforce page
controller class
button

visualforce page

<apex:page standardController="Event" extensions="macalendarentry" showheader="false" sidebar="false">
<apex:form >
<apex:pageblock title="MArket Appraisal Calendar Entry" mode="edit">
 <apex:pageBlockButtons location="top">
 <apex:commandButton action="{!save}" value="Save"/>


 </apex:pageBlockButtons>


<apex:pageBlockSection title="Calendar Details" columns="4" >


<apex:inputfield value="{!Event.Ownerid}" >
</apex:inputfield>



<apex:inputfield value="{!Event.Subject}" >
</apex:inputfield>

<apex:inputfield value="{!Event.WhatId}" >
</apex:inputfield>

<apex:inputfield value="{!Event.Type}" >
</apex:inputfield>

<apex:inputfield value="{!Event.StartDateTime}" >
</apex:inputfield>

<apex:inputfield value="{!Event.EndDateTime}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Event_Status__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Cancellation_Reason__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>

</apex:pageBlockSection>


<apex:pageBlockSection title="Other Information" columns="4">
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>
</apex:pageBlockSection>

<apex:pageBlockSection title="Description Information" columns="4">
<apex:inputfield value="{!Event.Description}" >
</apex:inputfield>
</apex:pageBlockSection>
</apex:pageblock>


</apex:form>
</apex:page>

controller
(to prepopulate values in edit screen)
public class macalendarentry {
   public event event{get;set;}
    public macalendarentry(ApexPages.StandardController stdController){

        if(event == null) event = new Event();
        event.ownerid = ApexPages.currentPage().getParameters().get('ownerID');
        event.whatid = ApexPages.currentPage().getParameters().get('whatid');
     
    }
}

button
execute javascript/onclick javascript
window.open('/apex/ADD2Calendar?whatid={!Easy_Opportunity__c.Id}&ownerid={!$User.Id}', '_blank', 'toolbar=0,location=0,menubar=0');

Thursday 16 June 2016

Visualforce - google maps

visual force - google maps visualforce page

fields required:

formula text
Coordinates__c
text( GPS_Coordinates__Latitude__s )&" "&Text(GPS_Coordinates__Longitude__s )

geolocation
GPS_Coordinates__c
decimal 7 places

visualforce page

<apex:page standardController="pba__Property__c">

<head>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

  var myOptions = {
  draggable: false,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControl: false
  }

  var map;
  var marker;

  var geocoder = new google.maps.Geocoder();

 
   var address = "{!pba__Property__c.Coordinates__c}";

 var infowindow = new google.maps.InfoWindow({
    content: "<b>{!pba__Property__c.pba__Address_pb__c}</b><br>{!pba__Property__c.pba__City_pb__c}<br>{!pba__Property__c.State__c}, {!pba__Property__c.pba__PostalCode_pb__c}<br>{!pba__Property__c.Country__c}"
  });

 

   geocoder.geocode( { address: address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);

        //center map
        map.setCenter(results[0].geometry.location);

        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "Property"
        });

        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition());
        });

      }

    } else {
      $('#map').css({'height' : '25px'});
      $('#map').html("Oops! Property's  address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });

  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }

});
</script>

<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:250px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:page>
                                     



Sunday 12 June 2016

Apex - maps sets and lists - data collections

lists - orders index numbers starting with 0, 1, 2, 3,........

List<string> ListOfCities = new List<string>();

List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'}();

List<account> AccountToDelete = new List<account> ();//This will be null

List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>();

String [] ListOfStates = new List<string>();

Below are some most frequently used methods.

size()
add()
get()
clear()
set()

//Initialize the List
List<string> ListOfStatesMethod = new List<string>();

//This statement would give null as output in Debug logs
System.debug('Value of List'+ ListOfStatesMethod);

//Add element to the list using add method
ListOfStatesMethod.add('New York');
ListOfStatesMethod.add('Ohio');

//This statement would give New York and Ohio as output in Debug logs
System.debug('Value of List with new States'+ ListOfStatesMethod);

//Get the element at the index 0
String StateAtFirstPosition = ListOfStatesMethod.get(0);

//This statement would give New York as output in Debug log
System.debug('Value of List at First Position'+ StateAtFirstPosition);

//set the element at 1 position
ListOfStatesMethod.set(0, 'LA');

//This statement would give output in Debug log
System.debug('Value of List with element set at First Position'+ ListOfStatesMethod[0]);

//Remove all the elements in List
ListOfStatesMethod.clear();

//This statement would give output in Debug log
System.debug('Value of List'+ ListOfStatesMethod);

sets - unorderd and unique

Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
System.debug('Value of ProductSet'+ProductSet);

//Adds an element to the set
//Define set if not defined previously
Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};
ProductSet.add('HCL');
System.debug('Set with New Value '+ProductSet);

//Removes an element from set
ProductSet.remove('HCL');
System.debug('Set with removed value  '+ProductSet);

//Check whether set contains the particular element or not and returns true or false
ProductSet.contains('HCL');
System.debug('Value of Set with all values '+ProductSet);

maps -unordered- case sensitive -  key value pair

//Initialize the Map
Map<string, string> ProductCodeToProductName = new Map<string, string> {'1000'=>'HCL', '1001'=>'H2SO4'};

//This statement would give as output as key value pair in Debug log
System.debug('value of ProductCodeToProductName'+ProductCodeToProductName);

// Define a new map
Map<string, string> ProductCodeToProductName = new Map<string, string>();

// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value
ProductCodeToProductName.put('1002', 'Acetone');

// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value
ProductCodeToProductName.put('1003', 'Ketone');

// Assert that the map contains a specified key and respective value
System.assert(ProductCodeToProductName.containsKey('1002'));
System.debug('If output is true then Map contains the key and output is :'+ProductCodeToProductName.containsKey('1002'));

// Retrieves a value, given a particular key
String value = ProductCodeToProductName.get('1002');
System.debug('Value at the Specified key using get function: '+value);

// Return a set that contains all of the keys in the map
Set SetOfKeys = ProductCodeToProductName.keySet();
System.debug('Value of Set with Keys '+SetOfKeys);

Apex - Variables and data types – strings, dates, numbers, booleans, and sObjects

Variables and data types – strings, dates, numbers, booleans, and sObjects

Data types are simply the different types of variables you can have
String bestteam = 'PortsmouthFC';
Integer numberofpoints = 3;

Decimal goalratio = 0.9;
Boolean winner = true;
Date next match = Date.today().addDays(30);

DateTime now = DateTime.now();
Contact me = [SELECT FirstName, LastName 
                 FROM Contact 
                 WHERE Email = 'iain.banks@email.com'

                 LIMIT 1];
Strings are simply text variables
Integers and decimals are used in number, currency, and percentage fields in Salesforce. Integers are for number fields without any decimal places.
Booleans are just either true or false. They’re used with checkboxes in Salesforce.

Apex - basic trigger and unit test explained

Apex - basic trigger and its unit test explained


Basic Trigger

// trigger name "addcompanyname" on "user" (sobject)
trigger addcompanyname on User (before insert) {

//for every user in trigger.new do whats in the bracket (known as loop)
    for (User thisuser : Trigger.new) {
//companyname field   is apre ltd  (is possible to add more values)           
        thisuser.companyname = 'aspre ltd';          
    }
}


notes:
trigger - starting point for all triggers

addcompanyname - name of trigger can be anything

user - sobject  for a full list of standard salesforce objects and for a full list of object refeence

before insert - trigger will fire before record inserted/created in database for list of trigger operations

thisuser - variable that represent each specific user in the loop as it iterates one by one across all users in the list trigger.new

trigger.new -returns a list of the new versions of the sObject recordsthat are captured in trigger. this list only available in insert/update triggers and record can only be changed in before triggers for list of trigger context variables

Unit Test for basic trigger
every trigger requires a unit test to push code from sandbox to production -Salesforce requires at least 75% of your code to be “tested” before deploying

tests what the code should do

//all tests start with @isTest 
@isTest
//this line defines the class method access and name (for tests below will never chnge)
public class test_addcompanyname
    static testMethod void insertNewUser() {
     
// how to instantiate new user
       User userToCreate = new User();
     
       // create all mandatory fields
       userToCreate.FirstName = 'Iain';
       userToCreate.LastName  = 'Banks';
       userToCreate.Email     = 'iain.banks@email.com';
       userToCreate.Username  = 'iain.banks@email.com.sandbox';
       userToCreate.Alias     = 'ilearnapex';
       userToCreate.ProfileId = '00ei0000000rTfp';
       userToCreate.TimeZoneSidKey    = 'America/Denver';
       userToCreate.LocaleSidKey      = 'en_US';
       userToCreate.EmailEncodingKey  = 'UTF-8';
       userToCreate.LanguageLocaleKey = 'en_US';

       // we explicitly insert our user into our Salesforce database using this DML code otherwise it will not eneter the dsatabase
       insert userToCreate;
    }
}

notes

@isTest – this tells Salesforce we’re writing test code

test_addcompanyname - name of test class

testMethod – this tells Salesforce once again that we’re doing a test

insertNewUser – the name we gave our test method.

User – the API name of any Salesforce sObject, in this case, the standard User object.

userToCreate – the variable we named to store our user record.

’00ei0000000rTfp’ – this is the ID of the profile we’ll give to our user. Note that your org will have different IDs. 15-digit record IDs can be found in the URL of any record. Like text, IDs need to be wrapped in single quotes.

insert – the DML statement to “create” a record in an org. The record only exists in our code until we save it using DML.