• Marek Kosar_
  • NEWBIE
  • 430 Points
  • Member since 2015


  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 61
    Replies
Hello,

I am new for apex classes. I was trying to create a trigger which replicate the account recorded to custom object. All account standard and custom field.

Could someone help me please?

Thanks
 
  • January 28, 2016
  • Like
  • 1
Hi, I am getting nullpointer exception while running below test class.

After inserting both contact and campaign objects only, i am referring them in campaign member object, wondering what i am missing here.
@isTest

public class CampaignMemberTaskcreation {

    Static testmethod void testtask(){

        Contact co1 = new Contact(
        LastName = 'Last',
        Title='CEO');
        
        insert  co1;
        string co1Id = co1.id;

        Campaign ca1 = new Campaign(
            Name = 'Testcampaign',
            Date_Sent__c=Date.today(),
            IsActive = TRUE);
        insert ( ca1 );
        string ca1Id = ca1.id;

        CampaignMember m1 = new CampaignMember();
            m1.Contact.Id = co1.Id; 
            m1.Campaign.Id = ca1.Id;
            m1.status='Responded';
        insert m1;
    }

}



Below is the error
Class CampaignMemberTaskcreation
Method Name testtask
Pass/Fail Fail
Error Message System.NullPointerException: Attempt to de-reference a null object
Stack Trace Class.CampaignMemberTaskcreation.testtask: line 22, column 1
I want to fetch id of contact person associated with an Account. And then use it in VF page.

SOQL
Account ac=[Select id,name,(select id,phone from Contact) where name='xyz' limit 1];
public ID cId;

This line compiles well.
But i don't how to use store contact Id from "ac" to "cId".

Any help would be highly appreciated.
Query:
  • January 27, 2016
  • Like
  • 0
Hi getting the exception when trying to add records on my custom object Position__c

Here is my Controller :


public class InsertByVF{

    public Position__c pos;
    public String positionName{get;set;}
    public Decimal MinimumPay{get;set;}
    public Decimal MaximumPay{get;set;}
    
    public InsertByVF()
    {
    pos=new Position__c();
    
    }
  
    public void doInsert()
    {
 
    pos.Name=positionName;
    pos.Max_Pay__c=MaximumPay;
    pos.Min_Pay__c=MinimumPay;
       
  insert pos;      
       
 }
}


And below is my Apex page code :

<apex:page controller="InsertByVF">
<apex:form >
<apex:pageBlock title="New Position">
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel >Position Name :</apex:outputLabel>
<apex:inputField id="FirstName" value="{!Position__c.positionName}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Max Pay :</apex:outputLabel>
<apex:inputField id="MaxPay" value="{!Position__c.MaximumPay}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Min Pay :</apex:outputLabel>
<apex:inputField id="MinPay" value="{!Position__c.MinimumPay}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton id="Save" action="{!doInsert}" value="Save"/>
<!--<apex:commandButton id="Cancel" action="{!Cancel}" value="Cancel"/>-->
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
 
Hi Everyone,

I would like to know can we return Multiple datatypes from single method in apex, Can anyone please help me .

Thanks.
I've got an Apex class which writes a description text to a case on creation.
Now i want add a date (today()) into the line of text.

Before deploying this to production (and possibly break the case creation process), can anyone tell me if the following line will do the trick ?
 
Description = 'Gegevens: \n\n Ontvangstdatum: + date.today() \n\n nummer:  ' + Code

 
Hi All,

I am writing test class for batch class.........but it covered upto 50 % only ..........Here is batch class 
global class batchAccountUpdateSLA implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
     date d = system.today();   
String query = 'SELECT Id,Name FROM Account where after1day__c = :d
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.SLA__c= 'Gold';            
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

Here is my test class

 
@isTest
 public class batchAccountUpdateSLA_Test{
 Static testmethod void batchAccountUpdateSLA_TestMethod(){
 
 Date d = system.today().addDays(3);
     Account acc = new Account();
     acc.name = 'Test';
     acc.Fax = '12345';
     insert acc;
      Test.StartTest(); 
      batchAccountUpdateSLA bacth = new batchAccountUpdateSLA ();
      ID batchprocessid = database.Executebatch(bacth ); 
      Test.StopTest();
    }
  }
Formula field is After1day code:
DATEVALUE(CreatedDate) + 
CASE( 
MOD(DATEVALUE(CreatedDate)- DATE(1900, 1, 7), 7), 
0, 2, 
1, 1, 
2, 1, 
3, 1, 
4, 1, 
5, 3, 
6, 3, 
0)



Adv thnx
Siv
 
  • January 22, 2016
  • Like
  • 0
Is it possible to create or instantiate a class of a type the is equal to the value of a String?    So something along these lines;

//Normal code
private MynewClass MyNewClass;
MyNewClass = new myNewClass();

// Is something like this possible instead?
private MynewClass MyNewClass;
String tempString = 'MyNewClass';
MyNewClass = new tempString();  //  ie somehow get the value of tempString' as the type of class to create.

cheers
George
Hello, I am working on writing a test class for a custom controller that creates an Account list, and then based on the selected Account's ID, redirects to a new page. I'm new to this so any help would be appreciated. 
Controller:
public without sharing class SDPController {
    public List<Account> PAISchools = new List<Account>();
    public SDPController(){   
    }

    public List<SelectOption> PAIList{
        get{
            PAISchools = [Select Account.Name, Account.Id From Account Where Account.ParentId = '0011700000BZkKR'];
            
            PAIList = new List<SelectOption>();
            
            for(Account temp : PAISchools){
                PAIList.add(new SelectOption(temp.id, temp.Name));
            }
            return PAIList;
        }
        set;    
    }
    
    public String idString{get;set;}
    
    
	public PageReference saveform(){
  		update PAISchools ; // helps in saving the record
  			PageReference pageRef = new PageReference('https://dev2-dor.cs22.force.com/eportfolio/LPRegistration?code='+idString+'');
            	pageRef.setRedirect(true);
            	return pageRef;
	}
    
    public PageReference signin(){
        PageReference signIn = new PageReference('https://dev2-dor.cs22.force.com/eportfolio/motivislp__LPSignIn');
        signIn.setRedirect(true);
        return signIn;
    }
  
        
}

Test class:
@isTest
public class TestSDPController {
    
    public static testMethod void testSDP() {  
       
       Account acc = new Account(name= 'Testing', ParentId= '0011700000BZkKR');
        insert acc;
       
       Test.startTest();
       PageReference testPage = Page.SchoolSelect2;
        Test.setCurrentPage(testPage);
        testPage.getUrl();
        
        SDPController sdp = new SDPController();
        	sdp.saveform();
        Test.stopTest();
        
              
     }

}

Am I at least on the right path?
Have 100% coverage using AnimalLocatorMock.apxc class in my connected org, but got the error when check challenge: 

Challenge Not yet complete... here's what's wrong:
No Apex class named 'AnimalLocatorMock' was found.

Please help!!!
System.JSONException: Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value at [line:1, column:215] 

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\WraPPER Class///////////////////////////////////////////

public class demomailsentwrap {
public String TotalViewCount{get;set;}   
public String echo{get;set;}  
public String TotalRecords{get;set;}    
public String TotalDisplayRecords{get;set;}   
public List<GroupData> GroupData{get;set;}  
public class GroupData 
{        
public String ID;        
public String Title;        
public String CompanyName;        
public String SessionTitle;        
public String ViewedDate;        
public String DurationStr;        
public String location;        
public String IsVirtualContact;       
public String Groupcontact;        
public String name;        
public String email;    
}     
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\APEX\\\\\\\\\\\\\\\\\\\\\\\
public class demomailsent{
    public List<demomailsentwrap> ConsoleWrapperList{get;set;} 
     public List<demomailsentwrap> getperformcallout(){
      ConsoleWrapperList = new List<demomailsentwrap>();
       HttpRequest req = new HttpRequest(); 
       HttpResponse res = new HttpResponse();
        Http http = new Http(); 
        req.setEndpoint('http://webapi.demomail.net/test/DemomailSent.js'); 
        req.setMethod('GET');
        //req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
        res = http.send(req);
         //System.assert(false,res.getBody()+'******');
       
        
        if(res.getstatusCode() == 200 && res.getbody() != null)
          { 
         ConsoleWrapperList=(List<demomailsentwrap>)System.JSON.deserialize(res.getbody(),List<demomailsentwrap>.class); 
          //System.debug('Response Checking Engine: '+ res.getBody());
          }
            return consolewrapperlist; 
            
          }
          
     }

 
Hi,

can anyone briefly explain me on real use cases these 2 oAuth flows?
I'm struggling to find any useful information, about when to use them.

Thanks,
Marek
Hi all,

have anyone of you already started/finished one of these domain specialist trainings?
There is a lack of information, and I really want to know for what I'll pay 400$.. I can't find anything revant about these trainings. 

--> http://www.salesforce.com/campaigns/success-services/architect-academy.jsp
--> https://www.inkling.com/store/salesforce-university/

Thanks,
Marek
Hi All ,

There is an integration code which is already developed in our org , I am not sure whether they have used SOAP API or REST API in achieving the integartion .
Below is the code , can you please help me .

private string Senddata(string authdetails,string endPoint,string soapAction,string requestBody)
    {

        Httprequest soap_request = new Httprequest();

        string xml='';
        http soa = new http();
        Httpresponse soap_response = new Httpresponse();
        soap_request.setEndpoint(endPoint);
        soap_request.setHeader('SOAPAction',soapAction);
        
        soap_request.setMethod('POST');
        soap_request.setHeader('X-DocuSign-Authentication', authdetails);
        soap_request.setHeader('Content-type', 'text/xml; charset=utf-8');
        soap_request.setHeader('Content-Length', ''+requestBody.length());
        
        soap_request.setTimeout(30000);
        soap_request.setBody(requestBody);
        try
        {
            soap_response = soa.send(soap_request);
            xml = soap_response.getbody();
            
        }
        catch(System.CalloutException ex)
        {
            System.Debug('Call out Exception thrown: ' + ex.getMessage());
            throw ex;
        }
        catch (Exception e)
        {
            xml=e.getmessage();
            System.Debug('Exception occured: ' + e.getMessage());
        }
        return xml;
    }

The data is sent in form of xml .

Few are saying its Rest and few are saying its SOAP
  • February 10, 2016
  • Like
  • 0
If it is not feasible, please share your thoughts if it may possible even with the customization to fetch the user and queue records in a custom field and how?
How to create a REST end point in salesforce and make it public and it should accept an Integer as argument/parameter and triple it and send the response.
This is my code ....  I created a button in Vf when i click on that button my page should convert in to pdf and send a mail with that pdf for that i have written below code ... but my problem is how can i give values to the page , my page name is Stre 
  public void sendpdf()
          {
           string cname = ApexPages.currentPage().getParameters().get('pId');
           string dname = ApexPages.currentPage().getParameters().get('cId');
           string ename = ApexPages.currentPage().getParameters().get('chId');
           string fname = ApexPages.currentPage().getParameters().get('chstnum');
           string gname = ApexPages.currentPage().getParameters().get('chendnum');
           string hname = ApexPages.currentPage().getParameters().get('commamount');  
          string iname = ApexPages.currentPage().getParameters().get('pcreated');      
           string jname = ApexPages.currentPage().getParameters().get('pcfailed');      
           string kname = ApexPages.currentPage().getParameters().get('totalcom');      
              Messaging.SingleEmailMessage email1=new Messaging.SingleEmailMessage();
              String[] toadd=new string[]{'teja.sfdc99@gmail.com'};
              email1.setToAddresses(toadd);
              pageReference p=page.Stre;
              Blob b=p.getContentAsPdf();
              Messaging.EmailFileAttachment ef=new  Messaging.EmailFileAttachment();
              ef.SetFileName('Check Run PDF');
              ef.SetBody(b);
              Messaging.EmailFileAttachment[] attachments=new  Messaging.EmailFileAttachment[]{ef};
              email1.setFileAttachments(attachments);
              email1.setSubject('PDF Attachment');
              email1.SetPlainTextBody('This is sample test PDF');
              Messaging.Email[] emails=new Messaging.Email[]{email1};
              Messaging.SendEmail(emails);
              
              }

sample page with parametes is https://c.cs1.visual.force.com/apex/Stre?pId=Phoenix%20Health%20Plans%20(Formerly%20Abrazo)&cId=14/03/2015&chId=369175.0&chstnum=22912&chendnum=22949&commamount=369175.0&pcreated=3240&pcfailed=399&totalcom=4324

how can i pass this in my code please tell me i have taken the values as strings in the code but how can i pass it in pageReference p=page.Stre?.......


please help me with this 

 

 
Hi,

  when I am running a test class the pagereference method is having try, cactch blocks the MyPage.setRedirect(true)  is return outside of the chatch block so i am not able to cover this code please help me on this.

Thanks,
 zabi
Public void mymethod(set<id> subord1,map<id,user> usersMap)
    {
for(id subid :subord1)
           {
             Id roleId=usersMap.get(subid).userRoleId; 
             user u1=usersMap.get(subid);
              List<user> users;
             
             if(roleId!=null)
             {
             users = [select Id from User where UserRoleId IN (select Id from UserRole where ParentRoleId = :roleId)];
             }
}
}

I want to move the SOQL out of for loop---Or change it into single SOQL.


Thanks in adv.
Laxman 
Hello,

I am new for apex classes. I was trying to create a trigger which replicate the account recorded to custom object. All account standard and custom field.

Could someone help me please?

Thanks
 
  • January 28, 2016
  • Like
  • 1
Class:
trigger OpportunityLineItemTrigger on OpportunityLineItem (before insert, before update, after insert, after update, before delete) { 
    
    public boolean lineitemtrigger=CustomSettings.TriggerSwitch('OpportunityHandlerLineItem').Trigger_Function__c;
  
    if (lineitemtrigger) 
        return; 
            
    OpportunityLineItemTriggerHandler handler = OpportunityLineItemTriggerHandler.getHandler();
   
    if (Trigger.isInsert && Trigger.isBefore) { 
      handler.onBeforeInsert(Trigger.new);
    }
    else if (Trigger.isInsert && Trigger.isAfter) {
        handler.onAfterInsert(Trigger.newMap, Trigger.oldMap);
    }
    else if (Trigger.isUpdate && Trigger.isBefore) {
        handler.onBeforeUpdate(Trigger.newMap, Trigger.oldMap);
    }
    else if (Trigger.isUpdate && Trigger.isAfter) {     
      handler.onAfterUpdate(Trigger.newMap, Trigger.oldMap);
    }
    else if (Trigger.isDelete && Trigger.isBefore) {
        handler.onBeforeDelete(Trigger.oldMap);
    }
    
}


how to cover these lines in my test class

    else if (Trigger.isDelete && Trigger.isBefore) {
        handler.onBeforeDelete(Trigger.oldMap);
    }
Thanks
 
Hi, I am getting nullpointer exception while running below test class.

After inserting both contact and campaign objects only, i am referring them in campaign member object, wondering what i am missing here.
@isTest

public class CampaignMemberTaskcreation {

    Static testmethod void testtask(){

        Contact co1 = new Contact(
        LastName = 'Last',
        Title='CEO');
        
        insert  co1;
        string co1Id = co1.id;

        Campaign ca1 = new Campaign(
            Name = 'Testcampaign',
            Date_Sent__c=Date.today(),
            IsActive = TRUE);
        insert ( ca1 );
        string ca1Id = ca1.id;

        CampaignMember m1 = new CampaignMember();
            m1.Contact.Id = co1.Id; 
            m1.Campaign.Id = ca1.Id;
            m1.status='Responded';
        insert m1;
    }

}



Below is the error
Class CampaignMemberTaskcreation
Method Name testtask
Pass/Fail Fail
Error Message System.NullPointerException: Attempt to de-reference a null object
Stack Trace Class.CampaignMemberTaskcreation.testtask: line 22, column 1
I want to fetch id of contact person associated with an Account. And then use it in VF page.

SOQL
Account ac=[Select id,name,(select id,phone from Contact) where name='xyz' limit 1];
public ID cId;

This line compiles well.
But i don't how to use store contact Id from "ac" to "cId".

Any help would be highly appreciated.
Query:
  • January 27, 2016
  • Like
  • 0
I have a master-detail relationship where the master record is information I want a user to see but not edit and the child is a record I want them to create. I realise that security is inherited in a master-detail however can you add additional edit rights to the child so that a user can create child records without having edit access to the parent?
Hi Experts,

I am new in salesforce  and little bit confusse for testMethod for this class, How i can use testMethod for below class so that i can get 75% code coverage, and get the  current records form the "getTodaysMileageRecords()" function that's returning the list.

@isTest

public class MileageExtension {

private final Mileage__c mileageObj;

public MileageExtension(ApexPages.StandardController controller) {

this.mileageObj = (Mileage__c)controller.getRecord();

}

public Mileage__c[] getTodaysMileageRecords() {

String createdbyId = UserInfo.getUserId();

Mileage__c[] mileageList =  [SELECT name, miles__c
FROM Mileage__c
WHERE Date__c = TODAY
AND createdbyid = :createdbyId];
return mileageList;

}

}

Waiting for possitive reply

Many Thanks

Mukesh gupta
Hi getting the exception when trying to add records on my custom object Position__c

Here is my Controller :


public class InsertByVF{

    public Position__c pos;
    public String positionName{get;set;}
    public Decimal MinimumPay{get;set;}
    public Decimal MaximumPay{get;set;}
    
    public InsertByVF()
    {
    pos=new Position__c();
    
    }
  
    public void doInsert()
    {
 
    pos.Name=positionName;
    pos.Max_Pay__c=MaximumPay;
    pos.Min_Pay__c=MinimumPay;
       
  insert pos;      
       
 }
}


And below is my Apex page code :

<apex:page controller="InsertByVF">
<apex:form >
<apex:pageBlock title="New Position">
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
<apex:outputLabel >Position Name :</apex:outputLabel>
<apex:inputField id="FirstName" value="{!Position__c.positionName}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Max Pay :</apex:outputLabel>
<apex:inputField id="MaxPay" value="{!Position__c.MaximumPay}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel >Min Pay :</apex:outputLabel>
<apex:inputField id="MinPay" value="{!Position__c.MinimumPay}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton id="Save" action="{!doInsert}" value="Save"/>
<!--<apex:commandButton id="Cancel" action="{!Cancel}" value="Cancel"/>-->
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
 
I created one actionfunction and its name is "callmymethod"   when i click on the button , this method is not calling .   please help. 
<apex:page controller="createDynamicTableProcess" >
<apex:form >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

function calldata()
{
//alert("this is 2nd alert");
//callmymethod();
//alert("this is 3rd alert");

}
    window.setTimeout(callmymethod,2000);

</script>


<apex:actionfunction name="callmymethod" action="{!insertSubContactRecords}" id="idd1"/>
<apex:pageblock title="All contacts" >
<apex:repeat value="{!cons}" var="a" >
<table border="1" width="300px;" > <tr> 
<td><apex:outputtext value="{!a.name}" /> <br/></td>
<td><apex:outputtext value="{!a.phone}" /><br/></td>
<td><apex:outputtext value="{!a.account.industry}" /><br/></td>
<td><apex:commandbutton value="Add Row"  id="one"  onclick="calldata();">
<!-- <apex:param name="sending contact id" value="{!a.id}" assignto="{!contactid}" /> -->
</apex:commandbutton>
<br/><br/></td>

</tr> </table> 
  <apex:pageblocktable value="{!scw}" var="a" id="pbt1">
            <apex:column ><apex:inputcheckbox value="{!a.flag}" /> </apex:column>
            <apex:column ><apex:inputtext value="{!a.name}" onchange="getrec(this.id)" id="v1"/> </apex:column>
            <apex:column ><apex:inputtext value="{!a.country}" id="v2"/> </apex:column>
   </apex:pageblocktable>
<center><apex:commandbutton value="Save Checked Records"  ><apex:param value="{!a.id}" assignto="{!SpecificContactRecordId}" />  </apex:commandbutton></center>
</apex:repeat>
</apex:pageblock>
</apex:form>


</apex:page>
 
public class createDynamicTableProcess {

public list<contact> cons{set;get;}
public string contactid {set;get;}
public list<subcontactwrapper> scw{set;get;}
public list<subcontactwrapper> scw2{set;get;}
public string SpecificContactRecordId{set;get;}
public createDynamicTableProcess ()
{
scw=new list<subcontactwrapper>();
scw2=new list<subcontactwrapper>();

    cons=new list<contact>();

    list<string> accids=new list<string>();
        for(account a1:[select id from account])
            {
            accids.add(a1.id);
            }

       cons=[select id,name,phone,account.industry from contact where accountid in:accids limit 1];
} //constructor closed

//method for button click for every contact.
public void createRecordForSubContact()
{
subcontactwrapper s1=new subcontactwrapper();
scw.add(s1);

}

public void insertSubContactRecords()
{
list<subcontact__c> subc=new list<subcontact__c>();
    for(subcontactwrapper s1: scw)
    { 
    
        subcontact__c su=new subcontact__c();
        su.name__c=s1.name;
        su.Country__c= s1.country;
        su.Contact__c=SpecificContactRecordId;
        subc.add(su);
        }
        insert subc;
        
}      
public class subcontactwrapper
{
public boolean flag {set;get;}
public string name{set;get;}
public string country{Set;get;}
}
}


 
Hi,
I have a visualforce page with a user inputfield (lookup) and is bind to an object at the controller. Whenever there are multiple matches to my search text, the first item in the list is always selected. So, when I hit save, the selected value is not passed to the controller. In the VF page, I've used action support with onchange and onselect events, but since I'm not making any change (the first value in the list is selected) so those events are not getting fired. Is there any way to resolve that?

My Code:
<apex:inputField value="{!currentObject.OwnerId}" id="OwnerChangeField">
     <apex:actionSupport event="onchange" reRender="refresh"/> 
     <apex:actionSupport event="onselect" reRender="refresh"/>
</apex:inputField>


User-added image
This is what I'm getting in the UI and the current selection is the correct one, but still the value does not reach the controller due to those events not firing.

I'm unable to get the default selected value in the controller. I might be missing something or there might be a better way to do this. Any help will be appreciated!

Regards,
Ayan