• deve
  • NEWBIE
  • 445 Points
  • Member since 2017

  • Chatter
    Feed
  • 13
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 112
    Replies
Hello,

I am trying to write a test class for the below Apex Trigger but could do with some assistance as this is a first for me.

Could anyone help?

​-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Trigger OldMVPTrigger on MVP__c (after update) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(5) ) 
        {
           task t = new Task();
           t.Subject = 'You need to call '+mvp.MVP_Forename__c+' today';
           t.ownerId = mvp.MVP_Owner__c;
           t.WhatId = mvp.Id;
           t.ActivityDate = mvp.Last_Contacted_On__c;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Good afternoon,

I am using an Apex Class coupled with a visualforce page to redirect a user to a Case record created from a Flow, when the Flow ends.

Code below:
 
public class flowController{
  // Instanciate the Flow for use by the Controller - linked by VF interview attribute
  public Flow.Interview.QuickCase flowInstance {get;set;}

  // Set the page reference accessor methods
  public PageReference finishLocation {
    get {
      PageReference pageRef = new PageReference('/' + newRecordId);
      pageRef.setRedirect(true);
      return pageRef;
      
    }
 
  }

  // Set the accessor methods for the flow output variable
  public String newRecordId {
    get {
      String strTemp = '';

      if(flowInstance != null) {
        strTemp = string.valueOf(flowInstance.getVariableValue('CreatedCaseId'));
      }
      return strTemp;
    }

  set { newRecordId = value; }
  }
}

I am having trouble writing a Test Class for this. Can anyone give me a starting point?

Many thanks
Hi,

  I am using below ID to extract data using SOQL query I keep getting below error. Not sure what is issue is please suggest me. 
 
Error running Query: INVALID_QUERY_FILTER_OPERATOR: 
select id,name from account where id in ( '0013400001VHnhM', '0013400001VHnhq'
                                  ^
ERROR at Row:1:Column:35
invalid ID field: 0013400001VrBc
 
select id,name from account where id in ( '0013400001VHnhM',
'0013400001VHnhq',
'0013400001VrBVL',
'0013400001VHnjN',
'0013400001VrBVQ',
'0013400001VrBVV',
'0013400001MRoeD',
'0013400001VrBVa',
'0013400001NO0uf',
'0013400001VHnsj',
'0013400001VrBVf',
'0013400001VHntD',
'0013400001VrBVk',
'0013400001VHnw2',
'0013400001VrBVp',
'0013400001VHnxy',
'0013400001VrBVu',
'0013400001VHo1g',
'0013400001VHo3S',
'0013400001VrBW4',
'0013400001VH6QP',
'0013400001VHo9V',
'0013400001VHoAJ',
'0013400001VrBW9',
'0013400001VrBWE',
'0013400001VHoLR',
'0013400001VrBWJ',
'0013400001VrBWO',
'0013400001VHoP9AAL',
'0013400001VrBWT',
'0013400001VHoRe',
'0013400001VHoT6',
'0013400001VrBWd',
'0013400001VrBWi',
'0013400001VHoXN',
'0013400001VrBWs',
'0013400001VrJRz',
'0013400001VrJS4',
'0013400001VrBWx',
'0013400001VrBX2',
'0013400001VrBX7',
'0013400001VrBXC',
'0013400001VrBXH',
'0013400001VrBXM',
'0013400001VrBXR',
'0013400001VrBXW',
'0013400001VrBXg',
'0013400001VrBXl',
'0013400001VrBXq',
'0018000001AFZTH',
'0013400001VrBXv',
'0013400001VrBY0',
'0013400001VrBY5',
'0013400001VrBYA',
'0013400001VrBYF',
'0018000001DwmE4',
'0013400001VrBYK',
'0013400001VrBYP',
'0013400001VrBYZ',
'0013400001VrBYe',
'0013400001VrBYj',
'0013400001VrBYt',
'0013400001VrBYy',
'0013400001VrBZ3',
'0013400001VrBZD',
'0013400001VrBZI',
'0013400001Qkeeo',
'0013400001Ri6eF',
'0013400001VrBZN',
'0013400001VrBZX',
'0013400001VrBZc',
'0013400001VrBZh',
'0013400001VrBZm',
'0013400001VrBZr',
'0013400001VrBZw',
'0013400001VrBa1',
'0013400001VrBa6',
'0013400001VrBaB',
'0013400001VrBaG',
'0013400001VrBaV',
'0013400001VrBaa',
'0013400001VrBaf',
'0013400001VrBak',
'0013400001VrBap',
'0013400001VrBaz',
'0013400001VrBb9',
'0013400001VrBbE',
'0013400001VrBbJ',
'0013400001VrBbO',
'0013400001VrBbY',
'0013400001VrBbd',
'0013400001VrBbi',
'0013400001VrBbn',
'0013400001VrBbs',
'0013400001VrBbx',
'0013400001VrBc2',
'0013400001VrBc',
'0013400001LH411',
'0013400001LHqTY')

 
  • August 14, 2018
  • Like
  • 0
Hi Guys,

I've written and executing the test class for below code and not getting a enough code coverage. Any idea what I am miising in the code?

I could see, the log is returning null values to the line (List<AccountTeamMember> accountTeamList = [select userId,AccountId from AccountTeamMember where userId IN :userIds ];) though I've enough records to satisfy the select querry.
Class

global class Accountteamroleupdate {
    @future
    public static void role(Set<Id> userIds) {
        system.debug('User Id is ' + userIds);
        List<AccountTeamMember> accountTeamList = [select userId,AccountId from AccountTeamMember where userId IN :userIds ];
        map<Id, user> ObjMap = new map<Id, user>([select User_ID_18__c,Taylor_Business_Unit__c, Function__c  from user where Id IN :userIds]);
        System.debug('AccountTeamList is ' + accountTeamList);
        List<AccountTeamMember> updatedaccountlist = new List<AccountTeamMember>();
        for (AccountTeamMember am : accountTeamList )
        {
            if(ObjMap.containsKey(am.userId))
            {  
                User obj = ObjMap.get(am.userId);
                AccountTeamMember teamrole =new AccountTeamMember();
                teamrole.userId = obj.User_ID_18__c;
                teamrole.AccountId= am.AccountId;
                if (obj.Taylor_Business_Unit__c != null && obj.Function__c != null)
                {
                    teamrole.TeamMemberRole = obj.Taylor_Business_Unit__c +' '+ obj.Function__c;
                }
                else 
                {
                    teamrole.TeamMemberRole = 'Unspecified';
                }
                updatedaccountlist.add(teamrole);
            }
            
        }
        insert updatedaccountlist;
    }
}

Test Class:

@isTest
public class Teamroleupdatetestcls {
    static testMethod void testAccountTrigger(){
        user ul = [select Id from user where User_ID_18__c='005Z0000003r5wMIAQ'];
        system.debug('UserId is ' + ul.Id);
        set<Id> setAccId = new Set<ID>();
        setAccId.add(ul.Id);
        
        Accountteamroleupdate.role(setAccId);
          
    }
}
  • July 24, 2018
  • Like
  • 0
Hi All,


i am getting following error while running the code on trailhead for Apex Rest Callouts
Line No 12  Variable does not exist: AnimalsCallouts

@isTest
private class AnimalsCalloutsTest {
    @isTest static void testGetCallout() {
        // Create the mock response based on a static resource
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('GetAnimalResource');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Associate the callout with a mock response
        Test.setMock(HttpCalloutMock.class, mock);
        // Call method to test
        HttpResponse result = AnimalsCallouts.makeGetCallout();
        // Verify mock response is not null
        System.assertNotEquals(null,result,
            'The callout returned a null response.');
        // Verify status code
        System.assertEquals(200,result.getStatusCode(),
          'The status code is not 200.');
        // Verify content type   
        System.assertEquals('application/json;charset=UTF-8',
          result.getHeader('Content-Type'),
          'The content type value is not expected.');  
        // Verify the array contains 3 items     
        Map<String, Object> results = (Map<String, Object>) 
            JSON.deserializeUntyped(result.getBody());
        List<Object> animals = (List<Object>) results.get('animals');
        System.assertEquals(3, animals.size(),
          'The array should only contain 3 items.');          
    }   
}

please help

Thanks
Pranav



 


I need to Use TRigger for above Question also need Test Class for it. I have created custom object mentioned above. Can anyone help me in Trigger ANd Test Class ? Its urgent. 


Thanks in advance.User-added image
  • July 22, 2018
  • Like
  • 0
Prepare the following map structures :
 
 Code:
 /** a. Account Name as key and AccountId as value.*/
 public class AccountMapClass {
  public static Map<String,String> accountMap(){
        Map<String,String> mapAccount = new Map<String,String>();
        for (Account acc :[SELECT Name,Id
                          FROM Account])
        {
            mapAccount.put(acc.Name,acc.Id);
        }
        System.debug(mapAccount);
        return mapAccount;
    }
    
  /*b. Account Id as key and entire Account object as value*/      
    public static Map<String, Account> accountMapNew(){
        Map<String, Account> mapAccount = new Map<String, Account>();
        for(Account accountObject  : [SELECT Id,Name,BillingAddress 
                                     FROM Account])
        {
            mapAccount.put(accountObject.Id, accountObject);
        }
        System.debug(mapAccount);
        return mapAccount;
    }    
}

Can anyone help in Test Class for following code. Considering positive and negative test Cases for both methods.
  • July 22, 2018
  • Like
  • 0
 Need COde for Following SOQL along with Test Cases

Need SOQL and Test Class for each Question. Any Help will be appreciated.
Thanks
  • July 21, 2018
  • Like
  • 0
Hello, I have this query:

SELECT b.Outstanding_Amount__c
FROM Billing__C b, Contract c
WHERE b.Contract_Number__C = c.ContractNumber
AND  c.AccountId =: cuenta.Id 

(cuenta.Id is the value that I pass)

But i need to do it in SOQL, could anybody help me pease?
 
I am getting unknown property error while using custom controller.I am using Developer console.please help

VisualForce code
<apex:page showHeader="false" controller="insertewsclass">
<style>
td{font-size:20px;color:blue}
.st{font-size:25px;color:red}
</style>
<apex:form >
<apex:image value="{!resource.logo}" width="220" height="100"/>
<apex:pageBlock tabStyle="Employment_Website__c">
<apex:outputText value="{!msg}" style="st"/><br/><br/>
<table boder="0" width="70%" height="70">
<tr>
<td>EWS Name</td>
<td><apex:inputText value="{!name}"/></td>
</tr>
<tr>
<td>Price per post</td>
<td><apex:inputText value="{!pp}"/></td>
</tr>
<tr>
<td>Maximum budget</td>
<td><apex:inputText value="{!mb}"/></td>
</tr>
<tr>
<td>URL</td>
<td><apex:inputText value="{!url}"/></td>
</tr>
<tr>
<td></td>
<td><apex:commandButton value="Insert" action="insert_rec" style="font-size:15px"/>
    &nbsp;<input type="reset" style="font-size:15px"/></td>
</tr>
</table>
</apex:pageBlock>
</apex:form>
</apex:page>

Apex code
public class insertewsclass {
    public string name{get;set;}
    public double pp{get;set;}
    public double mb{get;set;}
    public string url{get;set;}
    public string msg;
    
    public void insert_rec()
    {
        integer namecount = [select count() from Employment_Website__c where Name = :name];
        integer urlcount = [select count() from Employment_Website__c where Website_address__c = :url];
    if(namecount > 0 || urlcount > 0)
    {
      msg = 'Record Insertion Failed';
    }
    else
    {
        Employment_Website__c ob = new Employment_Website__c();
        ob.Name = name;
        ob.Price_per_post__c = pp;
        ob.Maximum_budget__c = mb;
        ob.Website_address__c = url;
        msg = 'Record Inserted Successfully';
    }
    }
    public string getmsg()
    {
        return(msg);
    }
}

 
Hey All, 
I am working with a 3rd party and they have a VFP with a list that has sortable columns. The test class has test methods without system asserts. On the one hard, this makes sense because what would you actually assert? But on the other hand, this simply calls the method. It doesn't actually validate anything. Code snipet is below. 
 
@isTest
	static void test_SortByAccount() {
		RecordReturnsCtrl ctrl = new RecordReturnsCtrl();
		ctrl.columnName = 'Account';
		ctrl.ascendingSort = false;
		ctrl.sortRecords();
}

Is this ok? My gut wants a system assert that checks the results against what is expected. But i'm not sure if i'm just asking for too much. Thanks. 

-Mike
Hi All,
 
I am new to salesforce and I need help with the code which I have attempted.

I am trying to fetch some fields from Salesforce Knowledge Standard Object. 
I have created a Controller and below is my code:
public class KBController {

 public list<Knowledge__kav> KBArticles {get;set;}
 
 public KBController (ApexPages.StandardController StdCtrller){
 
 this.KBArticles = new list<Knowledge__kav>();
 
 KBArticles = [Select articleNumber, Title from Knowledge__kav where PublishStatus='Online'];  
 
 }
 }

Below is the code in my markup: 
<apex:page showHeader="false" sidebar="false" standardController="Knowledge__kav" extensions="KBController">
<apex:form >
<apex:pageBlock >
<apex:pageBlockTable value="{!KBArticles}" var="articles">
                <apex:column value="{!articles.articleNumber}"/> 
                <apex:column value="{!articles.Title}"/> 
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

With this code, I am getting an error: 
Id value null is not valid for the Knowledge__kav standard controller 

Could anyone please suggest me here?

Thanks!
 
 
Hi experts,

I am trying to perform the dynamic search in account object but getting error while I input in respective fields: 

"System.QueryException: unexpected token: =
Error is in expression '{!desiredSearch}' in component <apex:commandButton> in page happysearchpage: Class.HappySearch.desiredSearch: line 18, column 1"
Class.HappySearch.desiredSearch: line 18, column 1

Please review my code and suggest me solution. 
Thanks

My Controller Code:
public class HappySearch {
    public list <Account> a {set;get;}
    public string aName     {set;get;}
    public string aType     {set;get;}
    
    public void desiredSearch(){
                        string Dsearch='Select Name, Type From Account';
                        if ((aName!=Null && aName!= '') && (aType!=''&& aType!=Null )){
                            Dsearch= Dsearch+ 'where name=\' '+aName+' \' and type=\' '+aType+' \'';}
                         else {
                            if(aName!=Null && aName!= ''){
                                    Dsearch= Dsearch+ 'where name=\' '+aName+' \'';} 
                                   else{
                                     if(aType!=Null && aType!=''){
                                         Dsearch= Dsearch+ 'where type=\' '+aType+' \'';}
                                       }
                                }
                          a= Database.query(Dsearch);
                        } 
                }

VF Page Code:
<apex:page controller="HappySearch" >
<apex:form >
    
    <apex:pageBlock title="Search">
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel Value="Name"/>
                <apex:inputText value="{!aName}"/>  
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel Value="Type"/>
                <apex:inputText value="{!aType}"/>  
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection> 
    
       <apex:pageBlockButtons location="Bottom">
           <apex:commandButton value="DSearch" Action="{!desiredSearch}"/>
       </apex:pageBlockButtons>
    </apex:pageBlock>
       
    <apex:pageBlock title="Search Result" rendered="(! !ISNULL(a))" >
       <apex:pageBlockTable value="{!a}" var="b">
       <apex:column value="{!b.Name}"/>
       <apex:column Value="{!b.Type}"/>
       </apex:pageBlockTable>    
    </apex:pageBlock>
     
</apex:form>
</apex:page>

P.S. it worked well if no inputs given to repective fields.   ​

 
I want to delete dupicate accounts below code for your reference. Attached is the error
global class DuplicateRecords implements Database.Batchable<SObject>  {

     

  Global Map<String , Account__c> AccountNumberBookmap = new Map<String ,  Account__c>();

     

    global Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([Select AccountNumber__c from Account__c where AccountNumber__c != null]);

      }

     

     

     

    global void excute(Database.BatchableContext BC , List<AccountNumber__c> scope){

         

      

         

         

      // Map<String , AccountNumber__c> AccountBookmap = new Map<String , AccountNumber__c>();

         

        List<AccountNumber__c> duplicatelist = new List<AccountNumber__c>();

        for(AccountNumber__c s : scope){

            if(! AccountBookmap.containsKey(s.Account__c)){

                AccountBookmap.put(s.Account__c , s);

            }

            else{

                duplicatelist.add(s);          

            }                       

        } 

                

        

       system.debug(duplicatelist);

        if(duplicatelist.size() > 0){

            delete duplicatelist;

        }

    }

     

    global void finish(Database.BatchableContext BC){

         

    }

         

 

}
User-added image
Hi below is my Simple Trigger and Test classes.
I am not able to Cover the code for Custom settings, can anyone help me
 
trigger CreateRecord on Deals__c (after insert, after update) 
{
    
    set<id> triggerIds = trigger.newMap.keyset();
    List <Project__c> Project = [select id, Name from Project__c where id in :triggerIds];
    List <Project__c> newProject = new List<Project__c>() ;
    
    for(Deals__c Deal : [Select id,Name,Property__r.Region__c,Type__c,Status__c,Manager__c,Property__r.Site__c from LMS_Deal__c where id IN :triggerIds])
    {
        if(Deal.Type__c == 'New')
        {
            string Name = Deal.Name + ' - ' + Deal.Property__r.Site__c;
            List <Project__c> ProjectList = [select id,Name,OwnerId,Property__r.Site__c from Project__c where Name =: Name];
            Region__c customSettings = Region__c.getInstance(Userinfo.getUserId());
			if (ProjectList.size() == 0)
            {
                if(deal.Manager__c == Null && Deal.Property__r.Region__c == 'Delhi')
                {
                    Deal.Manager__c = customSettings.Delhi__c;
    	        }     
                    newProject.add(new Project__c
                               (   Name = Deal.Name + ' - ' + Deal.Property__r.Site__c, 
                                   OwnerId = Deal.Manager__c
                    insert newProject;
            }//if
            else if (ProjectList.size() >> 0)
            {
                if(Deal.Manager__c == Null && Deal.Property__r.Region__c == 'Delhi')
				{
                    Deal.Manager__c = customSettings.Delhi__c;
                }
               Project__c NewProjectList = [select id,Name,OwnerId,Property__r.Site__c,Property__r.Region__c from Project__c where Name =: Name];
                NewProjectList.OwnerId = Deal.Manager__c; 
                update NewProjectList;
            }    
        }
    }
}

My test class:
 
@isTest(SeeAllData=true)
private class CreateRecordTest {
    static testmethod void CreateRecord(){
		// creating property
        Property__c prop = new Property__c(Name = 'Test property', Site_c = 'New Site', Region__c = 'Delhi');
        insert prop;
		// creating Units 
        Unit__c units = new Unit__c(Name = 'Test Unit', Property_Unit__c = prop.Id);
        insert units;
		// creating a user 
        Profile objProfile = [SELECT Id, Name FROM Profile WHERE Name='System Administrator'];
        User objUser = new User(Alias = 'Swill', 
                                Email='swill@mymail.com', 
                                EmailEncodingKey='UTF-8', 
                                LastName='Will', 
                                LanguageLocaleKey='en_US', 
                                LocaleSidKey='en_US', 
                                ProfileId = objProfile.Id, 
                                TimeZoneSidKey='America/Los_Angeles', 
                                UserName='will@gmail.com');
        insert objUser;
		// creating another user for assigning custom setting 
        Profile objProfile1 = [SELECT Id, Name FROM Profile WHERE Name='System Administrator'];
        User objUser1 = new User(Alias = 'Kaka', 
                                Email='kaka@kakamail.com', 
                                EmailEncodingKey='UTF-8', 
                                LastName='Mkaka', 
                                LanguageLocaleKey='en_US', 
                                LocaleSidKey='en_US', 
                                ProfileId = objProfile1.Id, 
                                TimeZoneSidKey='America/Los_Angeles', 
                                UserName='kaka_M@gmail.com');
        insert objUser1;
		// creating custom settings 
		Region__c CustomSettings = new Region__c ( Name = 'test custom setting',
													Delhi__c = objUser1.Id);
        insert CustomSettings;
       // creating deal  
       Deal__c deal = new Deal__c(Name = 'Test Deal',
                                  Manager__c = objUser1.Id,
                                  Type__c = 'New');
                          insert LMSdeal1;
       // creating property 
        Project__c TP = new Project__c(
                Name = deal.Name +  ' - '  + deal.Property__r.Site__c,
                OwnerId = deal.Manager__c);
            insert TP;
        
        
            
}
}

The problem -  not able to Pass the values into if conditions 
if(deal.Manager__c == Null && Deal.Property__r.Region__c == 'Delhi')
                {
                    Deal.Manager__c = customSettings.Delhi__c;
    	        }

 
  • January 19, 2019
  • Like
  • 0
I'm trying to get a contact from a custom object, but am struggling on how to do so. The custom object is called 'Opportunity Request' (API Name: 'Sales_Request__c'), which is a child object to an 'Opportunity', so one Opportunity can have many Opportunity Requests. On the Opportunity Request there is a field named 'Prospect Contact', which is not pulled from the Opportunity, but is selected when creating the Opportunity Request. How would I get this field since it is on a custom object and I'm unfamiliar of the IDs needed?
I'am trying to create an apex trigger for conditional autonumber on lead based on lead record type. Getting an error ''execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0''. Can someone help pelase? Thanks.

trigger Autonumber on Lead (before insert, before update) {

    list<Lead> lead= [SELECT Id,Name,Company,Status,Lead_Number__c FROM Lead WHERE Lead_Number__c !=:null AND Lead_Number__c > 0 order by Lead_Number__c desc limit 1];
    decimal maxlead=lead[0].Lead_Number__c;    

    for(Lead Lead:Trigger.new){
        if(lead.RecordTypeId =='0126F000001Cmgn'){
            lead.Lead_Number__c = Integer.valueOf(maxlead)+1;
        }
    }  
}
I am getting the following error message when trying to send info from livechat to salesforce. How do I resolve this
<table id= "maintable" width="100%" >
          <tr>
            <td width="1%">
            	<table id="linkdetails" class="linksection">
                  <tr>
                    <th><a href="" onclick="callmyjs('CreateAccount');">Create Account</a></th>
                  </tr>
                  <tr>
                    <th><a href="" onclick="callmyjs('UpdateAccount');">Update Account</a></th>
                  </tr>
                  <tr>
                    <th><a href="" onclick="callmyjs('RetriveAccount');">Retrive Existing Account Details</a></th>
                  </tr>
               </table> 
            </td>
            <td>
            	<apex:outputPanel id="createacc">
            	            Create 
            	</apex:outputPanel>
            	
            	<apex:outputPanel id="updateacc">
            	            update 
            	</apex:outputPanel>
            	
            	<apex:outputPanel id="retriveacc">
            	            retrive 
            	</apex:outputPanel>
            </td>
          </tr>
        </table>
        
        <apex:actionFunction name="showcreateacc" rendered="createacc">
        </apex:actionFunction>
        
        <apex:actionFunction name="showupdateacc" rendered="updateacc">
        </apex:actionFunction>
        
        <apex:actionFunction name="showretriveacc" rendered="retriveacc">
        </apex:actionFunction>
    

    <script>
            function callmyjs(val)
            {  
                if(val == 'CreateAccount')
                {
                        alert('Create Account');
                        showcreateacc();                       
                }        
                if(val == 'UpdateAccount')
                {
                        alert('Update  Account');
                        showupdateacc();
                }        
                if(val == 'RetriveAccount')
                {
                        alert('Retrive Account'); 
                       showretriveacc();
                }        
                
            }
    </script>
</apex:form>
Above is the piece of code I am refering where i am trying to call action function from javscript method 

but when i am calling it is showing me error as Uncaught ReferenceError: showcreateacc is not defined 

what i want to do here is on create only create output panel should show other should be disable and same for retrive and udpate as well
  • September 20, 2018
  • Like
  • 0
Date.monthsBetween method returns one day less. Is it how date method working?
eg.
date fDate = date.newInstance(2018, 09, 01);
date sDate = date.newInstance(2018, 09, 30);
system.debug(fDate.monthsBetween(sDate));

Thanks.
Myat
Hi, I have created a detail custom button of url type and passing Opportunity Date as shown below.

/apex/vfpage?oliId={!OpportunityLineItem.Id} && oppDate={!Opportunity.customDate__c}

And in apex constructor i am receiving the custom date value as below.

customDate = Date.valueOf(ApexPages.currentPage().getParameters().get('oppDate'));
But I am receiving error as
"Argument cannot be null. An unexpected error has occurred. Your development organization has been notified. "

How to pass the oppDate from url to constructor.
 
Hi Team,

Requirement : Update the Field A based on Field B value using trigger, Filed B value updated using Work flow. How can we achieve that using trigger (Insert and update events) .

Please let me know.

Thanks,
Lakshmi.
Hello All ,

I am getting error Message "Attempt to de-reference a null object"  when we run "permissionSett()" this method .
My Apex code is here please help me .
public class DeepcloneUser {
    Public String fName {set;get;}
    Public String lName {set;get;}
    Public static String eMail {set;get;}
    public static Id conId {set;get;}
    Public Contact c;
    Public static User u;
    public Static User[] uid;
    Public set<Id> CloneId;
    Public static Set<Id> permiId;
    public static PermissionSetAssignment[] Listperm;
    public static list<PermissionSetAssignment> Listpermission;
    
     public DeepcloneUser(ApexPages.StandardController stdController) {
          // conId=apexpages.currentpage().getparameters().get('id');
        CloneId=new Set<Id>();
        permiId=new Set<Id>(); 
         Listpermission=new List<PermissionSetAssignment>();
     }
     @future 
    Public static void CreateUser(String fname,String LName,String Email,Id Cid,String Pid ,String nickname)
    {
        u=new user();
       // String alias = 'aaa';
            
    
        
        u.FirstName=fname;
        u.LastName=lName;
        u.Email=eMail;
        u.Username=email;
        u.ProfileId=Pid;
       u.ContactId=cid;
       
        //u.CommunityNickname=attributes.get('u.CommunityNickname');   
        u.CommunityNickname=nickname;
        u.EmailEncodingKey='UTF-8';
        u.LocaleSidKey='en_US';
        u.Alias='snsa';
        u.LanguageLocaleKey='en_US';
        u.TimeZoneSidKey='GMT';
        insert u;
    }
    
     @InvocableMethod
   public static void GetDetail()
   {
     
          conId=apexpages.currentpage().getparameters().get('id');  
       
   
       Contact[] co=[select id,firstName,Community_Nickname__c, Clone_Contact__c,LastName, Email from contact where id=:conId limit 1];
     
       //String cCid=co[0].id;
       String ffname=co[0].firstName;
       String llname=co[0].lastName;
       String eemail=co[0].email;
       String nnickname=co[0].Community_Nickname__c;
      // String pfid='00ed00000019frTAAQ';
       String Clone=co[0].Clone_Contact__c;
        uid=[select id, profileid from user where contactid=:Clone limit 1];
      
      
       String pfid=uid[0].profileid;       
     CreateUser(ffname,ffname,eemail,conId,pfid,nnickname);
 
      //Listperm=[SELECT Id FROM PermissionSetAssignment  WHERE AssigneeId=:uid[0].id];
      }
    public void permissionSett()
    {
       List<PermissionSetAssignment> lstp=new list<PermissionSetAssignment>();
        List<PermissionSetAssignment> lstcloUserpert=[SELECT Id, PermissionSet.Name,AssigneeId
                                                                FROM PermissionSetAssignment
                                                                WHERE AssigneeId = :uid[0].id];
        conId=apexpages.currentpage().getparameters().get('id');   
        User Userid=[select id from user where contactId=:ConId limit 1];
       for(PermissionSetAssignment p:lstcloUserpert)
       {
        PermissionSetAssignment pmr=new PermissionSetAssignment();
        pmr.AssigneeId=userId.id;
         pmr.PermissionSetId=p.id;
           lstp.add(pmr);
           
           
           
       }
               
        
       upsert lstp;
        
    }
}

I need to add on a layout a button that deletes/empties certain field-values of the object once it gets clicked. The logic of the deletion is already implemented but now it shall be done via button click. Can anyone help? How do I combine the code with the button?

 

Hello All,

I have the below json response, need to store email and name field values in a custom object.
(Field_data:[name=email, values=(vsinb@gmail.com)], Field_data:[name=full_name, values=(SherinV)]).
Any idea on this would be of great help to me. Awaiting response.

Thanks in advance
Hi All,
i have an apex controller on account object and passing one parameter there.
In salesforce lightning, i used ui:inputtext for input field and is working fine, 
the issue is:- when i am not entering any value and pressing on enter, it is giving the records.. that is the issue i have,, 
i tried to make that field mandatory by putting required=true, but not working
Can anyone pls help on this!!
Thanks,
Chinna.
Hi All,
we want to activate the chatter for email to case in lightning but we do not want any person to post or comment using chatter.
I have written two triggers for not posting anything and also commenting via case feed both are working fine but failed to write a test classes for both.
FeedItem:
trigger ChatterCommentItem on FeedItem (before insert) {
for(FeedItem fi : trigger.new)
        if(fi.type == 'ContentPost' || fi.type == 'TextPost')
            fi.addError('you do not have permissions to post any comment or File.Please contact your system administrator.');
}
FeedComment
trigger ChatterComment on FeedComment (Before Insert) { 
    for(FeedComment fc : trigger.new)
if(fc.CommentType == 'ContentComment' || fc.CommentType == 'TextComment' )
            fc.addError('you do not have permissions to post any comment or File.Please contact your system administrator.');
}

I have written feed comment trigger for case object when the case status or any changes happens case feed is generated so no one should comment on it any help on the test classes for both triggers would be appriciated thank you.
Hi All,
         i have a controller class given below:-
                       public class GenericHistoryComponentController {

// External variables
public SObject myObject {get; set;}
public Integer recordLimit {get; set;}
public static String objectLabel {get;}

// Internal Variables
public objectHistoryLine[] objectHistory; 

public static final Map<String, Schema.SObjectType> mySObjectTypeMap = Schema.getGlobalDescribe();
public static Map<String, Schema.SObjectField> myObjectFieldMap;
public static List<Schema.PicklistEntry> historyFieldPicklistValues;

public List<objectHistoryLine> getObjectHistory(){

Id myObjectId = String.valueOf(myObject.get('Id'));
Schema.DescribeSObjectResult objectDescription = myObject.getSObjectType().getDescribe();

myObjectFieldMap = objectDescription.fields.getMap();
objectLabel = String.valueOf(objectDescription.getLabel());

//Get the name of thew history table
String objectHistoryTableName = objectDescription.getName();
//if we have a custom object we need to drop the 'c' off the end before adding 'History' to get the history tables name
if (objectDescription.isCustom()){
objectHistoryTableName = objectHistoryTableName.substring(0, objectHistoryTableName.length()-1);
}
objectHistoryTableName = objectHistoryTableName + 'History';

Schema.DescribeFieldResult objectHistoryFieldField = mySObjectTypeMap.get(objectHistoryTableName).getDescribe().fields.getMap().get('Field').getDescribe();
historyFieldPicklistValues = objectHistoryFieldField.getPickListValues();

list<objectHistoryLine> objectHistory = new list<objectHistoryLine>();

String prevDate = '';

if (recordLimit== null){
recordLimit = 100;
}

list<sObject> historyList = Database.query( 'SELECT CreatedDate,'+
'CreatedById,'+
'Field,'+
'NewValue,'+
'OldValue ' +
'FROM ' + objectHistoryTableName + ' ' +
'WHERE ParentId =\'' + myObjectId + '\' ' +
'ORDER BY CreatedDate DESC '+
'LIMIT ' + String.valueOf(recordLimit));

for(Integer i = 0; i < historyList.size(); i++){
sObject historyLine = historyList.get(i);
if ((historyLine.get('newValue') == null && historyLine.get('oldValue') == null) 
|| (historyLine.get('newValue') != null && !(string.valueOf(historyLine.get('newValue')).startsWith('005') || string.valueOf(historyLine.get('newValue')).startsWith('00G')))
|| (historyLine.get('oldValue') != null && !(string.valueOf(historyLine.get('oldValue')).startsWith('005') || string.valueOf(historyLine.get('oldValue')).startsWith('00G')))){
objectHistoryLine tempHistory = new objectHistoryLine();
// Set the Date and who performed the action
if (String.valueOf(historyLine.get('CreatedDate')) != prevDate){
tempHistory.theDate = String.valueOf(historyLine.get('CreatedDate'));
tempHistory.userId = String.valueOf(historyLine.get('CreatedById'));
tempHistory.who = String.valueOf(historyLine.get('CreatedById'));
}
else{
tempHistory.theDate = '';
tempHistory.who = '';
tempHistory.userId = String.valueOf(historyLine.get('CreatedById'));
}
prevDate = String.valueOf(historyLine.get('CreatedDate'));

// Get the field label
String fieldLabel = GenericHistoryComponentController.returnFieldLabel(String.valueOf(historyLine.get('Field')));

// Set the Action value
if (String.valueOf(historyLine.get('Field')) == 'created') { // on Creation
tempHistory.action = 'Created.';
}
else if (historyLine.get('oldValue') != null && historyLine.get('newValue') == null){ // when deleting a value from a field
// Format the Date and if there's an error, catch it and re
try {
tempHistory.action = 'Deleted ' + Date.valueOf(historyLine.get('oldValue')).format() + ' in <b>' + fieldLabel + '</b>.';
} catch (Exception e){
tempHistory.action = 'Deleted ' + String.valueOf(historyLine.get('oldValue')) + ' in <b>' + fieldLabel + '</b>.';
}
}
else{ // all other scenarios
String fromText = '';
if (historyLine.get('oldValue') != null) {
try {
fromText = ' from ' + Date.valueOf(historyLine.get('oldValue')).format();
} catch (Exception e) {
fromText = ' from ' + String.valueOf(historyLine.get('oldValue'));
}
}

String toText = '';
if (historyLine.get('oldValue') != null) {
try {
toText = Date.valueOf(historyLine.get('newValue')).format();
} catch (Exception e) {
toText = String.valueOf(historyLine.get('newValue'));
}
}
if (toText != ''){
tempHistory.action = 'Changed <b>' + fieldLabel + '</b>' + fromText + ' to <b>' + toText + '</b>.';
}
else {
tempHistory.action = 'Changed <b>' + fieldLabel;
}
}

// Add to the list
objectHistory.add(tempHistory);
}
}

List<Id> userIdList = new List<Id>();
for (objectHistoryLine myHistory : objectHistory){
userIdList.add(myHistory.userId);
}
Map<Id, User> userIdMap = new Map<ID, User>([SELECT Name FROM User WHERE Id IN : userIdList]);

for (objectHistoryLine myHistory : objectHistory){
if (userIdMap.containsKey(myHistory.userId) & (myHistory.who != '') ){
myHistory.who = userIdMap.get(myHistory.who).Name;
}
}

return objectHistory;


// Function to return Field Label of a object field given a Field API name
public Static String returnFieldLabel(String fieldName){

if (GenericHistoryComponentController.myObjectFieldMap.containsKey(fieldName)){
return GenericHistoryComponentController.myObjectFieldMap.get(fieldName).getDescribe().getLabel();
}
else {
for(Schema.PicklistEntry pickList : historyFieldPicklistValues){
if (pickList.getValue() == fieldName){
if (pickList.getLabel() != null){
return pickList.getLabel();
}
else {
return pickList.getValue();
}
}
}
}
return '';
}

// Inner Class to store the detail of the object history lines 
public class objectHistoryLine {

public String theDate {get; set;}
public String who {get; set;}
public Id userId {get; set;} 
public String action {get; set;}
}
}
  its showing me this error:-Variable is not visible: GenericHistoryComponentController.objectLabel
I have a custom Child object 'H' for Account object. I want to compare the values of a field 'R(number field ) of two child records. If the value is consecutively zero i have to create a case and send out a task to a user.

Any suggestions on this ?
  • August 16, 2018
  • Like
  • 0
I have written an VF page, to display return list of matched duplicate contacts before a lead convert.

While the process works for System Admin, some of my profiles, receive the following error - and are not getting the VF page to display:
Error: 
Invalid field AccountId for SObject Account
Error is in expression '{!item['AccountId']}' in component <apex:column> in page
leadconversionpage
Error evaluating dynamic reference 'AccountId'

The VF page, critical code is: leadConversionPage
<apex:sectionHeader title="Convert Lead" subtitle="{!oLead.Name}"/>
    <apex:form id="editPage">
        <apex:outputPanel rendered="{!hasDuplicateResult == false}">
            Leads can be converted to accounts, contacts, opportunities, and followup tasks.<br/>
            You should only convert a lead once you have identified it as qualified.<br/>
            After this lead has been converted, it can no longer be viewed or edited as a lead, but can be viewed in lead reports.<br/><br/>
        </apex:outputPanel>    
        <apex:outputPanel rendered="{!hasDuplicateResult}">
            To avoid creating duplicate contacts, select from the options below. When an existing contact is selected, all open activities from the lead will be added to the contact and all new data will be added. Lead data will not overwrite existing contact data.
        </apex:outputPanel> 
        
        
        <!-- saar added for duplicates -->
        <apex:pageBlock title="Duplicate Records" rendered="{!hasDuplicateResult}">
            <apex:pageMessages />
            <apex:pageBlockTable value="{!duplicateRecords}" var="item">
                <apex:column headerValue="Select to Merge">
                    <input type="radio" name="selectRadio" id="radio">
                    <apex:actionSupport event="onclick" action="{!setSelectedContactToMerge}" reRender="mergeButton">      
                        <apex:param name="selectedMergedContactId" value="{!item['Id']}"/>
                        <apex:param name="selectedMergedAccountId" value="{!item['AccountId']}"/>
                    </apex:actionSupport>
                </input>
            </apex:column>
            <apex:column >
                <apex:facet name="header">Name</apex:facet>
                <apex:outputLink value="/{!item['Id']}">{!item['Name']}</apex:outputLink>
            </apex:column>
            <apex:column >
                <apex:facet name="header">Owner</apex:facet>
                <apex:outputField value="{!item['OwnerId']}"/>
            </apex:column>                
            <apex:column >
                <apex:facet name="header">Account</apex:facet>
                <apex:outputField value="{!item['AccountId']}"/>
            </apex:column>
            <apex:column >
                <apex:facet name="header">Last Modified Date</apex:facet>
                <apex:outputField value="{!item['LastModifiedDate']}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>


Any help appreciated.