• Prosenjit Sarkar 7
  • SMARTIE
  • 638 Points
  • Member since 2015
  • 4x Certified Salesforce Developer
  • Cognizant Technology Solutions


  • Chatter
    Feed
  • 20
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 14
    Questions
  • 175
    Replies
@isTest
private class tprotest {


     @isTest static void testCallout() {   
                          
           Account acc = new Account(name = 'test', ia_crm__Sync_With_Intacct__c = true ,ia_crm__IntacctID__c = 'C111',Phone = '33333344444', 
 billingstreet = '4th avenue', billingcity = 'tampa',billingstate = 'FL',  billingcountry = 'United States', BillingPostalCode = '11001', Description = 'javascript :: null');
 insert acc;

          Opportunity op = new Opportunity(
          Name = 'Prasadam',                       
          Accountid = acc.id,                      
          IsPrivate = false,                       
          Amount = 1000.00,
          StageName = 'Contract Signed',                
          CloseDate = Date.parse('09/09/2019'),  
          Probability = 100  ,      
          Card_Holder_s_Name__c =   'rajni bala',
          Credit_Card_Number__c = '5446886522351236',
         Credit_Card_Expiration_Date__c = '07/2019',    
          Routing_Number__c = '123556985',
          Accounting_Number__c = '445669',
          TPro_Success__c = 'true',
          TPro_AuthID__c = null,
          TPro_CC_StoredAccountID__c = null,
          Billing_First_Name__c = 'Anna',
          Billing_Last_Name__c ='Jordan',
          Billing_Contact_Email__c = 'anna@jumpcrew.com'
        //  test__c = 'C111'
          );
          
         insert op;


         
    }                  
            //op.Routing_Number__c = '552236996';
           // op.Credit_Card_Number__c= '5546886522351236';
          //  op.Account.Name = 'testacc';
    
 
                // Set mock callout class 
                  
   @isTest static void testCalloutt(){
   
   Opportunity opp = [Select Id, Name FROM Opportunity WHERE Name = 'Prasadam' Limit 1];
      
   Test.setMock(HttpCalloutMock.class, new MocktProOpportunity()); 
   
                 Test.startTest();
               new tproOpportunityTriggerHandler().sendCardToTPro(opp);
               tproOpportunityTriggerHandler.send(opp.Id);             
            
                Test.stopTest(); 
                opp = [SELECT Id,Accountid, Card_Holder_s_Name__c,Credit_Card_Number__c,Credit_Card_Expiration_Date__c,Account.ia_crm__IntacctID__c,  Account.Name, test__c,Billing_Contact_Email__c,
              Event_Code__c,Routing_Number__c,Accounting_Number__c,TPro_Success__c,TPro_AuthID__c,StageName ,TPro_CC_StoredAccountID__c
             FROM Opportunity where id =: opp.Id];
             
             System.assertEquals('Prasadam', opp.Name ); 
             System.assertEquals('Contract Signed', opp.StageName ); 
             
           
 
}
      
}
Problem is here...   Opportunity opp = [Select Id, Name FROM Opportunity WHERE Name = 'Prasadam' Limit 1];

2nd problem is : System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
Hi All
Anyone give any idea regarding on sorting the wrapper list.
I have combined task and event into a single list using the wrapper class. Using the list I am showing the information to the VF page. But I want to show the result descending order so that I want to sort the list.

Please, anyone, give an idea to resolve the issue.
Hi,

I am new to APEX and have modified a trigger to fit my needs, but don't know how to properly modify the test class.  Could someone please help?

APEX Trigger:
trigger JIRATrigger on JIRA__c (after insert, after update) {
    for (JIRA__c j : Trigger.new) {
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Bug') {
            JCFS.API.createJiraIssue('10103', '10103');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Story') {
            JCFS.API.createJiraIssue('10103', '10100');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Epic') {
            JCFS.API.createJiraIssue('10103', '10000');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Bug') {
            JCFS.API.createJiraIssue('10300', '10103');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Story') {
            JCFS.API.createJiraIssue('10300', '10100');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Epic') {
            JCFS.API.createJiraIssue('10300', '10000');
        }
        if (Trigger.isUpdate && Trigger.isAfter) {
            JCFS.API.pushUpdatesToJira();
        }
    }
}

Current APEX Class: (0% code coverage)
@isTest public class JIRATriggerTest {
    @isTest static void caseAfterInsertTest() {
        JCFS.JiraTriggerTestHelper.testAfterInsert('JIRA__c');
    }
    @isTest static void caseAfterUpdateTest() {
        JCFS.JiraTriggerTestHelper.testAfterUpdate('JIRA__c');
    }
}

 
public class EC_CaseDetailController {
public String currentRecordId {get;set;}
public String parameterValue {get;set;}
public Case ca{get;set;} 
    public EC_CaseDetailController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        ca = [select Casenumber,
              PRX_Entity__c,
              PRX_Type_of_request__c,
              Status, 
              CreatedDate,
              ClosedDate,
              PRX_Number_of_requests__c,
              PRX_Partner_Customer_name__c,
              ContactEmail,
              PRX_Name__c,
              PRX_Free_text_field__c,
              PRX_Mobile_number__c from Case where id =: currentRecordId ];
        parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
    }
Hi all,

I have below code. I want to show error on VF page when particular condition not met and records not found.I have added my code in try catch block and added apex:messages as well.
Please suggest me what is wrong.
The error should be displayed when combination of service family and sub service category is not found in database.
 
Class:


public with sharing class SurveyClass{

Public Account acc{get;set;}
Public Proposal_Form__c pfc;
Public Proposal_Form__c pfc1 {get;set;}
public ProposalFields__c pf {get;set;}
public List<String> fieldSet {get;set;}
Public ID rid;
private ApexPages.StandardController standardController;
    
public SurveyClass(ApexPages.StandardController controller) {
    this.standardController = standardController;
    pfc1 = new Proposal_Form__c();
  }

public void Selected(){
    system.debug(pfc1.Service_Family__c +'------------'+pfc1.Sub_Service_Category__c);
    
    try{
        pfc = [SELECT Fields_Associated__c FROM Proposal_Form__c where Service_Family__c =: pfc1.Service_Family__c and Sub_Service_Category__c =: pfc1.Sub_Service_Category__c LIMIT 1];
        
    } catch(Exception ex){
     ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'No such combination exists');
     ApexPages.addMessage(myMsg);
      
    }
     
    fieldSet = new List<String>();
    List<String> fields = new List<String>();
    if(pfc.Fields_Associated__c != null && pfc.Fields_Associated__c != ''){
        fields = String.valueof(pfc.Fields_Associated__c).split(',');
        system.debug('*********Fields******'+fields);
    }
    else{
        Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No questions to Display"'));
    
    }
    Map<String,String> labelMap = new Map<String,String>();
    labelMap = getLabel.retLabelMap('ProposalFields__c');
    system.debug(labelMap);
    system.debug(labelMap);
    for(String s : fields){
        fieldSet.add(labelMap.get(s));
        system.debug('********fieldset*******'+fieldSet);
    }
    
}
}


VF Page:;


<apex:page standardController="Account" extensions="SurveyClass" sidebar="false" showHeader="false" tabStyle="Account">

<apex:form >
<apex:pageMessages rendered="true"/>
<apex:pageBlock title="Client Survey Form"> 
<apex:pageBlockSection title="Service Requirements" >

<apex:inputField value="{!pfc1.Service_Family__c}"/>
 
<apex:pageblocksectionItem >
    <apex:outputLabel value="Sub Service Category"/>
    <apex:outputPanel >
        
            <apex:inputfield value="{!pfc1.Sub_Service_Category__c}">
                <apex:actionSupport event="onchange" action="{!Selected}" rerender="fieldst" />
                <apex:pageMessages rendered="true"/>
            </apex:inputField>
       
    </apex:outputPanel>
</apex:pageblocksectionItem>
</apex:pageBlockSection> 

<apex:pageblockSection title="Question Set" id="fieldst">
    <apex:repeat value="{!fieldSet}" var="f">
      <apex:inputField value="{!pf[f]}"/> 
    </apex:repeat>
</apex:pageblockSection>

<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Submit" action="{!Save}"/>
</apex:pageBlockButtons>



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


 
Hi, on my account object, I created a picklist field - testPicklist1__c. The picklist field has various values in it. One picklist value is "abc t" & its API name is "abc". I retrieved the Account object using ANT & tried to deploy to another Salesforce org using ANT. I got the below error message -:
User-added image
Error Message says -:  "Picklist value: abc t in picklist: testPicklist1__c not found". 

When I viewed the Account.object file I found that under "testPicklist1" field definition, the picklist value is shown with full name "abc" like this <fullName>abc</fullName> as shown below -:    
<fields>
        <fullName>testPicklist1__c</fullName>
        <externalId>false</externalId>
        <label>testPicklist1</label>
        <picklist>
            <picklistValues>
                <fullName>abc</fullName>
                <default>false</default>
            </picklistValues>  
        </picklist>
</fields>

Wheras in "AOC" record type definition under the enabled picklist value, this picklist is being referenced using "abc t" as the full name like this <fullName>abc t</fullName> as shown below -:
<recordTypes>
        <fullName>AOC</fullName>
        <active>true</active>
        <label>AOC</label>
       <picklistValues>
            <picklist>testPicklist1__c</picklist>
            <values>
                <fullName>abc t</fullName>
                <default>false</default>
            </values>
     </picklistValues>
</recordTypes>
Is this what causing the above error ? How can I remove this error & deploy successfully without manually doing changes ? Thanks in advance. 
 
Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Update failed. First exception on row 0 with id 0012800000vRs6sAAC; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Account Number is not numeric.: [AccountNumber]
I have 2 triggers calling 2 different handler classes on the same object . As part of best practise I want to call both the classes from a single trigger. I am not sure how to call them. Below are my two triggers.
 
trigger ShippingAddress on Shipping_Address__c (after delete, 
                             after insert,  
                             after undelete, 
                             after update, 
                             before delete, 
                             before insert, 
                             before update ) {
    try  
    {
        ITriggerHandler handler = new SingleTriggerHandler (
                                        new ShippingAddressTriggerHandler(),
                                        Trigger.isExecuting,
                                        Trigger.isInsert, 
                                        Trigger.isUpdate, 
                                        Trigger.isDelete, 
                                        Trigger.isBefore, 
                                        Trigger.isAfter, 
                                        Trigger.isUndelete, 
                                        Trigger.new, 
                                        Trigger.newMap, 
                                        Trigger.old, 
                                        Trigger.oldMap, 
                                        Trigger.size );
        handler.process(); 
    }
    catch (AbstractTriggerHandler.InvalidTriggerInvocationException itie)
    {
        SystemExceptionLogger.insertSystemExceptionLogEntry(
                                        itie, 
                                        'Shipping Address Application - Common Use', 
                                        'Shipping Address Trigger', 
                                        SystemExceptionLogger.EXCEPTION_LEVEL_INFO);
        
    }
    catch (Exception e)
    {
        SystemExceptionLogger.insertSystemExceptionLogEntry(
                                        e, 
                                        'Shipping Address Trigger Application - Common Use', 
                                        'Shipping Address Trigger', 
                                        SystemExceptionLogger.EXCEPTION_LEVEL_CRITICAL);
        throw e;
    }

}
Trigger 2
trigger StagingShippingAddress on Shipping_Address__c (after delete, 
                             after insert,  
                             after undelete, 
                             after update, 
                             before delete, 
                             before insert, 
                             before update ) {
    try  
    {
        ITriggerHandler handler = new SingleTriggerHandler (
                                        new StagingShippingTriggerHandler(),
                                        Trigger.isExecuting,
                                        Trigger.isInsert, 
                                        Trigger.isUpdate, 
                                        Trigger.isDelete, 
                                        Trigger.isBefore, 
                                        Trigger.isAfter, 
                                        Trigger.isUndelete, 
                                        Trigger.new, 
                                        Trigger.newMap, 
                                        Trigger.old, 
                                        Trigger.oldMap, 
                                        Trigger.size );
        handler.process(); 
    }
    catch (AbstractTriggerHandler.InvalidTriggerInvocationException itie)
    {        SystemExceptionLogger.insertSystemExceptionLogEntry(itie,'Shipping Address Application - Common Use','Shipping Address Trigger',SystemExceptionLogger.EXCEPTION_LEVEL_INFO);
        
    }
    catch (Exception e)
    {        SystemExceptionLogger.insertSystemExceptionLogEntry(e,'Shipping Address Trigger Application - Common Use','Shipping Address Trigger',SystemExceptionLogger.EXCEPTION_LEVEL_CRITICAL); throw e;
    }

}


 

Hi there,

Below is some code I have in a custom button to tick a checkbox that runs a workflow rule

It has worked for almost a year and has now jut stopped working and I don't know why.

It runs the alerts but doesn't check the faculty Trial request box anymore, any help appreciated.

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")}
var newRecords = [];
var c = new sforce.SObject("Lead");
console.log("{!Lead.Faculty_Trial_test__c}");
if
("{!Lead.Faculty_Trial_test__c}" == "no")
{
alert("You can only request a Faculty Trial to SRM, Business or SAGE Video products. Plesae make sure you have added at least one of these products to the related Opportunity.");
}
if("{!Lead.Department__c}" == "")
{
alert("You must add a Department to request a Faculty Trial.");
}
if
("{!Lead.Email}" == "")
{
alert("You must add an Email to request a Faculty Trial.");
}
else
{
c.id ="{!Lead.Id}";
c.Faculty_Trial_Request__c = false;
c.Faculty_Trial_Request__c = true;
newRecords.push(c);
result = sforce.connection.update(newRecords);
window.location.reload();}
Hello,

A user has access to a public groupe, but he is not able to Add or remove memberes in that groupe, hos is it possible to give him access.

thank for suggestion.

Hi all,

I have written a code to update all the siblings records and parent records of the record getting updated. I want to use MAP in below trigger if it is possible. I want to optimize it using MAP. Can anyone please help me? Thank you so much.

 

trigger Addressflag on Address__c (After update, After Insert) {
    if(Trigger.isUpdate || Trigger.isInsert){
    List<ID> ConIds = new List<ID>();
    Boolean needsUpdate = FALSE; 
    for (Address__c Adds: trigger.new)
    {
    ConIds.add(Adds.contact__c);
    }
    system.debug('parent con ids'+ConIds);
    contact con = [select id, checkbox__c, recordTypeId from contact where Id IN :conIds];
    List<Address__c> otherAlt = new List<Address__c>([select id, contact__c, checkbox__c, contact__r.recordTypeId from Address__c where contact__c in: conIDs]);
        for (Address__c adds: trigger.new)
        {
            for (integer i=0; i < otherAlt.size(); i++)
            {
                if ((otherAlt[i].contact__c==adds.contact__c) && (otherAlt[i].id != adds.id))
                {
                     otherAlt[i].checkbox__c = FALSE;
                     con.checkbox__c=FALSE;
                     needsUpdate = TRUE;
                }
            }
        }

        if(checkrecursive.runOnce())
        {
              if (needsUpdate)
              {
                  update otherAlt;
                  update con;
              }
        }
    }
 }
Contact has master detail relationship with address. What I am trying to do is whenever the checkbox on any of the address is checked I am unchecking the same checkbox from all other siblings and parent record. I am acheving it through above trigger but I am concerned about the time when 1000s f records will get inserted at same time.
Hi All
Here is my trigger to limit a user to create only 10 cases in a month,it is half working accordingly, but i would like to put the logic in the apex class which is currently in the trigger, more over my trigger is restricting the users to create cases when they exceeded specified limit but i am seeing the first line of error 'Invalid Date' which is unexpected along with the custom error message that i have written in the trigger.
User-added image
 
Trigger LimitNoOfCases on case(Before insert){
    If (Trigger.IsInsert){
    Integer MonthNumber = Date.Today().Month();
    Integer YearNumber = Date.Today().Year();
    Integer MaxCases = Integer.valueof(System.Label.MaxCasesLimit);//configured maximum number of cases per user by creating Custom label.
    Id Xuser = UserInfo.Getuserid();
    User Usr = [select name from user where id=:userinfo.getuserid()];
    List<Case> LstCase = [select id,CreatedById,CreatedDate from case where CALENDAR_YEAR(CreatedDate) =:YearNumber and CALENDAR_MONTH(CreatedDate)=:monthnumber and CreatedById=:UserInfo.GetUserId()];
 
    If (Lstcase.Size()>=MaxCases)         
   {   
      Trigger.New[0].addError('Dear user you have exceeded the maximum number of cases allowed this month.');
   }  
     
  }
}

 
  • June 15, 2016
  • Like
  • 0
I have written a test class for apex class.i got 89% but 'for loop' is not covered represented as below screenshot.how to achieve morethan 90%?can you anybody help me where iam missing exactly.
apex class:

public with sharing class Rfleet_Financial_Informations {
    //Variable Declaration Parts
    public List < RFLEET_Account_Protocol__c > contt {get;set;}
    public List < EditableContact > myAssociatedContact {get;set;}
    public Integer editableContactNumber {get;set;}
    public Boolean refreshPage {get;set;}
    public String protocolname {get;set;}
    public String id;
    //Constructor for invoking the Records from AccountProrocol Object
    public Rfleet_Financial_Informations(ApexPages.StandardController stdCtrl) {
            id = ApexPages.currentPage().getParameters().get('id');
            myAssociatedContact = new List < EditableContact > ();
            Integer counter = 0;
            RFLEET_Protocol__c conn = [select name from RFLEET_Protocol__c where id = : id];
            protocolname = conn.name;
            contt = [select Name,Rfleet_Billing_Account__r.Name, Rfleet_Id_Alcor__c, Rfleet_Billing_Account_Type__c, Rfleet_Billing_Account__r.Rfleet_Street_Number__c, Rfleet_Billing_Account__r.Rfleet_Country__c, Rfleet_Billing_Account__r.Rfleet_Zip_Code__c, Rfleet_Billing_Account__r.Rfleet_State_Province__c, Rfleet_Billing_Account__r.Rfleet_City__c, Rfleet_Billing_Account__r.Rfleet_Street_Name__c from RFLEET_Account_Protocol__c where Rfleet_Protocol__c = : id];
            for (RFLEET_Account_Protocol__c myContact: contt) {
                myAssociatedContact.add(new EditableContact(myContact, false, counter));
                counter++;
            }
        }
        // This method is used for deleting the Row
    public void deleteRowEditAction() {
        try {
            myAssociatedContact.get(editableContactNumber).editable = false;
            delete(myAssociatedContact.get(editableContactNumber).myContact);
        } catch (Exception e) {}
        refreshPage = true;
    }
    public class EditableContact {
        public RFLEET_Account_Protocol__c myContact {get;set;}
        public Boolean editable {get;set;}
        public Integer counterNumber {get;set;}
        public EditableContact(RFLEET_Account_Protocol__c myContact, Boolean editable, Integer counterNumber) {
            this.myContact = myContact;
            this.editable = editable;
            this.counterNumber = counterNumber;
        }
    }
}

test class:
@isTest
public class Rfleet_Financial_Informations_Test {
    static testMethod void financialtest() {
    Billing_Repository__c brc = new Billing_Repository__c(Name='frest',Rfleet_City__c='cger',Rfleet_Country__c='japan',Rfleet_Zip_Code__c='7854',CurrencyIsoCode='EUR');
        Account acc = new Account(Name = 'cooluma',montant__c=0.2);
        acc.Rfleet_Id_Alcor__c=brc.id;
        acc.Rfleet_Street_Name__c ='gff';
        acc.Rfleet_Street_Number__c ='232';
        acc.Rfleet_Country__c ='fdffd';
        acc.Rfleet_City__c ='cdfdf';
        acc.Rfleet_State_Province__c ='dfdf';
        acc.Rfleet_Zip_Code__c ='dfdfnhj';
    insert acc;
        acc.Name = 'vfggf';
        update acc;

        RFLEET_Protocol__c test = new RFLEET_Protocol__c(Name = 'prabu');
        insert test;
        test.Name = 'prabu';
        update test;
        RFLEET_Account_Protocol__c myContact = new RFLEET_Account_Protocol__c(Rfleet_Billing_Account__c = acc.Id, Rfleet_Billing_Account_Type__c = 'Vehicle', Rfleet_City__c =acc.Rfleet_City__c,Rfleet_Country__c =acc.Rfleet_Country__c, Rfleet_Id_Alcor__c = acc.Rfleet_Id_Alcor__c,
            Rfleet_Protocol__c = acc.Id, Rfleet_State_Province__c =acc.Rfleet_State_Province__c , Rfleet_Street_name__c =acc.Rfleet_Street_Name__c, Rfleet_Street_number__c = acc.Rfleet_Street_Number__c, Rfleet_Zip_code__c =acc.Rfleet_Zip_Code__c);


        string name = 'ListConditionCheck';
        Boolean editable;
        Integer counternumber;

        Rfleet_Financial_Informations.editableContact wra = new Rfleet_Financial_Informations.EditableContact(mycontact, editable, counterNumber);
        test = [select id, Name from RFLEET_Protocol__c LIMIT 1];
        PageReference vfpage = Page.Rfleet_Financial_Informations;
        System.test.SetCurrentpage(vfpage);
        Apexpages.currentPage().getparameters().put('id',test.id);
        Apexpages.StandardController sc = new Apexpages.StandardController(test);
        Rfleet_Financial_Informations fintest = new Rfleet_Financial_Informations(sc);
        fintest.deleteRowEditAction();
        fintest.id = acc.Id;
    }
   
}
screenshot:
not covered in test class
 
I've written a trigger that duplicates an opportunity when we change its status to "Closed-Won." The idea is that every time we close an opportunity, we want to create a follow-up opportunity for pursuing that client again. My trigger makes a clone of the opportunity, adds some new products and schedule items, sets the status to discovery, and a couple of other minor things. As of right now, the trigger doesn't actually copy any objects associated with opportunity. Ideally, if there's a way to do this, I want to copy all of the existing Contact Roles from the closed Opp to the new one. Here's my code...let me know if you have any questions about it or need to know anything about our setup. 

​Thanks! 

trigger Create_followup on Opportunity (before update, after insert) {

Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE Name = :'Ambition'];//Create an instance of the standard pricebook


if(Trigger.isUpdate){


List<Opportunity> listOppor = new List<Opportunity>();
for (Opportunity o: Trigger.new){

    if (o.StageName == 'Closed Won' && o.Stage_Change__c == false && o.Is_Clone__c == false){

        Opportunity oppNew = o.clone();
        oppNew.Name = oppNew.Name  + ' - Annual ' + o.CloseDate.year();
        
        if(o.Renewal_Date__c != null){
        oppNew.Renewal_Date__c = o.Renewal_Date__c.addYears(1);
        oppNew.CloseDate = o.Renewal_Date__c.addYears(1);}
        
        oppNew.StageName = 'Discovery';
        oppNew.Probability = 25;
       
        
        
        oppNew.Pricebook2Id = standardBook.Id;//associate the standard pricebook with this opportunity
        
        oppNew.Is_Clone__c = true;
        listOppor.add(oppNew);
        o.Stage_Change__c = true;
        
}

 
}//end of for loop

   if(listOppor.size() > 0){
 insert listOppor;       
        
}

}

if(trigger.isInsert){

try{
OpportunityLineItem[] lines = new OpportunityLineItem[0];
PricebookEntry entry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = 'ENTERPRISE_ANNUAL_UPFRONT'];
List<Event> eventList = new List<Event>();
//List<Note> noteList = new List<Note>();


for(Opportunity o: Trigger.new){
if(o.Is_Clone__c == true){

//noteList.add(new Note(ParentId=o.id,Title='Matt is the Apex_God',Body='Matt is the Apex_God',isPrivate=false));

lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=o.Id, UnitPrice=entry.UnitPrice, Quantity=1));

if(o.Renewal_Date__c != null){

DateTime myDateTime = o.Renewal_Date__c.addMonths(-10);
 

eventList.add(new Event(whatid=o.id,startdatetime=myDateTime,subject='Account Management Follow-Up', EndDateTime=myDateTime, IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(2),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(2), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(4),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(4), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(6),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(6), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(8),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(8), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(10),subject='Account Management Follow-Up', EndDateTime=myDateTime.addMonths(10), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(10),subject='Renewal',EndDateTime=myDateTime.addMonths(10), IsAllDayEvent=true));
eventList.add(new Event(whatid=o.id,startdatetime=myDateTime.addMonths(9),subject='Sales Contract Follow-Up',EndDateTime=myDateTime.addMonths(9), IsAllDayEvent=true));

}//end of if

}
}
insert lines;
insert eventList;
//insert noteList;

}
catch(Exception e){

}
}


}
I have a trigger that I created that is working fine, but when i try to deploy it to our production org, it will not allow me to and gives me a few errors on apex test classes that i know work fine. Any help as to why this trigger is making these test classes fail woud be greatly appreciated. The trigger and error information is below. Another issue is I seem to have a problem with these test classes in eclipse. Any test class that references a Case object has a red X near the case where there's a insert case with a message stating sytax error mismatched input expecting RCurly Bracket)). But these test worked fine in my older galilieo eclipse. I am using Eclipse IDE for Java Developers Version: Luna Service Release 1a (4.4.1)

Case Currency Trigger:
trigger Trigger_ChangeCaseCurrency on Case (before update) {
    Set<Id> accIds=new Set<Id>();
    for (Case cs: trigger.new){
        accIds.add(cs.AccountId);
    }
    Map<Id,Account> accMap=new Map<Id,Account>([SELECT id, OwnerId,currencyisocode,Shipping_Country__c FROM Account WHERE  Id IN :accIds]);
    for (Case cs : trigger.new){
        if(accMap.get(cs.AccountId).Shipping_Country__c == 'GBR' || accMap.get(cs.AccountId).Shipping_Country__c == 'IRL' ){
           //update currency from Account
            cs.currencyisocode=accMap.get(cs.AccountId).currencyisocode;
           //set the curreny to GBP
           cs.currencyisocode='GBP';
           cs.Reason='Other';
           
        }
    }
}

Test Classes:

Test_AssignWebCaseQueue
@isTest
private class Test_AssignWebCaseQueue {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        
        test.startTest();
        
        Account acc = new Account( Name ='Key West Services', Market_Segment__c='Finance Company', Customer_Type__c='Finance Company', Preferred_SP__c ='0017000000WitqP', Registered_for_Seminar__c=true );
      insert acc;
      
      acc.Name='Key West Services';
      acc.Market_Segment__c ='Finance Company';
      acc.Customer_Type__c='Finance Company';
      acc.Preferred_SP__c ='0017000000WitqP';
      update acc;
      
      Case cse = new Case( Status='Open', Origin='Parts Support - Web', Subject='Parts', Web_Case_Type__c='Part Support');
      insert cse;

      cse.Status = 'Open';
      cse.Origin = 'Parts Support - Web';
      cse.OwnerId='00G70000001JGIA';
      cse.Web_Case_Type__c='Part Support';
      update cse;
      
      cse.Status = 'Open';
      cse.Origin = 'Tech Support- Web';
      cse.OwnerId='00G70000001hJGH';
      cse.Web_Case_Type__c='Tech Support';
      update cse;

      test.stopTest();
    }
}

Test_CaseFileUpload
@isTest
public class Test_CaseFileUpload {

      static testMethod void testAttachments()
    {
        Case cse=new Case();
        insert cse;
        BL_CaseFileUpload controller=new BL_CaseFileUpload(new ApexPages.StandardController(cse));
 
        controller.fileName='Unit Test Attachment';
        controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:cse.id];
        System.assertEquals(1, attachments.size());
    }
}

Test_VFController_survey_oppsmyUnitTest

@isTest
private class Test_VFController_survey_opps {

    static testMethod void myUnitTest() {
        VFController_survey_opps sv = new VFController_survey_opps();
        sv.qte1 = 'Excellent';
        sv.qte2 = 'Excellent';
        sv.qte3 = 'Excellent';
        sv.qte4 = 'Excellent';
        sv.qte5 = 'Excellent';
        sv.qte6 = 'Excellent';
        sv.qte7 = 'Excellent';
        sv.qte8 = 'Excellent';
        sv.qte9 = 'Excellent';
        sv.qte10 = 'Excellent';
        sv.qte11 = 'Excellent';
        sv.qte12 = 'Excellent';
        sv.qte13 = 'Excellent';
        sv.qte14 = 'Excellent';       
        sv.company = 'Key West Services';
        sv.Address = '10 Trotter' ;
        sv.city = 'Milford' ;
        sv.Country = 'USA,CAN,MEX';
        sv.zip = '02703' ;
        sv.state= 'MA' ;
        sv.email = 'bpoliquin@cybexintl.com' ;
        sv.Phone = '508-533-4300' ;
        sv.Comments = 'Test Commment' ;
        sv.oppId = '123456' ;
        sv.survey = true;
        sv.caseid = '123456';
        sv.getItemc();
        sv.getItems();
        sv.getItems2();
        sv.getItems3();
        sv.getItemst();
        
       
       
               
        
        // insert a case
        Case cs = new Case();
        cs.Subject = 'test';
        cs.Reason = 'test reason';
       insert cs;
        //--
        
        sv.caseid = cs.id;    
               
        
         //insert account
        Account acc = new Account();
        acc.Name = 'Lorenco';
        acc.Market_Segment__c = 'Commercial';
        acc.Customer_Type__c = 'Hospitality';
        acc.Shipping_Country__c = 'USA';  
        
        
        insert acc;           
       
        
        //insert opportunity
        Opportunity opp = new Opportunity();
        opp.Name = 'Lorenco';
        
        opp.Market_Segment__c = 'Commercial';
        opp.Customer_Type__c = 'Hospitality';
        opp.Lead_Source_Detail__c = 'Trade Show';
        opp.Direction__c = 'Incoming';
        opp.StageName= 'In Progress';
        opp.Original_Created_Date__c = date.today();
        opp.CloseDate = date.today();
        opp.Survey_Returned__c = true;
       
        opp.Id = opp.id;
        insert opp;
        
         Boolean good = True;
        System.assert(good);
    }
}



 
  • June 25, 2015
  • Like
  • 0
I have a field called "Call_Count__c" which is a number field in Contact. I want that when some one logs a call and if the Subject Category is "Call" or "Update" the Call Count field should increase by 1. for eg if value in call count field is 3 it should become 1. Please help me with a trigger for this.
I'm working on a visual force page for a mobile app

Code from Controller (summarized to relevant parts):
global with sharing class DTCI_Remote_Methods_Ctrl {   
    public String attendeeId {get; set;}         
                           
    public DTCI_Remote_Methods_Ctrl (ApexPages.StandardSetController controller) {
        attendeeId = ApexPages.currentPage().getParameters().get('attendeePageId');          
    }


 @RemoteAction
        //Get attendee specified by attendeeId
        global static List<CnP_PaaS_EVT__Event_attendee_session__c> getconfirmedAttendee(string attendeeId){
           
            List<CnP_PaaS_EVT__Event_attendee_session__c> confirmedAttendee = [SELECT Id, Name, CnP_PaaS_EVT__First_name__c, CnP_PaaS_EVT__Last_name__c                                                                                                               
                                                                       FROM CnP_PaaS_EVT__Event_attendee_session__c                                                                            
                                                                       WHERE Id = :attendeeId       
                                                                           AND DTCI_Agreement_Active__c = TRUE
                                                                       ORDER BY Name                                                                                    
                                                                      ];
            return confirmedAttendee;                                
        }

Code from VF Page (summarized):

<apex:page standardController="CnP_PaaS_EVT__Event_attendee_session__c" extensions="DTCI_Remote_Methods_Ctrl" recordSetVar="attendees"
           docType="html-5.0" standardStylesheets="false" showheader="false" sidebar="false">

<script>    
    $j=jQuery.noConflict();  
    var attendeeJsId = '{!$CurrentPage.Parameters.attendeePageId}';

   DTCI_Remote_Methods_Ctrl.getconfirmedAttendee(attendeeJsId, function(result,event){
        if(result.length === 0){
            $j("#confirmedAttendeeId").append("No results<br />");
        }else 
                              
            $j("#confirmedAttendeeId").append("<title1>" + result.Name + "has checked in</title1>" + "<br/><br/>" );                                                                                                                                                                                                                                                                                
        
                    
    }, {escape:true});

Everything works great on the page with the exception of returning the value of result.Name, it simply says 'undefined'.

I think I just need a little syntax tweak, but for the life of me can't figure it out!

assistance much appreciated, Amanda 
I have two custom objects [access.log & trans.log] who receive daily updates [New Records] from an external system. After 31 days we don't need them anymore and we would like to delete them. Both objects have a date field on the record 'Log_date__c'.

I know that you can make a job that deletes these records on a daily basis.

My question;

- How do I write a code that deletes the right records? (Log_date__c older than 31 days)
- How/where do I put in SFDC? (Apex Class or Trigger! - Both!)

Are there any who can help me progress. In which case it will be my first code in SFDC.
Hi ,

I am working on salesforce standard email sending feature, which we used to find from Send Email button of Activity History related list of a detail page. I need to do some coputation after the email has sent. So, I need to capture the send email button's event any how. Is there any way to do this ?

Thanks in advance,
Prosenjit
How to get User Information in Lightning Component or Javascript Controller ?
How can I attach a visual workflow in a Lightning Component ?

Thanks
Prosenjit
How can I attach a visual workflow in a Lightning Component ?
Hi developers,

I have not found in Lightning Component Developers Guide that how to maintain FLS and Look up  in Lightning Components. Can you please suggest some thing ?
Recently Salesforce has enabled a feature to assign supported objects to a custom queue. I need to get the names (or API) of those supported objects from a queue Id through Apex and SOQL or Meta data. Any body had idea about that ? 
Hi Developers,

I want to start an open source project using Lightning Component. Any idea about how to start an open source project in salesforce and relate it to developer forum.

P.S. - If any idea or some requiements are in your mind please share with me for the project. 
We can get REST callouts from Workbench. I want to know how to call this REST callouts from apex, with a proper simple example.
Hi, I have seen a  BLOG: Introducing Trailhead Contest 2015 in Partners.Salesforce.com. Here is the link https://partners.salesforce.com/partnerNews?id=a033000000C8In9AAF According to this I have completed data security module for June 2015. I want to know that, how can I get the information about next challane . Any body have some idea ?
 
@isTest
private class tprotest {


     @isTest static void testCallout() {   
                          
           Account acc = new Account(name = 'test', ia_crm__Sync_With_Intacct__c = true ,ia_crm__IntacctID__c = 'C111',Phone = '33333344444', 
 billingstreet = '4th avenue', billingcity = 'tampa',billingstate = 'FL',  billingcountry = 'United States', BillingPostalCode = '11001', Description = 'javascript :: null');
 insert acc;

          Opportunity op = new Opportunity(
          Name = 'Prasadam',                       
          Accountid = acc.id,                      
          IsPrivate = false,                       
          Amount = 1000.00,
          StageName = 'Contract Signed',                
          CloseDate = Date.parse('09/09/2019'),  
          Probability = 100  ,      
          Card_Holder_s_Name__c =   'rajni bala',
          Credit_Card_Number__c = '5446886522351236',
         Credit_Card_Expiration_Date__c = '07/2019',    
          Routing_Number__c = '123556985',
          Accounting_Number__c = '445669',
          TPro_Success__c = 'true',
          TPro_AuthID__c = null,
          TPro_CC_StoredAccountID__c = null,
          Billing_First_Name__c = 'Anna',
          Billing_Last_Name__c ='Jordan',
          Billing_Contact_Email__c = 'anna@jumpcrew.com'
        //  test__c = 'C111'
          );
          
         insert op;


         
    }                  
            //op.Routing_Number__c = '552236996';
           // op.Credit_Card_Number__c= '5546886522351236';
          //  op.Account.Name = 'testacc';
    
 
                // Set mock callout class 
                  
   @isTest static void testCalloutt(){
   
   Opportunity opp = [Select Id, Name FROM Opportunity WHERE Name = 'Prasadam' Limit 1];
      
   Test.setMock(HttpCalloutMock.class, new MocktProOpportunity()); 
   
                 Test.startTest();
               new tproOpportunityTriggerHandler().sendCardToTPro(opp);
               tproOpportunityTriggerHandler.send(opp.Id);             
            
                Test.stopTest(); 
                opp = [SELECT Id,Accountid, Card_Holder_s_Name__c,Credit_Card_Number__c,Credit_Card_Expiration_Date__c,Account.ia_crm__IntacctID__c,  Account.Name, test__c,Billing_Contact_Email__c,
              Event_Code__c,Routing_Number__c,Accounting_Number__c,TPro_Success__c,TPro_AuthID__c,StageName ,TPro_CC_StoredAccountID__c
             FROM Opportunity where id =: opp.Id];
             
             System.assertEquals('Prasadam', opp.Name ); 
             System.assertEquals('Contract Signed', opp.StageName ); 
             
           
 
}
      
}
Problem is here...   Opportunity opp = [Select Id, Name FROM Opportunity WHERE Name = 'Prasadam' Limit 1];

2nd problem is : System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
Hi,

Bear with, I am new to visualforce ;-)

I have two custom objects - Purchase_Order__c, which has a child object called Items. They have a master detail relationship.

I have built a controller to create a PDF attachement and send an email, which works when using a very basic VF page for the PDF. I have now updated the VF page which involves displaying fields on from both Purchase Order and Items object - but when trying to run the process it gives the error of "SObject row was retrieved via SOQL without querying the requested field: Purchase_Order__c.Items__r"

Reading through the forums, it seems that I need to give access to these fields in the controller but I have no idea how.

A copy of my controller is below, any advice would be appreciated.


public class EmailSend {

    public EmailSend(ApexPages.StandardController controller) {

}

//Set variable values
public String EmailAddress {get;set;}
public String eSubject{get;set;}
public String eBody{get;set;}


//Start mail process and set criteria for PDF
public PageReference SendEmail() {

Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();
PageReference pdfGeneration=Page.Purchase_Order_PDF;
pdfGeneration.SetRedirect(true);
Blob b=pdfGeneration.getContent();

//Create attachment and set criteria
Messaging.EmailFileAttachment attach=new Messaging.EmailFileAttachment();
attach.setFileName('AttachmentEmailFile.pdf');
attach.setBody(b);

    email.SetSubject(eSubject);
    email.SetPlainTextBody(eBody);
    email.setToAddresses(new String[] { EmailAddress });
    email.setFileAttachments(new Messaging.EmailFileAttachment[] {attach});
    
    
//Now Sending the Email
Messaging.SendEmailResult[] r=Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    
    return null;
    
    }
    }

 
Hi everyone,
         
I have two objects Expense and Travel request and both are related by a lookup.
1.Travel Request has two fields like Travel_Purpose__c(Text Field) and Client_Visit__c(Look Up With Account).
2.Expense has two fields like Travel_Request__c(Look Up with Travel Request ) and Claim_Purpose__c(Text)
3.Now when i select Travel_Request__c then Claim_Purpose__c automatically in the same Editable page update like
              If(Travel_Request__c != Null)     
                    {
                         (Claim_Purpose__c= Travel_Purpose__c+Clent_Visit__c)
                     }

 
This is class
-------------------------------------------------------------------------
public class leaddup {

    public List<lead>ac{get;set;}
    public leaddup(){
    ac =[SELECT name,email FROM lead ];
    }
    public void getbyname(){
       ac=[SELECT name,count(Id) FROM lead GROUP BY name HAVING count(Id)>1];
    }
     public void getbyemail(){
       ac=[SELECT email,count(Id) FROM lead GROUP BY email HAVING count(Id)>1];
    }
}
--------------------------------------------------
This is vf
---------------------------------------------------------------------
<apex:page controller="leaddup">
    <apex:form >
        <apex:pageblock title="Duplicate lead">
            <apex:pageBlockButtons >
                <apex:commandButton value="based on name" action="{!getbyname}"/>
                <apex:commandButton value="based on email" action="{!getbyemail}"/>
            </apex:pageBlockButtons>
                    <apex:PageBlockTable value="{!ac}" var="a">
                        <apex:Column value="{!a.Name}"/>
                        <apex:Column value="{!a.email}"/> 
                    </apex:PageBlockTable>
               
        </apex:pageblock>
    </apex:form>
</apex:page>
trigger ownerupdate on Account (before insert) {
set<id> setAccOwners= new set<id>();

for(Account acc: Trigger.new){
setAccOwners.add(acc.ownerID);
}

Map<id,user> user_map = new map<id,user>([select name from user where id in : setAccOwners]);
for (Account acc: Trigger.new){
user u = user_map.get(acc.ownerID);
 acc.RecordOwner__c = u.name;
}
}
Hi All
Anyone give any idea regarding on sorting the wrapper list.
I have combined task and event into a single list using the wrapper class. Using the list I am showing the information to the VF page. But I want to show the result descending order so that I want to sort the list.

Please, anyone, give an idea to resolve the issue.
Hello all,

I am struggling to write a Test Class for the following trigger and static class that synchronizes portal users with contact record data:
trigger UpdateContactFromPortalUser on User (after update) {
    //We only want to run on the single item that the user edited 
    if (Trigger.new.size()==1) 
    { 
        User u =_ Trigger.new[0]; 
        //And only if it's a portal user 
        if (u.ContactId!=null) { 
            UpdateContactFromPortalUser.updateContacts(u.Id); 
        } 
    } 
}
global class UpdateContactFromPortalUser { 
    @future 
    public static void updateContacts(String userId) {
        User u = [select ContactId,Email,FirstName,LastName,Title
                    from User
                    where Id=:userId];

        if (u!=null && u.ContactId!=null) {
            Contact c = new Contact(Id=u.ContactId,Email=u.Email,FirstName=u.FirstName,LastName=u.LastName,Title=u.Title);
            update c; 
        }
    }
}
Here is my test class code:
 
@isTest
private class UpdateContactFromPortalUserTest {

static testMethod void testUpdateContacts() {

        Test.startTest(); 
        
        User u = [select Id,ContactId,FirstName from User where ContactId<>'' limit 1]; 

        u.FirstName='Bar';
         
        update u; 

        Test.stopTest(); 

        Contact c = [select FirstName from Contact where Id=:u.ContactId]; 
        System.assertEquals(c.FirstName,u.FirstName); 
    }
}

I am getting no code coverage when I runt the test.  Can someone help point me to what I am missing?

Thanks in advance for any help.

 
I need to write the test class for below @future method and i already tried it's covered 61% and tried a lot but i can't make it please help me with this am a newbie
Class:
global class UpdateFAPShare{

@future
public static void UdpateFAPSharesfromAccountshares()
{
Map<Id,List<AccountShare>> AccSharesUdpatedMap = new Map<ID,List<AccountShare>>();
Map<Id,List<Foreign_Account_Approval__share>> FAPSharesMap = new Map<ID,List<Foreign_Account_Approval__share>>();

Map<Id,List<Id>> FAPUserSharestoAdd = new Map<ID,List<Id>>();
Map<Id,List<Id>> FAPActiveUserSharestoAdd = new Map<ID,List<Id>>();

Set<Id> AccRelated = new Set<Id>();
Set<Id> FAPSRelated = new Set<Id>();

List<Foreign_Account_Approval__c> FAPs =[Select Id,Customer__c from Foreign_Account_Approval__c];

List<Foreign_Account_Approval__share> FAPShares4add = new List<Foreign_Account_Approval__share>();
List<Foreign_Account_Approval__share> FAPShares4Del = new List<Foreign_Account_Approval__share>();
for (Foreign_Account_Approval__c FAP : FAPs)
{
   AccRelated.add(FAP.Customer__c);
 
}
list<Foreign_Account_Approval__share> FAPShares =[Select Id, UserOrGroupId,AccessLevel,RowCause,ParentId from Foreign_Account_Approval__share where RowCause=: Schema.Foreign_Account_Approval__Share.RowCause.Derived_From_Customer__c];

for (AccountShare[] AccShare : [Select Id, UserOrGroupId, AccountAccessLevel, RowCause, AccountId From AccountShare where AccountId =:AccRelated and RowCause <> 'ImplicitParent']){
  System.debug('Account Shares:'+accshare);
  for(AccountShare acs :AccShare){

     If(AccSharesUdpatedMap.containskey(Acs.accountid))
      {
        AccSharesUdpatedMap.get(Acs.accountid).add(acs);
      }
     else
        AccSharesUdpatedMap.put(acs.accountid,new AccountShare[]{acs});
  }
}
System.debug('AccSharesYpdateMap'+  AccSharesUdpatedMap);
for(Foreign_Account_Approval__share fs : FAPShares)
{
   FAPSRelated.add(fs.Id);
   If(FAPSharesMap.containskey(fs.parentId))
      {
        FAPSharesMap.get(fs.parentId).add(fs);
        
      }
     else
        FAPSharesMap.put(fs.parentId,new Foreign_Account_Approval__share[]{fs});
 } 
for(Foreign_Account_Approval__c FAP : FAPs)
{
 for(AccountShare acs : AccSharesUdpatedMap.get(FAP.customer__c))
  {
      boolean exists =false;  
    if(FAPSharesMap.containskey(FAP.id))  
    {
      for(Foreign_Account_Approval__share fs : FAPSharesMap.get(FAP.id))
     {
      if(fs.UserOrGroupId == acs.UserOrGroupId)
             
             {
                exists = true;
                FAPSRelated.remove(fs.Id);  
             }
     }
    }
  if(!exists) 
      {    String UsrOrGroupId  = acs.UserOrGroupId;
           if(!UsrOrGroupId.startswith('005'))
           {
           Foreign_Account_Approval__Share fs = new Foreign_Account_Approval__Share();
           fs.ParentId = FAP.Id;
           fs.UserOrGroupId = acs.UserOrGroupId;
           fs.Rowcause = Schema.Foreign_Account_Approval__Share.RowCause.Derived_From_Customer__c;
           fs.AccessLevel ='Read';
           FAPShares4add.add(fS);
           }
            else
           {
            If(FAPUserSharestoAdd.containskey(acs.UserOrGroupId))
            {
              FAPUserSharestoAdd.get(acs.UserOrGroupId).add(FAP.Id);
        
            }
            else
              FAPUserSharestoAdd.put(acs.UserOrGroupId,new Id []{FAP.Id});         
           }

           
      }  

}
} 
if(FAPUSerSharestoAdd.keyset().size()>0)
{
for(User u :[Select Id,isActive from User where id =:FAPUSerSharestoAdd.keyset()])
{
if(u.isActive)
{
 for(Id FAPID : FAPUSerSharestoAdd.get(u.ID))
 {
           Foreign_Account_Approval__Share fs = new Foreign_Account_Approval__Share();
           fs.ParentId = FAPId;
           fs.UserOrGroupId = u.Id;
           fs.Rowcause = Schema.Foreign_Account_Approval__Share.RowCause.Derived_From_Customer__c;
           fs.AccessLevel ='Read';
           FAPShares4add.add(fS);

 }
}
}
}

If(FAPShares4add.size()>0)
insert FAPShares4add;
if(FAPSRelated.size()>0)
{
FAPShares4Del =[Select Id from Foreign_Account_Approval__share where id =: FAPSRelated ];
delete FAPShares4Del;
}
}
}

My Test CLass:
@isTest(SeeAllData=true)
public class Test_UpdateFAPShare {
    static testMethod void TestMethodUpdateFAPShare(){
       // Select users for the test.
      List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
      Id User1Id = users[0].Id;
      Id User2Id = users[1].Id;
      Profile p = [SELECT Id,Name FROM Profile WHERE Name = 'DB_Standard User_sales'];
      User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        System.runAs (thisUser) 
        {  
      Account acc = new Account(Name='TestAcc');
      insert Acc;
        //Create Parent Group
        Group grp = new Group();
        grp.name = Acc.Name;
        grp.Type = 'Regular';
        grp.DoesIncludeBosses=false;
        Insert grp; 
 
        //Create Group Member
        GroupMember grpMem1 = new GroupMember();
        grpMem1.UserOrGroupId = UserInfo.getUserId();
        grpMem1.GroupId = grp.Id;
        Insert grpMem1;
 
       
      
   //   Account acc2 = new Account(Name='TestAcc2',OwnerId=grpMem1.UserOrGroupId);
     // insert Acc2;
     Case c = new Case(OwnerId = grp.Id,Reason='Record Deletion',Status='Done',subject='Test');
      insert c;
      Foreign_Account_Approval__c FAP = new Foreign_Account_Approval__c();
      FAP.Customer__c=Acc.id;
     // FAP.Name=thisuser.Name;
      FAP.OwnerId = thisUser.Id;
      FAP.CA_Name__c=thisUser.Id;
      FAP.Status__c='Pending BSO Approval';
      insert FAP;
      FAP = [select Id, Name,Customer__c from Foreign_Account_Approval__c where id = : FAP.id];
            
        //Create Sub group
        Group subGrp  = new Group();
        subGrp.name = FAP.Name;
        subGrp.Type = 'Regular'; 
        Insert subGrp; 
 
        //Assign Role To Parent Group
        GroupMember grpMem2 = new GroupMember();
        grpMem2.UserOrGroupId = subGrp.Id;
        grpMem2.GroupId = grp.Id;
        Insert grpMem2;   
         // Create new sharing Account for the Account object Account.
      AccountShare accShr  = new AccountShare();
   
      // Set the ID of record being shared.
      accShr.AccountId = FAP.Customer__c;
        
      // Set the ID of user or group being granted access.
      accShr.UserOrGroupId = grpMem1.UserOrGroupId;
        
      // Set the access level.
      accShr.AccountAccessLevel = 'Read';
        
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      accShr.RowCause = Schema.AccountShare.RowCause.Manual;
      
        // Create new sharing object for the custom object Job.
      Foreign_Account_Approval__share fapShr  = new Foreign_Account_Approval__share();
   
      // Set the ID of record being shared.
      fapShr.ParentId = FAP.Id;
        
      // Set the ID of user or group being granted access.
      fapShr.UserOrGroupId = grpMem2.UserOrGroupId;
        
      // Set the access level.
      fapShr.AccessLevel = 'Read';
       
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      fapShr.RowCause = Schema.Foreign_Account_Approval__share.RowCause.Manual;
      UpdateFAPShare.UdpateFAPSharesfromAccountshares();
        }
        UpdateFAPShare.UdpateFAPSharesfromAccountshares();
     }
}

 
Hi,

I am new to APEX and have modified a trigger to fit my needs, but don't know how to properly modify the test class.  Could someone please help?

APEX Trigger:
trigger JIRATrigger on JIRA__c (after insert, after update) {
    for (JIRA__c j : Trigger.new) {
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Bug') {
            JCFS.API.createJiraIssue('10103', '10103');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Story') {
            JCFS.API.createJiraIssue('10103', '10100');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Arkham' && j.Issue_Type__c == 'Epic') {
            JCFS.API.createJiraIssue('10103', '10000');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Bug') {
            JCFS.API.createJiraIssue('10300', '10103');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Story') {
            JCFS.API.createJiraIssue('10300', '10100');
        }
        if (Trigger.isInsert && Trigger.isAfter && j.Project__c == 'Harvey' && j.Issue_Type__c == 'Epic') {
            JCFS.API.createJiraIssue('10300', '10000');
        }
        if (Trigger.isUpdate && Trigger.isAfter) {
            JCFS.API.pushUpdatesToJira();
        }
    }
}

Current APEX Class: (0% code coverage)
@isTest public class JIRATriggerTest {
    @isTest static void caseAfterInsertTest() {
        JCFS.JiraTriggerTestHelper.testAfterInsert('JIRA__c');
    }
    @isTest static void caseAfterUpdateTest() {
        JCFS.JiraTriggerTestHelper.testAfterUpdate('JIRA__c');
    }
}

 
public class EC_CaseDetailController {
public String currentRecordId {get;set;}
public String parameterValue {get;set;}
public Case ca{get;set;} 
    public EC_CaseDetailController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        ca = [select Casenumber,
              PRX_Entity__c,
              PRX_Type_of_request__c,
              Status, 
              CreatedDate,
              ClosedDate,
              PRX_Number_of_requests__c,
              PRX_Partner_Customer_name__c,
              ContactEmail,
              PRX_Name__c,
              PRX_Free_text_field__c,
              PRX_Mobile_number__c from Case where id =: currentRecordId ];
        parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
    }
Hi all,

I have below code. I want to show error on VF page when particular condition not met and records not found.I have added my code in try catch block and added apex:messages as well.
Please suggest me what is wrong.
The error should be displayed when combination of service family and sub service category is not found in database.
 
Class:


public with sharing class SurveyClass{

Public Account acc{get;set;}
Public Proposal_Form__c pfc;
Public Proposal_Form__c pfc1 {get;set;}
public ProposalFields__c pf {get;set;}
public List<String> fieldSet {get;set;}
Public ID rid;
private ApexPages.StandardController standardController;
    
public SurveyClass(ApexPages.StandardController controller) {
    this.standardController = standardController;
    pfc1 = new Proposal_Form__c();
  }

public void Selected(){
    system.debug(pfc1.Service_Family__c +'------------'+pfc1.Sub_Service_Category__c);
    
    try{
        pfc = [SELECT Fields_Associated__c FROM Proposal_Form__c where Service_Family__c =: pfc1.Service_Family__c and Sub_Service_Category__c =: pfc1.Sub_Service_Category__c LIMIT 1];
        
    } catch(Exception ex){
     ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'No such combination exists');
     ApexPages.addMessage(myMsg);
      
    }
     
    fieldSet = new List<String>();
    List<String> fields = new List<String>();
    if(pfc.Fields_Associated__c != null && pfc.Fields_Associated__c != ''){
        fields = String.valueof(pfc.Fields_Associated__c).split(',');
        system.debug('*********Fields******'+fields);
    }
    else{
        Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No questions to Display"'));
    
    }
    Map<String,String> labelMap = new Map<String,String>();
    labelMap = getLabel.retLabelMap('ProposalFields__c');
    system.debug(labelMap);
    system.debug(labelMap);
    for(String s : fields){
        fieldSet.add(labelMap.get(s));
        system.debug('********fieldset*******'+fieldSet);
    }
    
}
}


VF Page:;


<apex:page standardController="Account" extensions="SurveyClass" sidebar="false" showHeader="false" tabStyle="Account">

<apex:form >
<apex:pageMessages rendered="true"/>
<apex:pageBlock title="Client Survey Form"> 
<apex:pageBlockSection title="Service Requirements" >

<apex:inputField value="{!pfc1.Service_Family__c}"/>
 
<apex:pageblocksectionItem >
    <apex:outputLabel value="Sub Service Category"/>
    <apex:outputPanel >
        
            <apex:inputfield value="{!pfc1.Sub_Service_Category__c}">
                <apex:actionSupport event="onchange" action="{!Selected}" rerender="fieldst" />
                <apex:pageMessages rendered="true"/>
            </apex:inputField>
       
    </apex:outputPanel>
</apex:pageblocksectionItem>
</apex:pageBlockSection> 

<apex:pageblockSection title="Question Set" id="fieldst">
    <apex:repeat value="{!fieldSet}" var="f">
      <apex:inputField value="{!pf[f]}"/> 
    </apex:repeat>
</apex:pageblockSection>

<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Submit" action="{!Save}"/>
</apex:pageBlockButtons>



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


 
Hi.
I tried to 'deploy to server' from Eclipse, and then validate, the error is occured.
'No package.xml found'.

Can anyone help me to solve this issue?
This deployment is from Sandbox to Product.

Please help.
 
I've created a button with this java script:
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")} 
sforce.apex.execute("buttonHandler","copyOLItoPP",{id:"{!Opportunity.Id}"}); 
location.reload();

but I keep getting this error whenever I try to click it:
{faultcode:'soapenv:Client; faultstring:'No such parameter id defined for operation. please check the WSDL for the service.'}
I have a field called "Call_Count__c" which is a number field in Contact. I want that when some one logs a call and if the Subject Category is "Call" or "Update" the Call Count field should increase by 1. for eg if value in call count field is 3 it should become 1. Please help me with a trigger for this.