• Amol Ch
  • NEWBIE
  • 105 Points
  • Member since 2015

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 26
    Questions
  • 48
    Replies
Hi All,

How can i link my VF Save button to a URL so that when a record in saved in my form, the user is redirectd to "www.google.com". Ive tried looking on different forms but other situations is always different to mine. Thanks for your help!

his is a snippet of my code.




<apex:page standardController="Turndown__c" sidebar="false" showHeader="true" extensions="pagereference" >
    <apex:form >
           <apex:pageBlock title="Documented Turndowns" id="turndown_list">
            
             <apex:pageBlockSection columns="1" >
                    <!-- to remove the header, but keep the fields' help texts -->
                         <style type="text/css">
                             .bPageHeader {display: none;}
                             </style>
                    
                                            <!-- Inputfields --> 
                                <apex:inputfield value="{! Turndown__c.Account__c }"/>
                                <apex:inputfield value="{! Turndown__c.Phone_Number__c }"/>
                                <apex:inputfield value="{! Turndown__c.Region__c }"/>

              
                 
                   </apex:pageBlockSection>
                        <apex:pageBlockButtons >  
                  
                                        <apex:commandButton action="{!Save}" value="Save"  />
 
                        </apex:pageBlockButtons>       


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

     
             
                                            
Thanks again!             
 

Hi,

I have created a Trigger and used Helper class in the trigger and created the Test Class which is covering 96% of helper class but when I am trying to deploy the code then it is showing 20% code coverage bcoz of which I am unable to deploy the code. Can anyone help?

 

Trigger

trigger lead_agent_trigger on Lead (before insert,before Update) 
    {   
    
    Lead_Agent_Trigger_Helper.Agent(trigger.new);
    
        
    }

Helper Class:-

public class Lead_Agent_Trigger_Helper {

public void Agent(List<Lead> Leads)
{
    for(Lead loopVar : Leads)
    {
        try
        {
            string country = loopVar.Country;
            //Agents__c agent = [select Id,Agent_Name__c,agent_email__c  from Agents__c where Country__c like : country and Active__c = True and Edition__c =: loopVar.Edition__c limit 1];
            if(loopVar.Sent_to_Agent__c==true)
           {
                if(loopVar.Sector_show__c == null && loopVar.Sectors__c == null)
                {
                    Agents__c agent = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c where 
                                       Country__c like : country and 
                                       Active__c = True and 
                                       Edition__c =: loopVar.Edition__c and
                                       Sector_show__c = null and
                                       Sectors__c = null limit 1];
                    loopVar.Agent__c = agent.Agent_Name__c;
                    loopVar.agent_email__c= agent.agent_email__c;
                    
                    Contact contact = [select AccountId,Email from Contact where Id =: agent.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact.AccountId;
                    loopVar.Agents__c = agent.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }
                else if(loopVar.Sector_show__c != null && loopVar.Sectors__c != null)
                {
                    String sector = loopVar.Sectors__c;
                    Agents__c agent1 = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c 
                                        where Country__c like : country 
                                        and Active__c = True and Edition__c =: loopVar.Edition__c 
                                        and Sector_show__c =: loopVar.Sector_show__c
                                        and Sectors__c  Includes (:sector) limit 1];
                    loopVar.Agent__c = agent1.Agent_Name__c;
                    loopVar.agent_email__c= agent1.agent_email__c;
                    
                    Contact contact1 = [select AccountId,Email from Contact where Id =: agent1.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact1.AccountId;
                    loopVar.Agents__c = agent1.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }           
            }
        }
        
        catch(Exception E){}
}
}
}

 

Test Class:-

public class Lead_Agent_Trigger_Helper {

public void Agent(List<Lead> Leads)
{
    for(Lead loopVar : Leads)
    {
        try
        {
            string country = loopVar.Country;
            //Agents__c agent = [select Id,Agent_Name__c,agent_email__c  from Agents__c where Country__c like : country and Active__c = True and Edition__c =: loopVar.Edition__c limit 1];
            if(loopVar.Sent_to_Agent__c==true)
           {
                if(loopVar.Sector_show__c == null && loopVar.Sectors__c == null)
                {
                    Agents__c agent = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c where 
                                       Country__c like : country and 
                                       Active__c = True and 
                                       Edition__c =: loopVar.Edition__c and
                                       Sector_show__c = null and
                                       Sectors__c = null limit 1];
                    loopVar.Agent__c = agent.Agent_Name__c;
                    loopVar.agent_email__c= agent.agent_email__c;
                    
                    Contact contact = [select AccountId,Email from Contact where Id =: agent.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact.AccountId;
                    loopVar.Agents__c = agent.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }
                else if(loopVar.Sector_show__c != null && loopVar.Sectors__c != null)
                {
                    String sector = loopVar.Sectors__c;
                    Agents__c agent1 = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c 
                                        where Country__c like : country 
                                        and Active__c = True and Edition__c =: loopVar.Edition__c 
                                        and Sector_show__c =: loopVar.Sector_show__c
                                        and Sectors__c  Includes (:sector) limit 1];
                    loopVar.Agent__c = agent1.Agent_Name__c;
                    loopVar.agent_email__c= agent1.agent_email__c;
                    
                    Contact contact1 = [select AccountId,Email from Contact where Id =: agent1.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact1.AccountId;
                    loopVar.Agents__c = agent1.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }           
            }
        }
        
        catch(Exception E){}
}
}

Error:-
 Code Coverage Error

I am integration salesforce with SAP system using SOAP API. SAP Provided the Username and Password. So I have created a NamedCreditials in salesforce and used that in my apex class as endpoint.

like 
public String endpoint_x ='callout:SAP_Callout';

AS per salesforce doc https://help.salesforce.com/HTViewSolution?id=000003652 we have whitelisted the Salesforce IP ranges in Firewall on SAP End.
But during callout, still we are getting Error,

System.Callout Exception Unexpected end of file from server

Named Credentials: http://prntscr.com/l28ba7 

Snapshot of IP ranges which is configured in firewall.

User-added imageUser-added imageUser-added imageUser-added image
I have a Vf page to display the related list which is editable.
Assesment is Custom object. We have two button "Create Assesment" & "Update assesment" on VF Page.
Scenario 1: When I open the page & click on update assessment then it updates the related record correct. Its Fine.
Scenario 2: When I open the page & click on create assessment button it open in new tab and I've created the record. Again back to same vf page & click on update assessment button then it updating the wrong records.
how to resolve this issue.
Vf Page:
<apex:page standardController="Assessment__c" sidebar="false" showHeader="false" showChat="true" extensions="AssessmentController">
<apex:form >
    <apex:pageBlock id="block1" >
        <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockSection title="Assessments" id="Assessments" columns="1" collapsible="true" >
                 <apex:outputPanel >
                    <apex:commandLink action="{!createAssesmnt}" target="_blank"><apex:commandButton value="New Assesment" style="float:right;"/></apex:commandLink>        
                    <apex:commandButton action="{!updateAss}" value="Update Assesment" style="float:right;" reRender="refTble"/>  
                  </apex:outputPanel>
                <apex:outputPanel Id="blockrefresh">
                <apex:pageBlockTable value="{!Asses}" var="a" Id="refTble" >
                    <apex:column headerValue="Assment" style="width: 5px;" >
                        <apex:outputLink value="/{!a.id}" target="_blank">Open</apex:outputLink>
                    </apex:column>

                    <apex:column headerValue="Description" >
                        <apex:inputField value="{!a.Assessment_Description__c}" style="overflow:hidden"/>
                    </apex:column>

                    <apex:column headerValue="Last Screening" >
                        <apex:inputField value="{!a.Last_Screening__c}" style="overflow:hidden"/>
                    </apex:column>

                </apex:pageBlockTable> 
                    </apex:outputPanel>
            </apex:pageBlockSection>
     </apex:pageBlock>
</apex:form>
Controller:
public with sharing class AssessmentController {

private List<Assessment__c> asses;
Assessment__c assment;
Assessment__c AssRec;
public Outcome__c outcome{get;set;}

public AssessmentController(ApexPages.StandardController controller) {
    this.assment= (Assessment__c)controller.getRecord();
    outcome = new Outcome__c ();
    AssRec= [select id,Name,Patient__r.Name,PHQ9_Measurement_ID__c,PSMS_Measurement_ID__c from Assessment__c where Id=:assment.Id];
}
public PageReference createAssesmnt(){
    Schema.DescribeSObjectResult result = Assessment__c.SObjectType.getDescribe();
    PageReference pageRef = new PageReference('/' + result.getKeyPrefix() + '/e?C00N1a000006Z8Gs_lkid='+assment.Patient__c+'&CF00N1a000006Z8Gs='+AssRec.Patient__r.Name);
    pageRef.setRedirect(true);
    return pageRef;
}
public List<Assessment__c> getAsses()
{  
    asses = [Select id,Assessment_Description__c,Last_Screening__c,Clone__c,Category__c,Date_Due__c, Resolved__c,Delete__c,Type__c,Sort__c,RT_Type__c,Outcome_Count__c,Create_Outcome__c,Use_Screening_Update__c,Screening_Update__c, (select id,Name,Assessment_Description__c,Outcome_Description__c,Type__c,Completed__c from Outcomes__r) from Assessment__c where Resolved__c=false AND Patient__c=:assment.Patient__c ORDER BY Assessment_Description__c ASC];
    for(Assessment__c a:asses)
    system.debug('Assesment List ##'+a.Id+'   '+a.Assessment_Description__c);
    return asses;
}
public pageReference updateAss(){
try{
    for(Assessment__c a:asses)
    system.debug('Assesment List @@'+a.Id+'   '+a.Assessment_Description__c);
    update asses;

    return null;
}
catch(Exception e){
    string message='Data Base error during saving...';
    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR,message));
    return null; 
}
} 
 }



 
I'm displaying the list of account record on VF page in pageblocktable. Account record will be inline edit on Vf page. Now I've to display the list of realted contact on account record on mouseover/click, In such a way that User can quickly review(read only) the contact without scrolling up/down.
So need a contact list should be visible on mosuseover. Is it possible? or other option.

we can display the realted list of contact below to all account record but in this case user has to scroll down. This it is not satisfy my requirement.
I've a force.com website, Now I'm integrating 2checkout(www.2checkout.com) payment gateway with my website.

As per this documentation I'm able to send the correct data to 2checkoout API. 2checkout is processing my payment on their  side. As per this I've mentioned the my VF page redirect URL on 2checkout , so i can redirect to back to my website after transaction complete.

After completing transaction on 2checkout, it will redirecting to my website at same time they sending the transaction parameter.

Now I've to get that transaction paramenter to my VF page. So I can store it in salesforce. How to get the parameter in VF page.

I've try to implement the below: 
VF page
<apex:page controller="paymentstatuscontr" action="{!SearchEvent}">
   hello
   {!a}<br/>        
   {!b}<br/>
   <apex:outputText value="{!response}"/> <br/>
    {!op}
</apex:page>
Contoller :
public class paymentstatuscontr {
public string a  {get; set;}
public string b  {get; set;}
public string response { get; set;}
public HttpResponse op { get; set;}

public void  SearchEvent() {
    System.debug(' ------ ');
    a='test data';
    // Instantiate a new http object
    Http h = new Http();
    // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://sandbox.2checkout.com/checkout/purchase');
    req.setMethod('GET');
    req.setHeader('Content-Type', 'application/json');
    HttpResponse res = h.send(req);
    System.debug(' ------ '+res);
    System.debug(' ------ '+res.getbody());
        
    /*
    /// tryied this but getting error System.CalloutException: no protocol Error    Salesforce call     out 

    if (res.getStatusCode() == 302) {
    req.setEndpoint(res.getHeader('Location'));
    res = new Http().send(req);
    response =res.getbody();
    }
    */     
    
    response =res.getbody();
    op = res;
    if(res.getStatusCode()==201){ 
        system.debug('@@@Success');
        b='Pass';
    }
    else{
        system.debug('@@@failed');
        b='Fail';
    }
  }
}
https://sandbox.2checkout.com/checkout/purchase  This is the URL for 2 Checkout  where I'm redirecting from 2chekout to my website. Please check below website. 
User-added image

Below is the output of VF page:
User-added image

It's showing me 302 Found.
Is I'm going by correct way or in wrong way.

Please Suggest the solution.

I've created the PHP page as putted that php page as redirect page, in this case I'm getting the all parameter on PHP page. But got stuck by using VF Page.
How to integrate outlook and salesforce.

My requirement is, when I received email, I've to add the email attachment to the respective contact record in salesforce.

As standard salesforce for outlook in not supporting. I'm using salesforce classic version.

Please guide.
  • September 21, 2017
  • Like
  • 0
I've created a community, and setup a custom domain name for community.

consider, My community url : www.xyz.force.com.

Customized domain name for community : www.xyz.com.

When I'm searching for website in google, it shows the pages with link like; www.xyz.force.com/... This should not be happen. means customer should not be able to see standard domain name of community.

Customer should be able to see the link on google like; www.xyz.com/...

Please check below screenshot:
User-added image

I've already submitted the sitemap.xml file to google webmaster tool more than 2 -3 week ago.

Please suggest any workaround.
I've created a website on community. and Set up Custom Domains for Salesforce Sites. I've configured the each and every thing as per this article.
when i type the my website URL like "www.mycompany.com" it works perfectly.

But the same URL is not working without www. means, when I type "mycompany.com" in the browser URL. It doesn't working , it shows blank page.
Please guide.
I've created a VF page with Dynamic filter.
Means My SOQL is Build dynamically in controller and I'm using Standard Set controller method to return the record.
I want the page pagination to display all 70 k record on VF page.

How we can do that.. Please Guide.
My requirement is like that;
I've different product pricing in saleforce. i 've to send the link of product and pricing to the customer via email. when customer click on that link in email they can able to see it.

Question is when customer open that link how it can see. Can we see that information on newly devloped PHP or asp.net website. or we need to by any saleforce portal for this. I'm not sure, customer is outside the company. he does not have saleforce access.

and another is when customer open link in email on that page he has book now option when he click on it, then it redirect to another payment site which is also we have to connect to the saleforce.

The diagram is:
User-added image
Please give some suggestion.

Thanx,
Amol
  • September 06, 2016
  • Like
  • 0
I've to create a field on contact object to store finger print.
now the quoestion is;
How to scan finger in salesforce.
i've to use finger print machine which is connected to computer externally.
Please guide.
Overall task is scan the barcode in saledforce.

Suppose my comoputer is connect with barcode scanner machine.
In salesforece  i've a custom object ITEM.  create a visualforce page of this item object and when we  click on new button the page will display.
we can scan the barcode then barcode id should be display on the page in row.
and finally when we click on saved button then record will be saved

How to achieve overall this functionality.

Please suggest.
 
I've written simple code to update field on object by using javascript custom button, The field is read only from Page Layout. When i try for System Admin it works, but when i try for non-admin user it throwing Error. The code is ;
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

 var o = new sforce.SObject("Student__c");
 o.id = "{!Student__c.Id}";
 alert(o.id)
 o.Laptop__c = true; 
 result =sforce.connection.update([o]);

 if (result[0].getBoolean("success")) {
 alert("record with id " + result[0].id + " updated");
 } else {
 alert("failed to update " + result[0]);
 }
 window.location.reload();
it throws me error as;
failed to update {errors:{fields:'Id', message:'Record ID: id value of incorrect type: fgggggggggg', statusCode:'MALFORMED_ID', }, id:null, success:'false', }
Even if i've removed read only form page layout still its throwing why? please suggest.
 
I've a field read only from field accessibility for a profile. on object has custom javascript button. It contain code to update checkbox field.

when i run for admin it works, but when it run for non-Admin user, this will not update the read only check box field.

i want checkbox field should be editabe from that button and not manually
how can i do?
 
formula field is not getting executed in test class, due to this condition is fails in apex class. the test class is below
@isTest(seealldata=false)
public class CreateOpty_Phyothersvcs_WPatsBatchTest {
static testMethod void test()
{
patient__C pat=new patient__C();
pat.name=test;
cost__C=100;
insert pat;

job__c jb = new job__c();
jb.name__c=test;
patient__C.id=pat.id;
//some field
insert jb;
//formula field in job object is patient_cost__c=patinet__r.cost__C

system.debug(''+jb.patient_cost__c);  //it showing null
//when i write query like

List<job__c> job = new List<job__c>();
job=[select id patient_cost__c from patient_cost__c where id=:jb.id];
 system.debug(''+job[0].patient_cost__c);  //it showing 100 correct as required

// but i want here 100
system.debug(''+jb.patient_cost__c);  //its still showing null
i've some formula field and another field update based on that formula field and thus
If formula field is Null then other field update operation will also be failed .
another it will not be cover test code coverage in apex class
in apex class i've used condtion like ex.
public class MySampleApexClass {
//some code
 List<job__c> jb=new List<job__c>();
 job=[select id,patient_cost__c from job__C where //some condition];
 for(job__c job : jb )
 {
		if(job.patient_cost__c<=50000) //this will fails(not cover in test class) due to formula field
			{ 
			
			//some code with different operation
			}
 }
 }



 
how to cover catch block in test class. below is the trigger. because if controller goes to update updatedAccSt  then it always update account
trigger SetAccountStatus on job__c (after insert) {
List<Account> AccSt = new List<Account_Status__c>();
List<Account> updatedAccSt = new List<Account_Status__c>();
List<Id> patientIds = new List<Id>();
for (job__c  job: trigger.new) 
	{
     patientIds.add(patient.id);
	}
	
AccSt = [Select Id,Account_Status__c from Account WHERE job__c in :patientIds ];
 
  for(Account_Status__c a : AccSt)
  {
    a.Account_Status__c = true;
    updatedAccSt.add(a);
  }
 
  if(updatedAccSt.size()>0)
  {
  try{
   update updatedAccSt;
   }
   catch{
      // here is code to send Email and other operation
   
   }
  }
}
below is the test class.
@istest(seealldata=false)
public class SetAccountStatustest {
    static testMethod void test()
    {
	patient__c pat = new patient__c();
		pat.name__c=Test;
		//some field
		insert pat;
		
	  Account acc = new Account();
	  acc.Name=Test;
	  acc.Patient__C=pat.id;
	  acc.Account_Status__c
	  //some field;
	  insert acc;
	  
	  job__c acc = new job__c();
	  job.Name__c=test;
	  //some field
	  insert job;
	  
	 }
	}
The above class is only example. my code is big code due to this i put here example.

 
I' ve one object Patient service and job is look up field on same object. field job has look up filter enable as below.
User-added image
@IsTest
public class test1
{
	Static testmethod void test12()
    {
		Job__c job= new Job__c();
            job.skdate__Finish__c = '20/08/2014 8:30 AM';
            job.skdate__Start__c = '18/08/2014 8:30 AM';
            job.Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM');
            job.Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM');
            job.sked__Duration__c = 501;
            job.sked__Region__c = Reg.Id;
            job.sked__Type__c='Podiatry Clinic';
            job.Job_Billable__c =true;
            job.Service_Type__c='Podiatry';
            job.Resource_Name__c=Res.Name;
            insert job;
               
        Patient_Services__c ps = new Patient_Services__c();
            ps.Service_Type__c = 'Podiatry';
            ps.Job__c = job.id;
            ps.Who_to_Invoice__c='Medicare Account';
             ps.Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM');
            ps.Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM');
            ps.Patient_Service_Lunch__c='10';
            insert ps;
	}
}
at the line insert ps  it throwing error as below

Value does not exist or does not match filter criteria.: [Job__c]

Please suggest what wrong here.
 
I' ve one object Patient service and job is look up field on same object. field job has look up filter enable as below.
User-added image

in my test class, i'm creating my test data like;
 
@Istest(SeeAllData=false)
public class test1{
  Static testmethod void test12()
    {
     job__c job= new Job__c();
     //job fields
      job.Service_Type__c='ABC';
insert job;

 Patient_Services__c ps = new Patient_Services__c();
     //ps fields
     ps.Service_Type__c='ABC';
insert ps
}}
at the line insert ps  it throwing error as below

Value does not exist or does not match filter criteria.: [Job__c]

Please suggest what wrong here.
 
Below is the apex class which will call from trigger on after update event
public class OptyCreationForDispFootPres
    {
    public static void createopty(List<Patient_Services__c> PSlist, map<id,Patient_Services__c> oldPSMap)
        {
        	set<string> PatientID= new set<string>();
            List<Patient_Services__c> psnewlist = new List<Patient_Services__c>();
            List<Rate_Card__c> rcardnewlist =new List<Rate_Card__c>();
            List<sked__Job__c> joblist=new List<sked__Job__c>();
            List<sked__Job__c> joblistnw=new List<sked__Job__c>();
            Set<OpportunityLineItem> olilist=new Set<OpportunityLineItem>();
            List<OpportunityLineItem> olilist1=new List<OpportunityLineItem>(); 
            List<Opportunity> oplist=new List<Opportunity>();
            List<Account> accname = new List<Account>();
            Integer extid;
            String RecNamePodwP,RecNameAudwP,RecNameDiteticscwP,RecNameDivTrpwP,RecNameMntHlthwP,RecNameOccTrpwP,RecNameOptmwP,RecNamePhytrpwP,RecNamePhyTrpExClswP,RecNameRegNrsewP,RecNameSpchTrpwP;
            String myeffDate = date.today().format();
            Date Nxtoptycreationdate,Closedate;
            String BillableCycle,InvoiceSentby,InvoiceSentTo,Accntterms,RateCardtype;
            List<Patient_Services__c> psupdlist= new List<Patient_Services__c>();
            Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe() ;
            Map<String,Schema.RecordTypeInfo> recordType = sObjectMap.get('Opportunity').getDescribe().getRecordTypeInfosByName();
            ID RtIdPodwP,RtIdAudwP,RtIdDiteticscwP,RtIdDivTrpwP,RtIdMntHlthwP,RtIdOccTrpwP,RtIdOptmwP,RtIdPhytrpwP,RtIdPhyTrpExClswP,RtIdRegNrsewP,RtIdSpchTrpwP;
            User vLstUserop = [select id from User where Opportunity_Owner__c=true and IsActive=true LIMIT 1];
            List<Opportunity> opty=[select Id,Opty_No__c from Opportunity order by CreatedDate DESC limit 1];
             
             
             for(Patient_Services__c PS :PSlist)
            {
                if(ps.Ready_for_Billing__c==true && ps.Dispensing_Footwear_F049__c==true && oldPSMap.get(ps.id).Dispensing_Footwear_F049__c ==false)
               
                {
                    PatientID.add(ps.id);
                }
             
            }
            
            psnewlist = [select id,Medicare_Account__c,Emergency_Visit__c,DVA_Code__c,Patient_DVA_Number__c,Patient_Medicare_No__c,
            Podiatry_Services__c,Job_Start_Datew_otime__c,Dispensing_Footwear_F049__c,DVA_Account__c,Initial_Consultation__c,
            Subsequent_Consulation__c,RecordType.name,Patient__r.Medicare_Account__c,Patient__r.Medicare_Account__r.Name,
            Patient__r.DVA_Account__c,Patient__r.DVA_Account__r.Name,Who_to_Invoice__c,Patient_Service_Lunch__c,
            Patient_Service_Invoice_Duration__c,Job_allocation_count__c,Job_Invoice_Start__c,Job_Invoice_Duration__c,Job_Invoice_Finish__c,
            Lunch_Break_Duration_from_Job__c,Job_Billable__c,Job__c,Patient_Service_Invoice_Finish__c,Patient_Service_Invoice_Start__c,
            Job_Type__c,Resource_Name__c,Service_Type__c from Patient_Services__c where id in :PatientID ]; 
            
                        
             if(PatientID.size()>0)
            {
            
            system.debug('++++++++++++++++++++++++++'+psnewlist.size());
           
                List<Rate_Card__c> ratecardlist = new List<Rate_Card__c>();
            
                ratecardlist=[Select id,Next_Opportunity_Creation_Date__c,Which_Rate_to_use_withpatients__c,Footwear_Dispensed__c,
                Emergency_Visit__c,PricebookEntryId__c,Job_Type__c,Assessment__c,Travel__c,Report__c,Treatment_Rate__c,Menu_Review__c,
                Hourly_Rate__c,Account_Name__c,Other__c,Next_Billable_Date__c,Opportunity_Creation_Frequency__c,Invoice_sent_by__c,Invoice_sent_to__c,Account_Terms__c,
                Rate_Card_Type__c from Rate_Card__c where Account_Name__c='Department of Veteran Affairs'];
                
                   // String DVAaccId = pslines.Patient__r.DVA_Account__c;
                   //  String DVAaccName = pslines.Patient__r.DVA_Account__r.Name;
            
                    
                for(Patient_Services__c pslines : psnewlist)
                {   for(Rate_Card__c rcard : ratecardlist)
                    {
                    if(rcard.Job_Type__c ==pslines.Job_Type__c && rcard.Rate_Card_Type__c == pslines.Service_Type__c)
                    rcardnewlist.add(rcard);
                    }
                }
                
                if(rcardnewlist.size()>0)
                {
                
               
                
                    for(Patient_Services__c pslines : psnewlist)
                    {
                   
                         if(pslines.RecordType.name =='Podiatry')
                        {
                            RtIdPodwP = recordType.get('Podiatry with Patients').getRecordTypeId();
                            RecNamePodwP=recordType.get('Podiatry with Patients').getName();
                            
                            System.debug('!!!!!!!!!!!!!!!!!!!!!!!!!!'+pslines.RecordType.name);
                       }
                     else if(pslines.RecordType.name =='Audiology')
                             {
                                RtIdAudwP = recordType.get('Audiology with Patients').getRecordTypeId();
                                RecNameAudwP=recordType.get('Audiology with Patients').getName();
                              }
                            else if(pslines.RecordType.name =='Dietetics')
                                {
                                    RtIdDiteticscwP = recordType.get('Dietetics with Patients').getRecordTypeId();
                                    RecNameDiteticscwP=recordType.get('Dietetics with Patients').getName();
                                }
                            else if(pslines.RecordType.name =='Diversional Therapy')
                                {
                                    RtIdDivTrpwP = recordType.get('Diversional Therapy with Patients').getRecordTypeId();
                                    RecNameDivTrpwP=recordType.get('Diversional Therapy with Patients').getName();
                                }
                            else if(pslines.RecordType.name =='Mental Health')
                            {
                                RtIdMntHlthwP = recordType.get('Mental Health with Patients').getRecordTypeId();
                                RecNameMntHlthwP = recordType.get('Mental Health with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Occupational Therapy')
                            {
                                RtIdOccTrpwP = recordType.get('Occupational Therapy with Patients').getRecordTypeId();
                                RecNameOccTrpwP=recordType.get('Occupational Therapy with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Optometry')
                            {
                                RtIdOptmwP = recordType.get('Optometry with Patients').getRecordTypeId();
                                RecNameOptmwP=recordType.get('Optometry with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Physiotherapy')
                            {
                                RtIdPhytrpwP = recordType.get('Physiotherapy with Patients').getRecordTypeId();
                                RecNamePhytrpwP=recordType.get('Physiotherapy with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Physiotherapy Exercise Classes')
                            {
                                RtIdPhyTrpExClswP = recordType.get('Physiotherapy Exercise Classes with Patients').getRecordTypeId();
                                RecNamePhyTrpExClswP=recordType.get('Physiotherapy Exercise Classes with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Registered Nurse')
                            {
                                RtIdRegNrsewP = recordType.get('Registered Nurse with Patients').getRecordTypeId();
                                RecNameRegNrsewP=recordType.get('Registered Nurse with Patients').getName();
                            }
                            else
                            {
                                RtIdSpchTrpwP = recordType.get('Speech Therapy with Patients').getRecordTypeId();
                                RecNameSpchTrpwP=recordType.get('Speech Therapy with Patients').getName();
                            }

                    
                    
                            for(Opportunity oppty:opty)
                            {
                                extid=Integer.valueOf(oppty.Opty_No__c)+1;
                            }
                    
                       
                           
                             Opportunity newopp =new Opportunity();
                             newopp.Optycreationbatch__c='DVA-WP-'+myeffDate+'-'+extid;
                             
                             
                                 for(Rate_Card__c rc : rcardnewlist)
                            {
                                    OpportunityLineItem oli = new OpportunityLineItem();
                                     oli.Opportunity =new Opportunity(Optycreationbatch__c=newopp.Optycreationbatch__c);
                                    oli.PriceBookEntryId = rc.PricebookEntryId__c;
                                    oli.Patient_Service__c=pslines.Id;
                                    oli.Provider_Name__c=pslines.Resource_Name__c;
                                    oli.Patient_Service_Invoice_Start__c=pslines.Patient_Service_Invoice_Start__c;
                                    oli.Patient_Service_Invoice_Finish__c=pslines.Patient_Service_Invoice_Finish__c;
                                    oli.Rate_Card__c=rc.Id;
                                    oli.UnitPrice = rc.Hourly_Rate__c;
                                    oli.Quantity = pslines.Job_allocation_count__c;
                                    oli.Patient_Service_Lunch__c=pslines.Patient_Service_Lunch__c;
                                    oli.Invoice_Start__c=pslines.Job_Invoice_Start__c;
                                    oli.Invoice_Finish__c=pslines.Job_Invoice_Finish__c;
                                    oli.Lunch_Break_Duration_from_Job__c=pslines.Lunch_Break_Duration_from_Job__c;
                                    oli.DVA_Code__c=pslines.DVA_Code__c;
                                    oli.AHP_Type__c=pslines.Podiatry_Services__c;
                                    
                                     if(pslines.Job_Billable__c ==true)
                                         {
                                              oli.Job_lkup__c=pslines.Job__c;
                                               oli.UnitPrice = rc.Footwear_Dispensed__c;
                                                oli.Quantity = pslines.Job_allocation_count__c;
                                         
                                         }
                                         else
                                             {
                                                oli.Job_lkup__c=pslines.Job__c;
                                                oli.Quantity = pslines.Job_Invoice_Duration__c; 
                                                oli.UnitPrice=0;
                                             }
                                             
                                        if( (oli.Quantity!=NULL) && (oli.PriceBookEntryId!=NULL))
                                            {
                                             olilist1.add(oli);
                                             psupdlist.add(pslines);
                                            }
                            
                            
                            
                                    newopp.OwnerId=vLstUserop.Id;
                                      newopp.stagename='To be reviewed';
                                      Nxtoptycreationdate=rc.Next_Opportunity_Creation_Date__c;
                                      Closedate=rc.Next_Billable_Date__c;
                                      BillableCycle=rc.Opportunity_Creation_Frequency__c;
                                      InvoiceSentby=rc.Invoice_sent_by__c;
                                      InvoiceSentTo=rc.Invoice_sent_to__c;
                                      Accntterms=rc.Account_Terms__c;
                                      RateCardtype=rc.Rate_Card_Type__c;
                                    
                                          newopp.DVA__c = true;
                                        newopp.AccountId=pslines.Patient__r.DVA_Account__c;
                                    
                                            System.debug('$$$$$$$$$$$$$$$$$$$$$$$$'+pslines.Patient__r.DVA_Account__r.Name);
                                            if(pslines.RecordType.name =='Podiatry')
                                            {
                                            newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePodwP + '-'+ Nxtoptycreationdate.format();
                                            newopp.RecordTypeId = recordType.get('Podiatry with Patients').getRecordTypeId();
                                            }
                                            else if(pslines.RecordType.name =='Audiology')
                                            {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameAudwP + '-'+ Nxtoptycreationdate.format();
                                                     newopp.RecordTypeId=RtIdAudwP ;
                                             }
                                           else if(pslines.RecordType.name =='Dietetics')
                                            { 
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameDiteticscwP + '-'+ Nxtoptycreationdate.format();
                                                       newopp.RecordTypeId=RtIdDiteticscwP ;
                                             }
                                           else if(pslines.RecordType.name =='Diversional Therapy')
                                            {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameDivTrpwP + '-'+ Nxtoptycreationdate.format();
                                                     newopp.RecordTypeId=RtIdDivTrpwP ;
                                             }
                                           else if(pslines.RecordType.name =='Mental Health')
                                            {
                                                    newopp.RecordTypeId=RtIdMntHlthwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameMntHlthwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Occupational Therapy')
                                            {
                                                    newopp.RecordTypeId=RtIdOccTrpwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameOccTrpwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Optometry')
                                            {
                                                    newopp.RecordTypeId=RtIdOptmwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameOptmwP + '-'+ Nxtoptycreationdate.format();
                                             }
                                           else if(pslines.RecordType.name =='Physiotherapy')
                                            {
                                                    newopp.RecordTypeId=RtIdPhytrpwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePhytrpwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Physiotherapy Exercise Classes')
                                            {
                                                    newopp.RecordTypeId=RtIdPhyTrpExClswP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePhyTrpExClswP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Registered Nurse')
                                            {
                                                    newopp.RecordTypeId=RtIdRegNrsewP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameRegNrsewP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Speech Pathology')
                                                    {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameSpchTrpwP + '-'+ Nxtoptycreationdate.format();
                                                      newopp.RecordTypeId=RtIdSpchTrpwP ; 
                                                     }
                                                      
                                      newopp.closedate=Closedate;
                                      newopp.Billable_Cycle__c=BillableCycle;
                                      newopp.RateCard__c=rc.Id;
                                      newopp.Invoice_sent_by__c=InvoiceSentby;
                                      newopp.Invoice_sent_to__c=InvoiceSentTo;
                                      newopp.Date_From__c=pslines.Job_Start_Datew_otime__c;
                                      newopp.Patient_DVA_No__c = pslines.Patient_DVA_Number__c;
                                      newopp.Patient_Medicare_No__c = pslines.Patient_Medicare_No__c;
                                      newopp.AHP_Type__c= pslines.Podiatry_Services__c;
                                      newopp.Date_To__c=Nxtoptycreationdate;
                                      newopp.Service_Type__c=RateCardtype;
                                      oplist.add(newopp);
                                    
                                
                                }
                    }                               
                        
                    }   
                
                }        
          if(olilist1.size()>0 && oplist.size()>0)
                   {
                  
                Database.SaveResult[] srList = Database.insert(oplist,false);
                Database.SaveResult[] srListlineitem = Database.insert(olilist1,false);  
                List<OpportunityLineItem> psidsfromlines=new List<OpportunityLineItem>();
                List<Patient_Services__c> psfinalupd= new List<Patient_Services__c>();
                List<Patient_Services__c> pswthsamejob = new List<Patient_Services__c>();
                List<sked__Job__c> jobfinalupd=new List<sked__Job__c>();
                Map<Id,Boolean> lineidssuccess=new Map<Id,Boolean>();
                List<Billing_Error_log__c> errorlog=new List<Billing_Error_log__c>();
                
                 for (Database.SaveResult sr : srListlineitem) 
                {
                        if (!sr.isSuccess()) 
                        {
                          Billing_Error_log__c billlog = new Billing_Error_log__c();
                                       
                            for(Database.Error err : sr.getErrors()) 
                            {
                              billlog.Error_Message__c='The following error has occured while inserting Line items:'+err.getStatusCode() + ': ' + err.getMessage();
                              billlog.Error_Message__c=billlog.Error_Message__c+'Line item Fields that affected this error: ' + err.getFields();
                              billlog.Object_name__c='Opportunity Product';
                              errorlog.add(billlog);
                              //insert billlog;
                            }
                        }
                    
                         if (sr.isSuccess()) 
                        {
                             lineidssuccess.put(sr.getId(),sr.isSuccess());
                        }
                }
                  for (Database.SaveResult sr : srList) 
                {
                   if (!sr.isSuccess()) 
                    {
                    Billing_Error_log__c billlog = new Billing_Error_log__c();
                        // Operation failed, so get all errors              
                        for(Database.Error err : sr.getErrors()) 
                        {
                        
                          billlog.Error_Message__c='The following error has occured while inserting opportunity:'+err.getStatusCode() + ': ' + err.getMessage();
                          billlog.Error_Message__c=billlog.Error_Message__c+' Opportunity Fields that affected this error: ' + err.getFields();
                          billlog.Object_name__c='Opportunity';
                          //if(billlog.Id=='')
                          errorlog.add(billlog);
                          //insert billlog;
                        }   
                    }                    
                                        
                } 
        system.debug('errorlog'+errorlog);
        if(errorlog.size()>0)
        {
        insert errorlog;
        }
        
        
                if(lineidssuccess.size()>0)
            {
                    psidsfromlines=[select Id,Patient_Service__c from OpportunityLineItem where Id in: lineidssuccess.keySet()];
                    List<sked__Job__c> jobvalues;
                    List<Patient_Services__c> psvalues;
                    Map<Id,Id> psidmap=new Map<Id,Id>();
                    Map<Id,String> jobidmap=new Map<Id,String>();
                    Integer counterjob=0;
                    if(psidsfromlines.size()>0)
                {
                    for(OpportunityLineItem oitem:psidsfromlines)
                        {
                            psidmap.put(oitem.Id,oitem.Patient_Service__c);
                        }
                  
                    try
                    {
                          psvalues=[select Id, Added_to_Opty__c,Dispensing_Footwear_F049__c,Added_to_Opty_Dispensing_Footwear__c from Patient_Services__c where Id in :psidmap.values()];
                          system.debug('psvalues'+psvalues);
                              for(Patient_Services__c psupdt:psvalues)
                              {                 
                                  psupdt.Added_to_Opty_Dispensing_Footwear__c=true;   
                                  psfinalupd.add(psupdt);
                              }
                         
                         if(psfinalupd.size()>0)
                        {
                         system.debug('psfinalupd'+psfinalupd);
                         update psfinalupd;
                         }
                    }
                    
                    catch(DMLException e)
                    {
                        list<string> emailsjob = new list<string>();
                        Messaging.reserveSingleEmailCapacity(2);
                        Messaging.SingleEmailMessage mailjob = new Messaging.SingleEmailMessage();
                                        htmlBody += 'Dear Admin,';
                                        htmlBody += '<br/><br/>DML Exception Occurred: e.getMessage()';
                                        htmlBody += '<br/><br/>Error Message: ' + e.getMessage() + '. Error Message: e.getMessage()';
                                        htmlBody += '<br/><br/>Regards,<br/><br/>HealthStrong Salesforce Admin</p>';
                                        htmlBody += '</td></tr></table></td></tr></table></td><td width="3" style="background-color:transparent;background-image:url(http://i3.createsend1.com/ti/r/F2/A34/58B/075043/images/main_right.png);background-repeat:repeat-y;background-position:0 0;background-attachment:scroll;" ></td></tr></table> </td></tr></table></body></html>';
                        mailjob.setHtmlBody(htmlBody);
                        emailsjob.add('errorlog@healthstrong.com.au');
                        mailjob.setToAddresses(emailsjob);
                        mailjob.setSaveAsActivity(false); 
                         mailjob.setReplyTo('technicalsupport@healthstrong.com.au');
                        mailjob.setSenderDisplayName('HealthStrong Salesforce Support');
                       mailjob.setSubject('Error Updating the flag Added to Opportunity for the Jobs');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mailjob });
                    }
                 }
            }
           }
                   
         }

    }
due to size limitation i will give by code in below post
Here is my apex class which is call from custom button contan javascript code
global class CreateOpty{

WebService static String CreateOptywithps(String Id)
{
List<Patient_Services__c> ps= new List<Patient_Services__c>();
List<Rate_Card__c> rcard=new List<Rate_Card__c>();
List<sked__Job__c> joblist=new List<sked__Job__c>();
List<sked__Job__c> joblistnw=new List<sked__Job__c>();
Set<OpportunityLineItem> olilist=new Set<OpportunityLineItem>();
List<OpportunityLineItem> olilist1=new List<OpportunityLineItem>(); 
List<Opportunity> oplist=new List<Opportunity>();
List<Account> accname = new List<Account>();
Integer extid;
String RecNamePodwP,RecNameAudwP,RecNameDiteticscwP,RecNameDivTrpwP,RecNameMntHlthwP,RecNameOccTrpwP,RecNameOptmwP,RecNamePhytrpwP,RecNamePhyTrpExClswP,RecNameRegNrsewP,RecNameSpchTrpwP;
String myeffDate = date.today().format();
Date Nxtoptycreationdate,Closedate;
String BillableCycle,InvoiceSentby,InvoiceSentTo,Accntterms,RateCardtype;
List<Patient_Services__c> psupdlist= new List<Patient_Services__c>();
Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe() ;
Map<String,Schema.RecordTypeInfo> recordType = sObjectMap.get('Opportunity').getDescribe().getRecordTypeInfosByName();
ID RtIdPodwP,RtIdAudwP,RtIdDiteticscwP,RtIdDivTrpwP,RtIdMntHlthwP,RtIdOccTrpwP,RtIdOptmwP,RtIdPhytrpwP,RtIdPhyTrpExClswP,RtIdRegNrsewP,RtIdSpchTrpwP;

User vLstUserop = [select id from User where Opportunity_Owner__c=true and IsActive=true LIMIT 1];

ps=[select id,Medicare_Account__c,Emergency_Visit__c,DVA_Code__c,Patient_DVA_Number__c,Patient_Medicare_No__c,Podiatry_Services__c,Job_Start_Datew_otime__c,Dispensing_Footwear_F049__c,DVA_Account__c,Initial_Consultation__c,Subsequent_Consulation__c,RecordType.name,Patient__r.Medicare_Account__c,Patient__r.Medicare_Account__r.Name,Patient__r.DVA_Account__c,Patient__r.DVA_Account__r.Name,Who_to_Invoice__c,Patient_Service_Lunch__c,Patient_Service_Invoice_Duration__c,Job_allocation_count__c,Job_Invoice_Start__c,Job_Invoice_Finish__c,Lunch_Break_Duration_from_Job__c,Job_Billable__c,Job__c,Patient_Service_Invoice_Finish__c,Patient_Service_Invoice_Start__c,Job_Type__c,Resource_Name__c,Service_Type__c from Patient_Services__c where id=:ID ];

joblistnw=[Select id,name,Facility_Patient_Sevices_Count__c,Day_count__c,Added_to_Opportunity__c,Opportunity_Id__c,Job_Start_Datew_otime__c,Job_Finish_Datew_otime__c,Lunch_Break_Duration__c,Job_Invoiced__c,sked__Type__c,sked__Account__c,
Resource_Name__c,sked__Job_Allocation_Count__c,Invoice_Finish__c, Invoice_Duration__c,
Invoice_Start__c,Job_Billable__c,sked__Duration__c from sked__Job__c 
where id=:ps[0].Job__c];

String medaccId = ps[0].Patient__r.Medicare_Account__c;
String MedaccName=ps[0].Patient__r.Medicare_Account__r.Name;
String DVAaccId = ps[0].Patient__r.DVA_Account__c;
String DVAaccName=ps[0].Patient__r.DVA_Account__r.Name;

// Check Record type and assing Id and Name to Variable
if(ps[0].RecordType.name =='Podiatry')
{     RtIdPodwP = recordType.get('Podiatry with Patients').getRecordTypeId();
	  RecNamePodwP=recordType.get('Podiatry with Patients').getName();
}
else if(ps[0].RecordType.name =='Audiology')
     {	RtIdAudwP = recordType.get('Audiology with Patients').getRecordTypeId();
        RecNameAudwP=recordType.get('Audiology with Patients').getName();
      }
	  
else if(ps[0].RecordType.name =='Dietetics')
    {		RtIdDiteticscwP = recordType.get('Dietetics with Patients').getRecordTypeId();
           RecNameDiteticscwP=recordType.get('Dietetics with Patients').getName();
    }
	
else if(ps[0].RecordType.name =='Diversional Therapy')
    { 	RtIdDivTrpwP = recordType.get('Diversional Therapy with Patients').getRecordTypeId();
        RecNameDivTrpwP=recordType.get('Diversional Therapy with Patients').getName();
    }
	
if(ps[0].Who_to_Invoice__c=='Medicare Account')
    {
    rcard=[Select id,Next_Opportunity_Creation_Date__c,Which_Rate_to_use_withpatients__c,Footwear_Dispensed__c,Emergency_Visit__c,PricebookEntryId__c,Job_Type__c,Assessment__c,Travel__c,Report__c,Treatment_Rate__c,Menu_Review__c,Hourly_Rate__c,Other__c,Next_Billable_Date__c,Opportunity_Creation_Frequency__c,Invoice_sent_by__c,Invoice_sent_to__c,Account_Terms__c,Rate_Card_Type__c from Rate_Card__c where Account_Name__c='Department of Human Services' AND Job_Type__c=:ps[0].Job_Type__c AND Rate_Card_Type__c=:ps[0].Service_Type__c ];
    }
else
    {
    rcard=[Select id,Next_Opportunity_Creation_Date__c,Which_Rate_to_use_withpatients__c,Footwear_Dispensed__c,Emergency_Visit__c,PricebookEntryId__c,Job_Type__c,Assessment__c,Travel__c,Report__c,Treatment_Rate__c,Menu_Review__c,Hourly_Rate__c,Other__c,Next_Billable_Date__c,Opportunity_Creation_Frequency__c,Invoice_sent_by__c,Invoice_sent_to__c,Account_Terms__c,Rate_Card_Type__c from Rate_Card__c where Account_Name__c='Department of Veteran Affairs' AND Job_Type__c=:ps[0].Job_Type__c AND Rate_Card_Type__c=:ps[0].Service_Type__c];
    }
    
List<Opportunity> opty=[select Id,Opty_No__c from Opportunity order by CreatedDate DESC limit 1];
for(Opportunity oppty:opty)
    {
    extid=Integer.valueOf(oppty.Opty_No__c)+1;
    }
    
	//Create opportunity and opportunity line item
    if(rcard.size()>0 && joblistnw.size()>0 && ps.size()>0)
    {
    Opportunity newopp =new Opportunity();
    if(ps[0].Who_to_Invoice__c=='Medicare Account')
    newopp.Optycreationbatch__c='Medicare-WP-'+myeffDate+'-'+extid;
    if(ps[0].Who_to_Invoice__c=='DVA Account')
     newopp.Optycreationbatch__c='DVA-WP-'+myeffDate+'-'+extid;
     if(ps.size()>0)
        {
				for(Patient_Services__c pslines:ps)
              {
              OpportunityLineItem oli = new OpportunityLineItem();
						oli.Opportunity =new Opportunity(Optycreationbatch__c=newopp.Optycreationbatch__c);
                        oli.PriceBookEntryId = rcard[0].PricebookEntryId__c;
                        oli.Patient_Service__c=pslines.Id;
                        oli.Provider_Name__c=pslines.Resource_Name__c;
                        oli.Patient_Service_Invoice_Start__c=pslines.Patient_Service_Invoice_Start__c;
                        oli.Patient_Service_Invoice_Finish__c=pslines.Patient_Service_Invoice_Finish__c;
                        oli.Rate_Card__c=rcard[0].Id;
                        oli.UnitPrice = rcard[0].Hourly_Rate__c;
                        oli.Quantity = pslines.Job_allocation_count__c;
                        oli.Patient_Service_Lunch__c=pslines.Patient_Service_Lunch__c;
                        oli.Invoice_Start__c=pslines.Job_Invoice_Start__c;
                        oli.Invoice_Finish__c=pslines.Job_Invoice_Finish__c;
                        oli.Lunch_Break_Duration_from_Job__c=pslines.Lunch_Break_Duration_from_Job__c;
                        oli.DVA_Code__c=pslines.DVA_Code__c;
                        oli.AHP_Type__c=pslines.Podiatry_Services__c;
                    
                     if(pslines.Job_Billable__c ==true)
                     {
                        oli.Job_lkup__c=pslines.Job__c;
                        if(pslines.Emergency_Visit__c == true)
                        {
                            oli.UnitPrice = rcard[0].Emergency_Visit__c;
                            oli.Quantity = pslines.Job_allocation_count__c;
                        }
                          if(pslines.Dispensing_Footwear_F049__c == true)
                        {
                            oli.UnitPrice = rcard[0].Footwear_Dispensed__c;
                            oli.Quantity = pslines.Job_allocation_count__c;
                        }
                         if(pslines.Who_to_Invoice__c=='DVA Account' && pslines.Service_Type__c=='Podiatry' && pslines.Initial_Consultation__c==true && pslines.Subsequent_Consulation__c==true)
                        {
                              oli.UnitPrice = rcard[0].Assessment__c;
                              oli.Quantity = pslines.Job_allocation_count__c;
                        }
                     else
                        {   
                            if(rcard[0].Which_Rate_to_use_withpatients__c=='Always use Treatment Rate')
                             {
                                 oli.UnitPrice = rcard[0].Treatment_Rate__c;
                                 oli.Quantity = pslines.Job_allocation_count__c;
                             }
                           else if(rcard[0].Which_Rate_to_use_withpatients__c=='Always use Menu Review Rate')
                             {
                                 oli.UnitPrice = rcard[0].Menu_Review__c;
                                 oli.Quantity = pslines.Job_allocation_count__c;
                             }
                        }                       
                    }
                     else
                     {
                        oli.Job_lkup__c=pslines.Job__c;
                        oli.Quantity = pslines.Job_Invoice_Duration__c; 
                        oli.UnitPrice=0;
                     }
						if( (oli.Quantity!=NULL) && (oli.PriceBookEntryId!=NULL))
                        {	olilist1.add(oli);
                             psupdlist.add(pslines);
                         
                        }
             }}
           if(psupdlist.size()>0)
                {
                      newopp.OwnerId=vLstUserop.Id;
                      newopp.stagename='To be reviewed';
                      Nxtoptycreationdate=rcard[0].Next_Opportunity_Creation_Date__c;
                      Closedate=rcard[0].Next_Billable_Date__c;
                      BillableCycle=rcard[0].Opportunity_Creation_Frequency__c;
                      InvoiceSentby=rcard[0].Invoice_sent_by__c;
                      InvoiceSentTo=rcard[0].Invoice_sent_to__c;
                      Accntterms=rcard[0].Account_Terms__c;
                      RateCardtype=rcard[0].Rate_Card_Type__c;
                 }
                      
                 if(ps[0].Who_to_Invoice__c=='Medicare Account')   
                {
                    newopp.Medicare__c = true;
                    newopp.AccountId=medaccId ;
					//Check record type and assign respective name to oppty
                    if(ps[0].RecordType.name =='Podiatry')
                        newopp.Name= MedaccName +'-' + RecNamePodwP + '-'+ Nxtoptycreationdate.format();
               else if(ps[0].RecordType.name =='Audiology')
                        newopp.Name= MedaccName +'-' + RecNameAudwP + '-'+ Nxtoptycreationdate.format();
               else if(ps[0].RecordType.name =='Dietetics')
                        newopp.Name= MedaccName +'-' + RecNameDiteticscwP + '-'+ Nxtoptycreationdate.format();
                if(ps[0].RecordType.name =='Diversional Therapy')
                        newopp.Name= MedaccName +'-' + RecNameDivTrpwP + '-'+ Nxtoptycreationdate.format();
              }
                  
               if(ps[0].Who_to_Invoice__c=='DVA Account')
              {
                    newopp.DVA__c = true;
                    newopp.AccountId=DVAaccId ;
                if(ps[0].RecordType.name =='Podiatry')
                        newopp.Name= DVAaccName  +'-' + RecNamePodwP + '-'+ Nxtoptycreationdate.format();
               else if(ps[0].RecordType.name =='Audiology')
                        newopp.Name= DVAaccName  +'-' + RecNameAudwP + '-'+ Nxtoptycreationdate.format();
               else if(ps[0].RecordType.name =='Dietetics')
                        newopp.Name= DVAaccName  +'-' + RecNameDiteticscwP + '-'+ Nxtoptycreationdate.format();
                if(ps[0].RecordType.name =='Diversional Therapy')
                        newopp.Name= DVAaccName  +'-' + RecNameDivTrpwP + '-'+ Nxtoptycreationdate.format();
              }
                  
                 newopp.closedate=Closedate;
                  newopp.Billable_Cycle__c=BillableCycle;
                  
                  //check Patient service Record type and assign respective record type id to oppty
                    if(ps[0].RecordType.name =='Podiatry')
                        newopp.RecordTypeId=RtIdPodwP ;
               else if(ps[0].RecordType.name =='Audiology')
                        newopp.RecordTypeId=RtIdAudwP ;
               else if(ps[0].RecordType.name =='Dietetics')
                        newopp.RecordTypeId=RtIdDiteticscwP ;
               else if(ps[0].RecordType.name =='Diversional Therapy')
                        newopp.RecordTypeId=RtIdDivTrpwP ;
               
                    /////////////////////
                  
                 newopp.RateCard__c=rcard[0].Id;
                  newopp.Invoice_sent_by__c=InvoiceSentby;
                  newopp.Invoice_sent_to__c=InvoiceSentTo;
                  newopp.Date_From__c=ps[0].Job_Start_Datew_otime__c;
                  newopp.Patient_DVA_No__c = ps[0].Patient_DVA_Number__c;
                  newopp.Patient_Medicare_No__c = ps[0].Patient_Medicare_No__c;
                  newopp.AHP_Type__c= ps[0].Podiatry_Services__c;
                  newopp.Date_To__c=Nxtoptycreationdate;
                  newopp.Service_Type__c=RateCardtype;
                  oplist.add(newopp);
                  psupdlist.clear();
                              
    }
	if(olilist1.size()>0 && oplist.size()>0)
    {
        insert oplist;
        insert olilist1;          
return (medaccId );
}}
And below in test class,as per my knowledge i've created test class and try to cover few apex code line, but it not showing me any test code coverage,
as I am creating test class in correct way or wrong way ? Please guide
Please explain solution and how to write test class for this in brief
 
@Istest(SeeAllData=True)
public class TestCreateOpty3 {
    Static testmethod void CreateOptyTest1()
    {
        Integer extid;
        User vLstUserop = [select id from User where Opportunity_Owner__c=true and IsActive=true LIMIT 1];
          date myDate = date.today();
        Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe() ;
            Map<String,Schema.RecordTypeInfo> recordType = sObjectMap.get('Opportunity').getDescribe().getRecordTypeInfosByName();
            ID RtIdPodwP,RtIdAudwP,RtIdDiteticscwP,RtIdDivTrpwP,RtIdMntHlthwP,RtIdOccTrpwP,RtIdOptmwP,RtIdPhytrpwP,RtIdPhyTrpExClswP,RtIdRegNrsewP,RtIdSpchTrpwP;
            String RecNamePodwP,RecNameAudwP,RecNameDiteticscwP,RecNameDivTrpwP,RecNameMntHlthwP,RecNameOccTrpwP,RecNameOptmwP,RecNamePhytrpwP,RecNamePhyTrpExClswP,RecNameRegNrsewP,RecNameSpchTrpwP;       
        RtIdPodwP = recordType.get('Podiatry with Patients').getRecordTypeId();
        RecNamePodwP=recordType.get('Podiatry with Patients').getName();
        RtIdAudwP = recordType.get('Audiology with Patients').getRecordTypeId();
        RecNameAudwP=recordType.get('Audiology with Patients').getName();
        Id MedicareAccRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Medicare Account').getRecordTypeId();                
        
        List<Account> Parentacc= new List<Account>();
        
       Parentacc.add(new Account(RecordTypeId = MedicareAccRecordTypeId, 
                                          Name = 'Department of Human Services',
                                          Account_Address__c = '123 street 123', 
                                          ABN__c = '1236523652',
                                          Email__c = 'test1@test.com', 
                                          Facility_Notification_Opt_Out__c = True,
                                          Is_Admin__c = True,
                                          Active__c = True));
      insert Parentacc;
        
         List<Contact> Con= new List<Contact>();
        Con.add(new contact(FirstName = '',
                              LastName = 'TestContact',
                              accountId = Parentacc[0].id,
                              MobilePhone = '1234567890',
                              email = 'test@skedulo.com',
                              MailingStreet = 'ABC',
                              Active__c = True,
                              MailingCity = 'ABC',
                              MailingState = 'ABC',
                              MailingPostalCode = 'ABC',
                              MailingCountry = 'ABC'));
            insert Con;
            
          Parentacc[0].Account_Contact__c = con[0].id;
          update Parentacc;
        
         List<Account>  acc= new List<Account>();
         acc.add(new Account(RecordTypeId = MedicareAccRecordTypeId,         
                                    Name = 'Medicare Account',
                                    ParentId=Parentacc[0].Id,
                                    Account_Address__c = '123 street 123',
                                    ABN__c = '12345678912',
                                    Email__c = 'test@test.com',
                                    Facility_Notification_Opt_Out__c = True,
                                    Medicare_Number__c = '123456789',
                                    Is_Admin__c = True,
                                    Active__c = True,
                                    Card_Expiry_Date__c = system.today().addDays(10)));
           insert acc; 
        
         sked__Region__c Reg = new sked__Region__c(Name='SYD');
         Reg.sked__Timezone__c='Australia/Sydney';
         insert Reg;
        
         sked__Location__c Loc = new sked__Location__c( Name = 'Test Location',sked__Region__c = Reg.Id,sked__Address__c = 'Test Address' );
         insert Loc;
        
         sked__Resource__c Res = new sked__Resource__c(Name = 'Test Resource', sked__User__c=UserInfo.getUserId(),sked__Primary_Region__c = Reg.Id);
         insert Res;
        
         Patient__c pat1 = new Patient__c(First_Name__c='First', Last_Name__c='Last',Medicare_Account__c=acc[0].id, Location__c=Loc.Id, Patient_Status__c='Active');
         Patient__c[] pat = new Patient__c[]{pat1};     
         insert pat;
        
        List<sked__Job__c> job=new List<sked__Job__c>();         
        job.add(new sked__Job__c(skdate__Finish__c = '20/08/2014 8:30 AM',
                                            skdate__Start__c = '18/08/2014 8:30 AM',
                                            Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM'),
                                            Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM'),
                                            sked__Duration__c = 501,
                                            sked__Region__c = Reg.Id,
                                            sked__Type__c='Podiatry Clinic',
                                            Job_Billable__c =true,
                                            Resource_Name__c=Res.Name));
         
         job.add(new sked__Job__c(skdate__Finish__c = '20/08/2014 8:30 AM',
                                            skdate__Start__c = '18/08/2014 8:30 AM',
                                            Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM'),
                                            Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM'),
                                            sked__Duration__c = 501,
                                            sked__Region__c = Reg.Id,
                                            sked__Type__c='Audiology Clinic',
                                            Job_Billable__c =true,
                                            Resource_Name__c=Res.Name));
            
         insert job;
        
         List<Patient_Services__c> ps= new List<Patient_Services__c>();
         ps.add(new Patient_Services__c(Service_Type__c = 'Podiatry',
                                                Patient__c = pat1.Id,
                                                Job__c = job[0].id,
                                                Who_to_Invoice__c='Medicare Account',
                                                RecordTypeid= '01290000000hN0p',
                                                Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM'),
                                                Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM'),
                                                Patient_Service_Lunch__c='10'));
         ps.add(new Patient_Services__c(Service_Type__c = 'Audiology',
                                                Patient__c = pat1.Id,
                                                Job__c = job[1].id,
                                                Who_to_Invoice__c='Medicare Account',
                                                RecordTypeid= '012O000000011Im',
                                                Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM'),
                                                Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM'),
                                                Patient_Service_Lunch__c='10'));
                
        insert ps;
        
         List<PricebookEntry > Pricebook=new List<PricebookEntry >();
        Pricebook =[select id from PricebookEntry where IsActive=true limit 1];
         List<Rate_Card__c> rcard=new List<Rate_Card__c>();    
        rcard.add(new Rate_Card__c(Is_Active__c=true,
                                    Rate_Card_Type__c='Podiatry',
                                    Job_Type__c='Podiatry Clinic',
                                    Invoice_sent_by__c='Email',
                                    Invoice_sent_to__c='Account',
                                    PricebookEntryId__c= Pricebook[0].id,
                                    Treatment_Rate__c=100.00,
                                    Account__c = acc[0].Id,
                                    Which_Rate_to_use_withpatients__c='Always use Treatment Rate',
                                    Next_Opportunity_Creation_Date__c=date.parse('18/08/2016')));
        
       
        rcard.add(new Rate_Card__c(Is_Active__c=true,
                                    Rate_Card_Type__c='Audiology',
                                    Job_Type__c='Audiology Clinic',
                                    Invoice_sent_by__c='Email',
                                    Invoice_sent_to__c='Account',
                                    PricebookEntryId__c= Pricebook[0].id,
                                    Treatment_Rate__c=100.00,
                                    Account__c = acc[0].Id,
                                    Which_Rate_to_use_withpatients__c='Always use Treatment Rate',
                                    Next_Opportunity_Creation_Date__c=date.parse('18/08/2016')));
         insert rcard;
        
         List<Opportunity> opty=[select Id,Opty_No__c from Opportunity order by CreatedDate DESC limit 1];
         extid=Integer.valueOf(opty[0].Opty_No__c)+1;
       
        List<Opportunity> newopp=new List<Opportunity>();
         newopp.add(new Opportunity(
         			Optycreationbatch__c='Medicare-WP-'+myDate+'-'+extid,
                     OwnerId=vLstUserop.Id,
                     stagename='To be reviewed',
                     Medicare__c = true,
                     AccountId=acc[0].Id ,
                     Name=  acc[0].Name +'-' + 'Podiatry with Patients' + '-'+ myDate.format(),
                     Invoice_sent_by__c=rcard[0].Invoice_sent_by__c,
                     Invoice_sent_to__c=rcard[0].Invoice_sent_to__c,
                     closedate=myDate,
                     AHP_Type__c= ps[0].Podiatry_Services__c,
                     Date_To__c=rcard[0].Next_Opportunity_Creation_Date__c,
                     Service_Type__c= rcard[0].Rate_Card_Type__c,
                     RecordTypeId=RtIdPodwP,
                     RateCard__c=rcard[0].Id));
        
        newopp.add(new Opportunity(
            						Optycreationbatch__c='Medicare-WP-'+myDate+'-'+extid+1,
                                     OwnerId=vLstUserop.Id,
                                     stagename='To be reviewed',
                                     Medicare__c = true,
                                     AccountId=acc[0].Id ,
                                     Name=  acc[0].Name +'-' + 'Audiology with Patients' + '-'+ myDate.format(),
                                     Invoice_sent_by__c=rcard[0].Invoice_sent_by__c,
                                     Invoice_sent_to__c=rcard[0].Invoice_sent_to__c,
                                     closedate=myDate,
                                     AHP_Type__c= ps[1].Podiatry_Services__c,
                                     Date_To__c=rcard[0].Next_Opportunity_Creation_Date__c,
                                     Service_Type__c= rcard[0].Rate_Card_Type__c,
                                     RecordTypeId=RtIdAudwP,
                                     RateCard__c=rcard[0].Id));
        insert newopp;
                
        List<OpportunityLineItem> oli = new List<OpportunityLineItem>();
          oli.add(new OpportunityLineItem(
                                         OpportunityId =newopp[0].id,
                                         PriceBookEntryId = rcard[0].PricebookEntryId__c,
                                         Provider_Name__c=ps[0].Resource_Name__c,  
                                         Patient_Service__c=ps[0].Id,
                                         Rate_Card__c=rcard[0].Id,
                                         Patient_Service_Invoice_Start__c=ps[0].Patient_Service_Invoice_Start__c,
                                         Patient_Service_Invoice_Finish__c=ps[0].Patient_Service_Invoice_Finish__c,
                                         Patient_Service_Lunch__c=ps[0].Patient_Service_Lunch__c,
                                         UnitPrice = rcard[0].Treatment_Rate__c,
                                         Invoice_Start__c=ps[0].Job_Invoice_Start__c,
                                         Invoice_Finish__c=ps[0].Job_Invoice_Finish__c,
                                         Lunch_Break_Duration_from_Job__c=ps[0].Lunch_Break_Duration_from_Job__c,
                                         AHP_Type__c=ps[0].Podiatry_Services__c,
                                         Quantity = 1,
                                         Job_lkup__c=ps[0].Job__c)
                                         );
       oli.add(new OpportunityLineItem(
                 OpportunityId =newopp[1].id,
                 PriceBookEntryId = rcard[1].PricebookEntryId__c,
                Provider_Name__c=ps[1].Resource_Name__c,  
                 Patient_Service__c=ps[1].Id,
                 Rate_Card__c=rcard[1].Id,
                 Patient_Service_Invoice_Start__c=ps[1].Patient_Service_Invoice_Start__c,
                 Patient_Service_Invoice_Finish__c=ps[1].Patient_Service_Invoice_Finish__c,
                 Patient_Service_Lunch__c=ps[1].Patient_Service_Lunch__c,
                 UnitPrice = rcard[1].Treatment_Rate__c,
                 Invoice_Start__c=ps[1].Job_Invoice_Start__c,
                 Invoice_Finish__c=ps[1].Job_Invoice_Finish__c,
       			 Lunch_Break_Duration_from_Job__c=ps[1].Lunch_Break_Duration_from_Job__c,
       			 AHP_Type__c=ps[1].Podiatry_Services__c,
                 Quantity = 1,
                 Job_lkup__c=ps[1].Job__c));
          insert oli;
        }}


 
I,ve one Parent object 'Patient'  and Child Object 'Patient Services' and another Parent object 'Job'
On Patient Services Object one Look up field Named Patient related to Patient object & another lookup field Named job related to job object
The Location Field  on both object Patient and Job.
When adding a Patient Service from the Patient object; then the Job field lookup should filter based on the Location of the Patient.
User-added image

When I click on Job lookup field icon, it allow to show me only record that has location field is equal to  location field of Patient record Patient 000972 in above image.
How to configure in look filter Please help
I am integration salesforce with SAP system using SOAP API. SAP Provided the Username and Password. So I have created a NamedCreditials in salesforce and used that in my apex class as endpoint.

like 
public String endpoint_x ='callout:SAP_Callout';

AS per salesforce doc https://help.salesforce.com/HTViewSolution?id=000003652 we have whitelisted the Salesforce IP ranges in Firewall on SAP End.
But during callout, still we are getting Error,

System.Callout Exception Unexpected end of file from server

Named Credentials: http://prntscr.com/l28ba7 

Snapshot of IP ranges which is configured in firewall.

User-added imageUser-added imageUser-added imageUser-added image
Hi All,
I am having a Teacher Object with fields(Email,Phone,Name) and all those records are retrived in VisualForce Page with an edit button added manullay. Now, if any record field is edited then an approval process must run and after an approval the respective record field must be updated.

Is this Possible by Standard Feature of approval process or do i need to have a custom approval process if so please help me with the code
Thanks in Advance 
Geetham
Hi,

1. I do have one picklist field which has values as YES, NO, and NA as the default value. 

2. I do also have a multipicklist field which has random values. 

Requirement: When I select the picklist value with NO, the multi picklist should be visible otherwise, if I select YES and default value NA the multi picklist shouldn't be visible. Your help is really appreciated.

Thanks
Ravi.
Hi All,

I'm a new admin and do not have any developer experience, so any help would be greatly appreciated!

I've added new tasks to an existing apex class button and it works perfectly in my sandbox instance but when I validate the change in production before deployment I received the following error code:

System.AssertException: Assertion Failed 
Stack Trace: Class.TestCreateOnboardingTasks.verifyTasksCreated: line 51, column 1

This is line 45-59 in my apex class:

Task t = new Task();
        t.WhatId = accountID;
        t.WhoId = champion.Id;
        t.Subject = 'Onboarding: Day 7';
        t.ActivityDate = a.Subscription_Start_Date__c.addDays(7);
        t.OwnerId = a.OwnerId;
        insert t;
        
        t = new Task();
        t.WhatId = accountID;
        t.WhoId = champion.Id;
        t.Subject = 'Onboarding: Day 15';
        t.ActivityDate = a.Subscription_Start_Date__c.addDays(15);
        t.OwnerId = a.OwnerId;
        insert t;

Any ideas on what to do for it to pass the validation test?
Hi All,

How can i link my VF Save button to a URL so that when a record in saved in my form, the user is redirectd to "www.google.com". Ive tried looking on different forms but other situations is always different to mine. Thanks for your help!

his is a snippet of my code.




<apex:page standardController="Turndown__c" sidebar="false" showHeader="true" extensions="pagereference" >
    <apex:form >
           <apex:pageBlock title="Documented Turndowns" id="turndown_list">
            
             <apex:pageBlockSection columns="1" >
                    <!-- to remove the header, but keep the fields' help texts -->
                         <style type="text/css">
                             .bPageHeader {display: none;}
                             </style>
                    
                                            <!-- Inputfields --> 
                                <apex:inputfield value="{! Turndown__c.Account__c }"/>
                                <apex:inputfield value="{! Turndown__c.Phone_Number__c }"/>
                                <apex:inputfield value="{! Turndown__c.Region__c }"/>

              
                 
                   </apex:pageBlockSection>
                        <apex:pageBlockButtons >  
                  
                                        <apex:commandButton action="{!Save}" value="Save"  />
 
                        </apex:pageBlockButtons>       


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

     
             
                                            
Thanks again!             
 
dd

Please find the error which i am getting in test class : Field is not writeable: OpportunityLineItem.ProductCode at line 30 column 35  and suggest me how to resolve this.
Hi All

How can i merge two triiger in a single trigger on a perticular object.
I have created two trigger but not working at a time both trigger(one is working only ).so how to merge this two trigger on a single trigger.
 
trigger CreateOpportunity on Boutique__c (after insert , after update) {
    
    List<Opportunity> opps = new List<Opportunity>();

    for (Boutique__c boutique : Trigger.new) {
        
        if((boutique.Visit_Type__c == 'Browsing' || boutique.Visit_Type__c == 'Enquiry') 
            && boutique.LeadType__c== 'Regular'
            && String.isNotBlank(boutique.Opportunity_Name__c)) {

            Opportunity childOpp                        = new Opportunity();
                        childOpp.Boutique__c            = boutique.Id;
                        childOpp.Name                   = boutique.Opportunity_Name__c;
                        childOpp.StageName              = 'Invitation';
                        childOpp.CloseDate              = System.Today()+150;
                        childOpp.Contact__c             = boutique.Customer_Name__c;
                        childOpp.Amount                 = boutique.Amount__c;
                        childOpp.AccountId              = '0012800001J3sMRAAZ';
                        childOpp.Assisted_By__c         = boutique.Assisted_By_Look_Up__c;
                        childOpp.Budget_Range__c        = boutique.Budget_Range__c;
                        childOpp.Stone__c               = boutique.Stone__c;
                        childOpp.Shadow_Assistance__c   = boutique.Shadow_Assistance_Look_Up__c;
                        childOpp.Visit_Type__c          = boutique.Visit_Type__c;
                        //childOpp.Enquiry_Details__c     = boutique.Enquiry_Details__c;
                        childOpp.Enquiry_Details1__c     = boutique.Enquiry_Details__c;
                        childOpp.FullName__c            = boutique.Customer_Name__c;

            opps.add(childOpp);    
        } 
    }  
        
    if (!opps.isEmpty()) 
        insert opps;
}
 
Trigger ContactCountTrigger on Boutique__c(After insert,After Delete,After Undelete)
{
  Set<Id> setAccountIds = new Set<Id>();
  
  //Whenever your working with After Undelete operation you can access data through 
  //Trigger.new or Trigger.newMap but not with Trigger.old or Trigger.oldmap variables
  if(Trigger.isInsert || Trigger.isUndelete)
  {
   for(Boutique__c con : Trigger.new)
   {
    setAccountIds.add(con.Customer_Name__c);
   }
  }
  
  if(Trigger.isDelete)
  {
   //if you use Trigger.new below in place of Trigger.old you will end up with 
   //System.NullPointerException:Attempt to de-reference a null object
   for(Boutique__c con : Trigger.old) 
   {
    setAccountIds.add(con.Customer_Name__c);
   }
  }
  
 List<Contact> listAccs = [Select id,name,Total_Visit__c,(Select id from Boutiques__r) from Contact where Id in : setAccountIds];
  for(Contact acc :listAccs)
  {
   acc.Total_Visit__c = acc.Boutiques__r.size();
  }
  update listAccs;
}

 

Hi,

I have created a Trigger and used Helper class in the trigger and created the Test Class which is covering 96% of helper class but when I am trying to deploy the code then it is showing 20% code coverage bcoz of which I am unable to deploy the code. Can anyone help?

 

Trigger

trigger lead_agent_trigger on Lead (before insert,before Update) 
    {   
    
    Lead_Agent_Trigger_Helper.Agent(trigger.new);
    
        
    }

Helper Class:-

public class Lead_Agent_Trigger_Helper {

public void Agent(List<Lead> Leads)
{
    for(Lead loopVar : Leads)
    {
        try
        {
            string country = loopVar.Country;
            //Agents__c agent = [select Id,Agent_Name__c,agent_email__c  from Agents__c where Country__c like : country and Active__c = True and Edition__c =: loopVar.Edition__c limit 1];
            if(loopVar.Sent_to_Agent__c==true)
           {
                if(loopVar.Sector_show__c == null && loopVar.Sectors__c == null)
                {
                    Agents__c agent = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c where 
                                       Country__c like : country and 
                                       Active__c = True and 
                                       Edition__c =: loopVar.Edition__c and
                                       Sector_show__c = null and
                                       Sectors__c = null limit 1];
                    loopVar.Agent__c = agent.Agent_Name__c;
                    loopVar.agent_email__c= agent.agent_email__c;
                    
                    Contact contact = [select AccountId,Email from Contact where Id =: agent.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact.AccountId;
                    loopVar.Agents__c = agent.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }
                else if(loopVar.Sector_show__c != null && loopVar.Sectors__c != null)
                {
                    String sector = loopVar.Sectors__c;
                    Agents__c agent1 = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c 
                                        where Country__c like : country 
                                        and Active__c = True and Edition__c =: loopVar.Edition__c 
                                        and Sector_show__c =: loopVar.Sector_show__c
                                        and Sectors__c  Includes (:sector) limit 1];
                    loopVar.Agent__c = agent1.Agent_Name__c;
                    loopVar.agent_email__c= agent1.agent_email__c;
                    
                    Contact contact1 = [select AccountId,Email from Contact where Id =: agent1.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact1.AccountId;
                    loopVar.Agents__c = agent1.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }           
            }
        }
        
        catch(Exception E){}
}
}
}

 

Test Class:-

public class Lead_Agent_Trigger_Helper {

public void Agent(List<Lead> Leads)
{
    for(Lead loopVar : Leads)
    {
        try
        {
            string country = loopVar.Country;
            //Agents__c agent = [select Id,Agent_Name__c,agent_email__c  from Agents__c where Country__c like : country and Active__c = True and Edition__c =: loopVar.Edition__c limit 1];
            if(loopVar.Sent_to_Agent__c==true)
           {
                if(loopVar.Sector_show__c == null && loopVar.Sectors__c == null)
                {
                    Agents__c agent = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c where 
                                       Country__c like : country and 
                                       Active__c = True and 
                                       Edition__c =: loopVar.Edition__c and
                                       Sector_show__c = null and
                                       Sectors__c = null limit 1];
                    loopVar.Agent__c = agent.Agent_Name__c;
                    loopVar.agent_email__c= agent.agent_email__c;
                    
                    Contact contact = [select AccountId,Email from Contact where Id =: agent.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact.AccountId;
                    loopVar.Agents__c = agent.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }
                else if(loopVar.Sector_show__c != null && loopVar.Sectors__c != null)
                {
                    String sector = loopVar.Sectors__c;
                    Agents__c agent1 = [select Id,Agent_Name__c,agent_email__c,Sector_show__c,Sectors__c from Agents__c 
                                        where Country__c like : country 
                                        and Active__c = True and Edition__c =: loopVar.Edition__c 
                                        and Sector_show__c =: loopVar.Sector_show__c
                                        and Sectors__c  Includes (:sector) limit 1];
                    loopVar.Agent__c = agent1.Agent_Name__c;
                    loopVar.agent_email__c= agent1.agent_email__c;
                    
                    Contact contact1 = [select AccountId,Email from Contact where Id =: agent1.Agent_Name__c limit 1];
                    loopVar.Agent_Account__c = contact1.AccountId;
                    loopVar.Agents__c = agent1.Id;
                    loopVar.Date_sent_to_Agent__c = date.Today();
                }           
            }
        }
        
        catch(Exception E){}
}
}

Error:-
 Code Coverage Error

 I have a visualforce page and an apex class written. I have added that as the community self registartion page in the community settings.   How do I debug the code using UI?
  • November 20, 2017
  • Like
  • 0
what is the use of Action support in salesforce 
Hi...
ALL
i want to delete Lead Records Based on the company name.But i am facing this Error any one can can support me.
public class DML_Delete 
{    
    
    public static void RecordsDeletefromLead (string StartText)
    {
        
        if(StartText !='Null' && StartText !='')
        {
            StartText +='%';
           Map<id,Lead>  DeleteLead =new Map<id,Lead> ([select id,Company from Lead where Company Like:StartText]);
        }
        if(!DeleteLead.isEmpty())
        {
            delete DeleteLead;
        }        
    } 
}
My apex skill level is not quite there yet and we would like to have this trigger up to best practice standards as we hit the governor limit randomly. How would you simplify this code to reduce soql queries?
 
trigger WorkAssign on VanaHCM__Worker_Assignment__c (after insert, after update) 
{
    if(Trigger.isInsert)
    {
        VanaHCM__Worker_Assignment__c gplObject = new VanaHCM__Worker_Assignment__c(); // This takes all available fields from the required object. 
        Map<String, Schema.SObjectField> mapFields = Schema.SObjectType.VanaHCM__Worker_Assignment__c.fields.getMap(); 
     
   
                string objString =  string.valueOf(gplObject);
                
                for(VanaHCM__Worker_Assignment__c gpl : trigger.new)
                {
                Id hcmID = (Id) gpl.get('VanaHCM__Worker_Assignment__c');
                sObject idObject = [Select VanaHCM__Employee_ID__c From VanaHCM__Worker__c where Id = :hcmID];  
                string vpID = (string) idObject.get('VanaHCM__Employee_ID__c');     
                          
                    for (String str : mapFields.keyset()) 
                    { 
                       
                        if (str == 'VanaHCM__Position__c')
                        {  
                            if (gpl.get('VanaHCM__Position__c') != null)
                            {
                                String val = (string) gpl.get(str);
                                sObject find = [Select Name from VanaHCM__Position__c where Id = :val];
                                string PC = (string) find.get('Name'); 
                                WebServiceCallout.sendNotification(vpID, str, PC, objString);
                        
                                sObject find1 = [Select Insurance_Code__c from VanaHCM__Position__c where Id = :val];
                                string co = (string) find1.get('Insurance_Code__c');
                                    if (co != '')
                                    {
                                        sObject code = [Select Name from Insurance_Code__c where Id = :co];
                                        string name = (string) code.get('Name');
                                        WebServiceCallout.sendNotification(vpID, 'inscode' , name, objString);
                                    }
                            }
                        }   
                        
                        else if (str == 'VanaHCM__Pay_Group_Worker_Assign__c')
                        {
                        
                                String val = (string) gpl.get(str);
                                if (val != null)
                                {
                                    sObject find = [Select Name from VanaHCM__Pay_Group__c where Id = :val];
                                    string PG = (string) find.get('Name');
                                    WebServiceCallout.sendNotification(vpID, str, PG, objString);
                                }
                       
                        }
                        else if (str == 'Craft__c' && gpl.get('VanaHCM__Worker_Event__c') != 'a45500000006KVHAA2')
                        {
                                String val = (string) gpl.get(str);
                                if (val != null)
                                {
                                    sObject find = [Select Name from Craft__c where Id = :val];
                                    String val1 = (string) find.get('Name');
                                    WebServiceCallout.sendNotification(vpID, str, val1, objString);
                                }
                                else
                                {
                                    WebServiceCallout.sendNotification(vpID, str, '', objString);   
                                }
                        
                        }
                        else if (str == 'Class__c' && gpl.get('VanaHCM__Worker_Event__c') != 'a45500000006KVHAA2')
                        {
                                String val = (string) gpl.get(str);
                                if (val != null)
                                {
                                    sObject find = [Select Name from Class__c where Id = :val];
                                    String val1 = (string) find.get('Name');
                                    WebServiceCallout.sendNotification(vpID, str, val1, objString);
                                }
                                else
                                {
                                    WebServiceCallout.sendNotification(vpID, str, '', objString);   
                                }
                        }
                        else if (str == 'VanaHCM__Department__c')
                        {
                                String val = (string) gpl.get(str);
                                if (val != null)
                                {
                                    sObject find = [Select Name from VanaHCM__Department__c where Id = :val];
                                    String val1 = (string) find.get('Name');
                                    WebServiceCallout.sendNotification(vpID, str, val1, objString);
                                }
                        
                        }
                        else if(gpl.get(str) == 'a45500000006KVHAA2')
                        {
                                datetime val = (datetime) gpl.get('VanaHCM__Termination_Date__c');
                                WebServiceCallout.sendNotification3(vpID, 'terminate', val, objString);
                        }
                        else if (gpl.get(str) == 'a45500000006KVJAA2')
                        {
                                datetime val = (datetime) gpl.get('VanaHCM__Effective_Date_Work_Assign__c');
                                WebServiceCallout.sendNotification3(vpID, 'rehire', val, objString);
                        }
                          else if (gpl.get('VanaHCM__Not_Eligible_for_Rehire__c') == 1)
                        {
                               
                           WebServiceCallout.sendNotification(vpID, 'NOrehire', 'Y', objString);
                        }
                       
                       }
                    
                
            }
        
        }
    else if(Trigger.isUpdate)
    {
        VanaHCM__Worker_Assignment__c gplObject = new VanaHCM__Worker_Assignment__c(); // This takes all available fields from the required object. 
        Map<String, Schema.SObjectField> mapFields = Schema.SObjectType.VanaHCM__Worker_Assignment__c.fields.getMap(); 
      
        for(VanaHCM__Worker_Assignment__c gpl : trigger.new)
        {
.....

 
I'm displaying the list of account record on VF page in pageblocktable. Account record will be inline edit on Vf page. Now I've to display the list of realted contact on account record on mouseover/click, In such a way that User can quickly review(read only) the contact without scrolling up/down.
So need a contact list should be visible on mosuseover. Is it possible? or other option.

we can display the realted list of contact below to all account record but in this case user has to scroll down. This it is not satisfy my requirement.
How to integrate outlook and salesforce.

My requirement is, when I received email, I've to add the email attachment to the respective contact record in salesforce.

As standard salesforce for outlook in not supporting. I'm using salesforce classic version.

Please guide.
  • September 21, 2017
  • Like
  • 0
Best Practice : When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.

User-added image


      That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it. 

Thanks #Copy_Steve Molis