• v varaprasad
  • PRO
  • 3575 Points
  • Member since 2015
  • Salesforce Developer

  • Chatter
    Feed
  • 115
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 745
    Replies
I'm trying to write a class that will call a flow. I don't understand why Dev Console won't let me save, telling me that myFlow.start() is an invalid constructor name.
User-added image
Hi, 

I have a list with the following format in apex controller. 

Custom__Object_Analysis__c:{Id=a0L1N00000L1izqUAB, Name=All Accounts, CreatedDate=2018-02-15 15:15:12, isCustom__c=false, Fields__c=0, Filter__c=Industry = '', Object_Name__c=account, Tally__c=0}

How do I serialize this? 
JSON.Serialize() gives Uncaught SyntaxError: Unexpected string 
Hi,
Test Class Failing for Methods defined as TestMethod do not support getContent call


Test Class:
@isTest
private class PicklistDescriberTest {
 
    @isTest 
    static void test() {
        
        Map<String, Schema.RecordTypeInfo> recordTypes = Schema.SObjectType.Account.getRecordTypeInfosByName();
        List<String> recordTypeNames = new List<String>(recordTypes.keyset());
         
      
        
        Account testAccount = new Account(Name='Test Account', Continent__c = 'Asia', Country__c = 'India', RecordTypeId = recordTypes.get(recordTypeNames[0]).getRecordTypeId());
        insert testAccount;
        
          
        
        System.assert(PicklistDescriber.describe(testAccount.Id, 'Asia').size()!=0);
        
        
        System.assert(PicklistDescriber.describe('Account', recordTypeNames[0], 'Continent__c').size() > 0);
        
        System.assert(PicklistDescriber.describe('Account', recordTypes.get(recordTypeNames[0]).getRecordTypeId(), 'Continent__c').size() > 0);
        
        System.assert(PicklistDescriber.describe('Account', recordTypeNames[0], 'Country__c', 'Continent__c').size() > 0);
        
        System.assert(PicklistDescriber.describeWithDependency('Account', recordTypeNames[0], 'Country__c', 'Continent__c').size() > 0);
        
        System.assert(PicklistDescriber.describeWithDependency('Account', recordTypes.get(recordTypeNames[0]).getRecordTypeId(), 'Country__c', 'Continent__c').size() > 0);
    }
    
}



Actual Class:

public with sharing class PicklistDescriber {
    static final Pattern OPTION_PATTERN = Pattern.compile('<option.+?>(.+?)</option>');

    /**
        Desribe a picklist field for an sobject id. RecordType is automatically picked
        based on the record's RecordTypeId field value.
        example usage :
        List<String> options = PicklistDescriber.describe(accountId, 'Industry');
    */
    public static List<String> describe(Id sobjectId, String pickListFieldAPIName) {
        return parseOptions(
                            new Map<String, String> {
                                                     'id' => sobjectId,
                                                     'pickListFieldName'=> pickListFieldAPIName
                                                    }
                            );
    }

    /**
        Describe a picklist field for a SobjectType, its given record type developer name and the picklist field
        example usage :
        List<String> options = PicklistDescriber.describe('Account', 'Record_Type_1', 'Industry'));
    */
    public static List<String> describe(String sobjectType, String recordTypeName, String pickListFieldAPIName) {
        return parseOptions(
                            new Map<String, String> {
                                                     'sobjectType' => sobjectType,
                                                     'recordTypeName' => recordTypeName,
                                                     'pickListFieldName'=> pickListFieldAPIName
                                                    }
                            );
    }

    /**
        Describe a picklist field for a SobjectType, its given record type ID and the picklist field
        example usage :
        Id recType1Id = [Select Id from RecordType Where SobjectType = 'Account'
                                            AND DeveloperName like 'Record_Type_2'].Id;
        System.assertEquals(REC_TYPE_1_OPTIONS, PicklistDescriber.describe('Account', recType2Id, 'Industry'));
    */
    public static List<String> describe(String sobjectType, Id recordTypeId, String pickListFieldAPIName) {
        return parseOptions(
                            new Map<String, String> {
                                                     'sobjectType' => sobjectType,
                                                     'recordTypeId' => recordTypeId,
                                                     'pickListFieldName'=> pickListFieldAPIName
                                                    }
                            );
    }

    public static List<String> describe(String sobjectType, String recordTypeName, String pickListFieldAPIName, String contrfieldName) {
        return parseOptions(
                            new Map<String, String> {
                                                     'sobjectType' => sobjectType,
                                                     'recordTypeName' => recordTypeName,
                                                     'pickListFieldName'=> pickListFieldAPIName,
                                                     'contrfieldName' => contrfieldName
                                                    }
                            );
    }

    public static Map<String,List<String>> describeWithDependency(String sobjectType, String recordTypeName, String pickListFieldAPIName, String contrfieldName) {
        Map<String, List<String>> result = new Map<String,List<String>>();
        Map<String, List<String>> depentOptions = PicklistFieldController.getDependentOptionsImpl(sobjectType, contrfieldName, pickListFieldAPIName);
        for(String pickval : PicklistDescriber.describe(sobjectType, recordTypeName, pickListFieldAPIName, contrfieldName)) {
            for(String dep : depentOptions.keySet()) {
                result.put(dep, new List<String>());
                for(String val : depentOptions.get(dep)) {
                    if(val == pickval) {
                        result.get(dep).add(val);
                    }
                }
            }
        }

        return result;
    }

    public static Map<String,List<String>> describeWithDependency(String sobjectType, Id recordTypeId, String pickListFieldAPIName, String contrfieldName) {
        Map<String, List<String>> result = new Map<String,List<String>>();
        Map<String, List<String>> depentOptions = PicklistFieldController.getDependentOptionsImpl(sobjectType, contrfieldName, pickListFieldAPIName);
        for(String pickval : PicklistDescriber.describe(sobjectType, recordTypeId, pickListFieldAPIName)) {
            for(String dep : depentOptions.keySet()) {
                result.put(dep, new List<String>());
                for(String val : depentOptions.get(dep)) {
                        System.debug(val);
                        System.debug(pickval);
                    if(val == pickval) {
                        result.get(dep).add(val);
                    }
                }
            }
        }

        return result;
    }

    /*
        Internal method to parse the OPTIONS
    */
    static List<String> parseOptions(Map<String, String> params) {
        PageReference pr = Page.PicklistDesc;
        // to handle development mode, if ON
        pr.getParameters().put('core.apexpages.devmode.url', '1');

        for (String key : params.keySet()) {
            pr.getParameters().put(key, params.get(key));
        }

        String xmlContent = pr.getContent().toString();

        Matcher mchr = OPTION_PATTERN.matcher(xmlContent);
        List<String> options = new List<String>();
        while(mchr.find()) {
            System.debug(mchr.group(1));
            options.add(mchr.group(1));
        }
        // remove the --None-- element
        if (!options.isEmpty()) options.remove(0);
        return options;
    }
}
Hi,

I have created a simple Rest API endpoint however my test class is not touching the endpoint at all. The API URL mapping is

//** services/apexrest/accounts/0016E00000YNC49/entitlements
@RestResource(urlMapping='/accounts/*/entitlements')
Global with sharing class U4_REST_AccountEntitlements {
    @HttpGet
    global static Account getAccount(){

and returns entitlement values. Using REST Explorer within workbench it works perfectly but when I run the test class it is not returning any values. In fact ... the result is [REST_AccountEntitlements_TEST].RestResource response:RestResponse:[headers={}, responseBody=null, statusCode=null]​

Any help would be much appreciated.
Test.startTest();

           Id recordId = NewServiceAccount.Id;
           RestRequest request = new RestRequest();
           RestResponse response = new RestResponse();
           request.httpMethod = 'GET';

           Request.requestURI  ='/services/apexrest/accounts/'+NewServiceAccount.Id+'/entitlements';
           System.debug(LoggingLevel.Info,'+*+*+*+*+*+*+* '+NewServiceAccount.id);

           System.debug(LoggingLevel.Info,'[REST_AccountEntitlements_TEST].RestResource response:'+Request.requestURI);

           RestContext.request = request;
           RestContext.response = response;

           System.debug(LoggingLevel.Info,'[REST_AccountEntitlements_TEST].RestResource response:'+response); 
  
        Test.stopTest();

 
I have tried this :
trigger Surajtrg on Contact (after insert, after update, after delete)
{
    set<id> act=new set<id>();
    List <Account> lstAccountsToUpdate = new List <Account>();
    if(trigger.isInsert ||trigger.isUpdate)
    {
        for(contact cc:trigger.new)
        {
            act.add(cc.AccountId);
         }
    }
    if(trigger.isDelete)
    {
        for(contact cc:trigger.old)
        {
            act.add(cc.AccountId);
        }
    }
    List<Account> shocksList = [SELECT Id,Youngest__c,(SELECT id,MIN(Age__c) FROM Contact) from Account where Id IN: act]; 
for(Account acc:shocksList) //(Select Id from Contacts)  represents size of Contacts        
{
    Account accObj = new Account ();
    accObj.Id = acc.Id;
   accObj.Youngest__c= acc.MIN(Age__c);
    lstAccountsToUpdate.add(accObj);
}
    Update lstAccountsToUpdate; 
}
 
I have multiple contacts with their different ages. I want to fetch out minimum and max age among all contacts. 
I tried this query....Select id,Min(age__c) from Contact GROUP BY Name.
please correct me
Hi everyone, 

I'm a new developer so please bear that in mind! I'm trying to update an Account's custom fields from a Custom Object called Pub_Opportunity__c. The account has a lookup relationship to the pub_opportunity__c. But I only want the Account to update once with these fields as sometimes there are many pub opportunities related to one Account. I just want to retain the original values. 

When I use the code below, it keeps updating the Account every single time with the new Pub Opportunity's fields regardless of the condition. For example, when I change the Account_Status__c field on the Account to 'Active', when I create a new Pub Opportunity, it still updates the Account_Status__c to 'Closed Won - Implementing'. Even when the Link_to_Contract__c field on the Account is filled out, it still updates the field with the new value from the Pub Opportunity. 

Would appreciate your help!


public static void updatePubs(Map<Id,Pub_Opportunity__c> pubOppMap){
        List<Account> aList = new List<Account>();
        
        for(Pub_Opportunity__c p : pubOppMap.values()){
            Account a = new Account();
            if(a.Account_Status__c != 'Active'){
                a.Account_Status__c = 'Closed Won - Implementing';
                a.id = p.Publisher__c;
               if(String.Isblank(a.Link_to_Contract__c)){
                a.Link_To_Contract__c = p.Link_to_Contract__c;
            }
          
            aList.add(a);
        }
        
        if(aList.size() > 0){
            update alist;
        }
    }
    }
    
I am trying to search through all records passed in by trigger and find ones where buyer zip codes matches an open Open Territory. The "Name" field on Open_Territory__c contains zip codes.

I am getting 2 errors. Variable does not exist: Name, and DML requires SObject or SObject list type: List<Id>.

Any help would be appreciated. 
 
public static void setOpenTerritory(List<dealer__Sales_Up__c> triggerValues) {
        List<Open_Territory__c> openList = [SELECT Id, Name FROM Open_Territory__c WHERE Is_Active__c = true];
        List<Id> suToUpdate = new List<Id>();
        System.debug('openList contains ' + openList);
        // Search through all Sales Ups passed in trigger. Find ones with buyer zip codes matches Open Territory zip and add them to List.
        for(dealer__Sales_Up__c s : triggerValues) { 
            if(s.dealer__Mailing_Zip__c === openList.Name){
                s.Open_Territory__c = true;
                suToUpdate.add(s.Id);
            }
        }
        update suToUpdate;
    }

 
Hi 

require help in class 

global class CDPForecastExtractBatch implements Database.Batchable<sObject> {
    
    String query;
    Forecast_Scenario__c forecastScenario;
    
    global CDPForecastExtractBatch(Forecast_Scenario__c scenario) {
        forecastScenario = scenario;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        query = 'SELECT Id, Deal__c, Deal__r.Parent_Deal_Id__c, Deal__r.Stage__c, Deal__r.IsPlaceholder_Deal__c, Deal__r.IsInfrastructure_Deal__c, Deal__r.RecordType.Name, Deal__r.Is_Cloned_Deal__c, Deal__r.Is_Closed_Deal__c, Deal__r.Forecast_Scenario__c, ';
        query += '(SELECT Id, CDP_Asset__c, Customer__c, Customer__r.Name,Customer__r.Account_Subtype__c FROM CDP_Asset_Customer_Accounts__r) , ';
        query += '(SELECT Id, Development_Deal_Id__c, Land_Name__c, CDP_Asset__c, Land_Area__c, Land_Area_UOM__c, Land_Source__c, Land_Code__c FROM CDP_Land_Strategy__r) '; 
        query += 'FROM CDP_Asset__c WHERE (NOT Deal__r.Stage__c like \'%Lost%\')  AND (Deal__r.Is_Cloned_Deal__c = true OR (Deal__r.Stage__c like \'%Won%\') ) ';
        query += 'AND Deal__r.Hold__c = false AND (Deal__r.IsNamedDeal__c = true OR Deal__r.IsPlaceholder_Deal__c = true OR Deal__r.IsInfrastructure_Deal__c = true OR (Deal__r.Stage__c like \'%Won%\') ) ';
           query += 'AND Deal__r.RecordType.Name NOT IN ('+ '\'Value-Add\'' +')';
        return Database.getQueryLocator(query);
    }

       global void execute(Database.BatchableContext BC, List<sObject> scope) {
        CDPForecastExtractHandler.getChildRecords(scope, forecastScenario);
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}
On the Case object we have the standard lookup field to the standard Account object. I also added a field called "Login_ID__c". We have this same field (Login_ID__c) in the Account object as well. Now when the user enters a Login ID in the case object, based on the value in the Login ID field it should auto populate the Account lookup field because each Account record has a unique Login ID. I have tried using a workflow and process builder but to no avail. From what I’ve researched, I think it’s possible to do this with an apex trigger but I am not familiar with apex at all. Can anybody help me out or offer any insight? Thank you.
 
WHAT: In my Account object when a field "GDPR flag" gets checked,it should automatically fill the "GDPR date" field to be te same date(date on which the flag chcekbox  gets checked).
So we are using the formula field: IF( R2_ACC_CHK_GDPR_UnSub__c , TODAY() , NULL).
ISSUE: Because of this formula field, the "GDPR date"is getting changed everyday to the current day, which is wrong.It should reflect the day when the checkbox was checked and should stay always the same date.i.e if we marked any customer as GDPR on 09th Sept 2018, tomorrow or one year from now , the date should always reflect 09th sept 2018.
How can i achieve that? Can i make some changes in formula field?or can i do it in the triger code?Please help.I am novice so would require your explanation as well.
 
Hello friends, Iam getting error "Variable does not exist: RecursiveTriggerHandler" while deploying the apex trigger to production.
Please find the trigger below

trigger BD_AccountTrigger on Account (after insert, after update) {
  BD_ProcessSwitchSettings__c custSettings = BD_ProcessSwitchSettings__c.getInstance();
 
 System.debug('****************in BD_LeadTrigger');
 
 if(trigger.isInsert || trigger.isUpdate){
   System.debug('****************in BD_LeadTrigger, Trigger.old:'+trigger.old);
   System.debug('****************in BD_LeadTrigger, Trigger.new:'+trigger.new);
 } 
  
 // if(!custSettings.BD_AllTriggersDisabled__c && custSettings.BD_NotesTriggerEnabled__c){
  if(!custSettings.BD_AllTriggersDisabled__c ){
     if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
        new  AC_AccountTriggerHandler().run();
     } 
        
  }
}
I tried to import an Apex trigger and Class I created so that when an opportunity is created a quote is created, with the opportunity's product if it has one. We said me that we have to have 75%code coverage to import it. So I have to create an Apex test. But above my trigger and my class, it is already written 100%, so I don't understand.

Also, my Apex test is only 62%... And I don't know how to increase it. 

/// TRIGGER

trigger Facturation on Opportunity (after insert) {

        List<Id> oppIds = new List<Id>();

        for (Opportunity o : Trigger.new)
            oppIds.add(o.id);

        CreateQuote.createQuote(oppIds);   

}

/// CLASS

public class CreateQuote {

    @future

    public static void createQuote(List<Id> oppIds) {
        List<Quote> lstQ = new List<Quote>();

        //Fetching all the OLIs belonging to the Opportunities of Trigger.new
        List<OpportunityLineItem> olis =[select id, OpportunityId, quantity, PriceBookEntry.Product2Id, UnitPrice, PricebookentryId from OpportunityLineItem where OpportunityId in :oppIds];
        List<Opportunity> opps =[select id, name, CloseDate, Type, Pricebook2Id from Opportunity where Id in :oppIds];

        //Preparing a Map of each Opportunity and their corrresponding LineItems  ( Id of the opportunity => List of the OLIs that belong to the opportunity)
        Map<Id,List<OpportunityLineItem>> mapOppIdOli = new Map<Id,List<OpportunityLineItem>>();
        for (OpportunityLineItem oli : olis) {
            if (mapOppIdOli.containsKey(oli.OpportunityId)) {
                mapOppIdOli.get(oli.OpportunityId).add(oli);
            } else {
                List<OpportunityLineItem> lstOlis = new List<OpportunityLineItem>();
                lstOlis.add(oli);
                mapOppIdOli.put(oli.OpportunityId, lstOlis);
            }
        }

        //Preparing the new quotes - one for each Opportunity
        //List<Opportunity> opps =[select id, name, CloseDate, Pricebook2Id from Opportunity where Id in :oppIds];
        for (Opportunity o : opps) {
            if (o.Type == 'Event') {
                Quote q = new Quote();
                //q.name = 'Credit Note ' + o.name;
                q.name = o.name;
                //q.Montant_1_re_ch_ance__c = 1000;
                q.Date_de_Facture__c = o.CloseDate;
                q.Date_1_re_ch_ance__c = o.CloseDate;
                q.opportunityId = o.id;
                q.Pricebook2Id= o.Pricebook2Id;
                lstQ.add(q);
            }  
        }

        //Inserting the new quotes
        insert lstQ;

        //Preparing the new QLIs - one for each OLI
        List<QuoteLineItem> lstQLI = new List<QuoteLineItem>();
        for (Quote q : lstQ) {
            List<OpportunityLineItem> lstOlis = mapOppIdOli.get(q.OpportunityId);
            if (lstOlis != null) {
                for (OpportunityLineItem oli : lstOlis) {
                    QuoteLineItem qli = new QuoteLineItem();
                    qli.quoteId = q.Id;
                    qli.UnitPrice = oli.UnitPrice;
                    qli.Product2Id = oli.PriceBookEntry.Product2Id;
                    qli.Quantity = oli.Quantity;
                    qli.PriceBookentryid = oli.PriceBookentryId;
                    lstQLI.add(qli);
                }
            }
        }
        //Inserting the new QLIs
        insert lstQLI;
    }
}

/// TEST


@isTest

public class CreateQuoteTest {
    static testMethod void insertNewOpportunity() {
        Test.startTest();

        Product2 testProduct = new Product2(
            Name = 'Happy Funtime Ball'

        );

        insert testProduct;

        PricebookEntry pbEntry = new PricebookEntry(
             Pricebook2Id = Test.getStandardPricebookId(),
             Product2Id = testProduct.Id,
             UnitPrice = 100.00,
             IsActive = true

        );

        insert pbEntry;

        Opportunity testOpportunity = new Opportunity(
            Name = 'Test Opportunity Triggers',
            CloseDate = date.today().addDays(5),        
            StageName = 'Sourcing Demand',
            Type = 'Event',           
            Account_manager_gescom__c = 'Farida Raji',
            Pricebook2Id = pbEntry.Pricebook2Id                      

        );

        insert testOpportunity;

        OpportunityLineItem testOLI = new OpportunityLineItem(
            OpportunityId = testOpportunity.Id,
            Product2Id = testProduct.Id,
            PricebookEntryId = pbEntry.Id,
            Quantity = 5,
            TotalPrice = 5 * pbEntry.UnitPrice        
            //UnitPrice = 1100.00

        );

        insert testOLI;     
        
        OpportunityLineItem testOLI2 = new OpportunityLineItem(
            OpportunityId = testOpportunity.Id,
            Product2Id = testProduct.Id,
            PricebookEntryId = pbEntry.Id,
            Quantity = 5,
            TotalPrice = 5 * pbEntry.UnitPrice         
            //UnitPrice = 1100.00

        );

        insert testOLI2;  
        
        
        Test.stopTest();

    }

}
 
@RestResource(urlMapping='/ContactCRDID/*')
global with sharing class Ebuy_API
{
  @HttpGet
   global static List<Opportunity> doGet()
   {
      RestRequest request = RestContext.request;
        Integer ConCRD= Integer.valueof(request.requestURI.substring(request.requestURI.lastIndexOf('/')+1));
        List<Opportunity> result =  [Select StageName, PrimaryBPCRDID__c, Opportunnity_Source__c, OpportunityNumber__c, Name, 
                                     LastModifiedDate, Id, CreatedDate, Amount, Account.Name, CloseDate From Opportunity  
                                     where PrimaryBPCRDID__c =: ConCRD AND (((NOT StageName  LIKE '9-Closed%') AND 
                                     (NOT StageName  LIKE '8-Closed%')) OR (StageName  LIKE '8-Closed%' AND 
                                     CloseDate > LAST_N_MONTHS:1 )) ];  
       
       return result;
   }
 
}
i mean ,i want to know the general errors we are facing .because i want learn why these errors are faced to impove my knowledge'
example:dml exemption
thank you 
Need Test class for following Rest Service class to insert update delete Lead record.
Can anyone help? please provide positive negative bulk test scenarios.
@RestResource(urlMapping='/Lead')
global class LeadManipulationService {
    
    global class Result {
        public Boolean isSuccess;
        public String lead;
        public String status;
    }
    
  @HttpPost
    global static Result createLead(String firstName, String lastName, String email, String phone, String company) {
        Result res= new Result();
        res.isSuccess = false;
        res.status = 'Error';
        
        Lead l = new Lead();
        l.FirstName = firstName;
        l.LastName = lastName;
        l.Email = email;
        l.Phone = phone;
        l.Company = company;
        
        
        try {
            insert l;
        }catch(DMLException e) {
            return res;
        }
        
     res.isSuccess = true;
        res.status = 'Success';
        res.lead = l.Id;
        return res;   
        
    }
    
    
    @HttpPut
    global static Result updateLead(String firstName, String lastName, String email, String phone) {
        Result res= new Result();
        res.isSuccess = false;
        res.status = 'Error';
        
        List<Lead> l = [
            SELECT
              FirstName,
              LastName,
              Email,
              Phone
            FROM
              Lead
            WHERE
        FirstName LIKE :firstName
            AND
              LastName LIKE :lastName
            LIMIT 1
        ];
        l[0].FirstName = firstName;
        l[0].LastName = lastName;
        l[0].Email = email;
        l[0].Phone = phone;
        
        
        try {
            update l;
        }catch(DMLException e) {
            return res;
        }
        
     res.isSuccess = true;
        res.status = 'Success';
        res.lead = l[0].Id;
        return res;   
        
    }
    
    
    
    @HttpDelete
   global static Result deleteLead() {
        Result res= new Result();
        res.isSuccess = false;
        res.status = 'Error';
        
        String firstName = RestContext.request.params.get('firstName');
        String lastName = RestContext.request.params.get('lastName');
        String email = RestContext.request.params.get('email');
        String phone = RestContext.request.params.get('phone');
        

        List<Lead> leadList = [
            SELECT
                id
            FROM
                Lead
            WHERE
                FirstName = :firstName 
            AND
                LastName = :lastName
            AND 
                Email = :email
            AND
                Phone = :phone
        ];
        
        try {
            delete leadList;
        }catch(DMLException e) {
            return res;
        }
        
     res.isSuccess = true;
        res.status = 'Success';
        res.lead = leadList[0].Id;
        return res;   
        
    }
 
    
}
  • August 21, 2018
  • Like
  • 0
Hi Everyone,

I have created a custom metadata and have kept three values in it. Consider those values as- 
'God'
'Is'
'Great'

Now, I have a list of type string which can either have these three values or altogether different values. I want to compare the custom metadata values agaist this list but I am not able to do that using Apex code. 
Is there a way I can compare String to a custom metadata list.

List <custom_metadataname__mdt> SNamefromCsetting = [Select sname__c from custom_metadataname__mdt];
System.Debug('SNamefromCsetting :' +SNamefromCsetting );
String[] st = Name.split(' , ');



 
  • August 17, 2018
  • Like
  • 0
Racking my brains as to why I can't get the final two lines to pass and hit 100% coverage

It's both branches of the IF statement outstanding, but I thought I had captured that with generating 2 different account records

Any pointers much appreciated!

CLASS
public without sharing class lastViewedAccount{
    public Datetime cDT;
    public String LongDate;
    public String firstname;
    public String lastname;
    public String existinglastviewed;
    public String userid;
    private final Account acc;
    
    public lastViewedAccount(ApexPages.StandardController stdController) {
        this.acc = (Account)stdController.getRecord();
    }
    
    public String getLongDate() {
        cDT = System.now();
        //Formats the datetime value to locale
        LongDate = cDT.format('dd/MM/yyyy HH:mm');
        return LongDate;
    }
    
    
    public void updateField() {
        //Get the user info from the current user
        firstname = System.Userinfo.getFirstName();
        lastname = System.Userinfo.getLastName();
        userid = System.Userinfo.getUserId();
        //Get the Opportunity record to be updated
        Account a = [select Last_Viewed_By__c, Track_Record__c from Account where id = :acc.id limit 1];
        //get existing string of the record, so that new view can be appended to the end of this
        existinglastviewed = a.Last_Viewed_By__c;
        //check to see if the Opportunity has been flagged for tracking
        if(a.Track_Record__c){
            //Assign values to Last Viewed By field and update the record - only concatenate if there is a value there already
            if(existinglastviewed != null){
                a.Last_Viewed_By__c = (existinglastviewed + '; \n' + firstname + ' ' + lastname + ' ' + getLongDate());
            }
            else a.Last_Viewed_By__c = (firstname + ' ' + lastname + ' ' + getLongDate());
            update a;
        }    
    }
    
}

TEST CLASS
@isTest
public with sharing class lastViewedAccountTest {


    static testMethod void triggerTest() {
        
        //Create Account1 - with pre-existing 'Last Viewed By' populated - to test if statement
        Account testAccount1 = new Account(Name = 'testAccount');
        testAccount1.Company_Registered_Number_SOC__c = '00000000';
        testAccount1.Primary_Sector__c = 'Business Goods & Services';
        testAccount1.Sub_Sector__c = 'Point of Sale';
        testAccount1.Organisation_type_SOC__c = 'Limited Company'; 
        testAccount1.Street_Head_Office_SOC__c = 'Test Street'; 
        testAccount1.City_Head_Office_SOC__c = 'London'; 
        testAccount1.Country_Head_Office_SOC__c = 'United Kingdom';
        testAccount1.Last_Viewed_By__c = 'Example User';
        insert testAccount1;
 
 
        ApexPages.StandardController sc1 = new ApexPages.StandardController(testAccount1);
        lastViewedAccount lastViewedAcc1 = new lastViewedAccount(sc1);
        
        System.assert(!String.isEmpty(lastViewedAcc1.getLongDate()));
        lastViewedAcc1.updateField();
        
        
              
        //Create Opportunity 2 - with no 'Last Viewed By' data - to check 2nd branch of if statement
        Account testAccount2 = new Account(Name = 'testAccount');
        testAccount2.Company_Registered_Number_SOC__c = '00000000';
        testAccount2.Primary_Sector__c = 'Business Goods & Services';
        testAccount2.Sub_Sector__c = 'Point of Sale';
        testAccount2.Organisation_type_SOC__c = 'Limited Company'; 
        testAccount2.Street_Head_Office_SOC__c = 'Test Street'; 
        testAccount2.City_Head_Office_SOC__c = 'London'; 
        testAccount2.Country_Head_Office_SOC__c = 'United Kingdom';
        insert testAccount2;
 
 
        ApexPages.StandardController sc2 = new ApexPages.StandardController(testAccount2);
        lastViewedAccount lastViewedAcc2 = new lastViewedAccount(sc2);
        
        System.assert(!String.isEmpty(lastViewedAcc2.getLongDate()));
        lastViewedAcc2.updateField();
        
        
    }   

}

Hello
I'am getting this error on the below trigger can anyone help me in solving this :Apex trigger TaskUpdateLead caused an unexpected exception, contact your administrator: TaskUpdateLead: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 00Q0S000002IXn2UAG: ()

trigger TaskUpdateLead on Task ( After insert) {
    Set<ID> LeadIds = new Set<ID>();
      

    
    //We only care about tasks linked to Leads.
    
    String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();
    
    //Add any Lead ids coming from the new data
    
    if(trigger.new!=null){
        for (Task t : Trigger.new) {
            if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {
                
                if(!LeadIds.contains(t.WhoId)){
                    //adding unique lead ids since there can be many tasks with single lead
                    LeadIds.add(t.WhoId);
                }
            }
        }
    }
    
    //Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)
    
    if(trigger.old!=null){
        for (Task t2 : Trigger.old) {
            if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
            {
                if(!LeadIds.contains(t2.WhoId)){
                    //adding unique lead ids since there can be many tasks with single lead
                    LeadIds.add(t2.WhoId);
                }
            }
        }
    }
    
    if (LeadIds.size() > 0){
        
        
        
        List<Lead> leadsWithTasks = [select id,Activity_Count__c,Last_activity_date__c,(select id,createddate from Tasks) from Lead where Id IN : Leadids];
        
        List<Lead> leadsUpdatable = new List<Lead>();
        //set<ID> LeadIds = new Set<ID>();
        
        
        for(Lead L : leadsWithTasks){
            If(L.Last_activity_date__c == NUll || L.Last_activity_date__c != System.Today())
            {
                Set<Date> set_Uniquedate = new Set<Date>();
                integer Count = 0;
                For(Task tsk: L.tasks)
                {
                    If(!set_Uniquedate.Contains(date.newinstance(tsk.createddate.year(), tsk.createddate.month(), tsk.createddate.day())))
                    {    
                        Count = Count+1;
                        L.Last_activity_date__c = System.Today();               
                        L.Activity_Count__c = Count;
                        leadsUpdatable.add(L);
                        set_Uniquedate.add(date.newinstance(tsk.createddate.year(), tsk.createddate.month(), tsk.createddate.day()));
                    }
                }
            }
        }
         
        if(leadsUpdatable.size()>0){
            
            update leadsUpdatable;
            //update all the leads with activity count
            
        }
        
    }
}
Hi All,

Please help me on below issue.


1. Trigger will work on user mode or system mode
2. In below class account is having one contact but one user able to see contact another user not why another user not able to see contact please help me.

3. As per my knowledge below class will work on system mode.
4. Please help me why another user not ble to see the contact.
 
trigger sampleTrigger on account(after update){
  AccountHelper.Createcontact(Trigger.new);
}

If account type == hot then i need create one conatct for account only one contact.
If contact is existing then no need to crete contact.

public class AccountHelper{

 public static void Createcontact(list<account> accs){
  set<id> acciDs = new set<id>(); 
  for(account acc : accs){
   if(acc.type == 'hot'){    
      acciDs.add(acc.id);   
   } 
 }
 list<account> accslist = [select id,name,(select id from contacts) from acount];
 
 for(account acc : accslist){
     if(acc.contacts.size()== 0){
	 
	    //crating contact here 
	 }
 
 }
}

 
If anybody aware on deleting territories  can help me  because we could not able to delete territories  even though we had "Managed Territories"  permission in profile level. The  territory  trying to delete don't have child  territory but have parent territory.So while deleting I am getting the following error  below.

Error:  
Cannot Delete the Territory
You cannot delete the territory because at least one territory rolls up to it. 

could you please help on this.
I'm looking for a side gig, about 30 hours a week.

My certficiations: http://certification.salesforce.com/certification-detail-print?conId=003G000002FKbh3IAD

I have about 5 years experience with Salesforce. Please send an email: varaprasad4sfdc@gmail.com email for a resume.

Thanks
Varaprasad
@For Support : varaprasad4sfdc@gmail.com
Some users having issue with list views .
Ex : 

DETAILED DESCRIPTION:
1) select a personalized view (here e.g. 003 - My cases in process).
2) open a case out of this list (here e.g. CAS001).
3) go back to the case list by pressing the "Back-Arrow" of the browser .
 
The wrong list of cases is displayed Here.

Any help really appreciated.

Thanks
Varaprasad
Hi ,

Some times in chatter Chatter bold ,italic buttons are not displaying.
User-added image

Please let me know the reason .

Thanks
Varaprasad
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
I have a Parent Object called "Treatement" and a child object "Infusion". For a particular treatement we have to create infusion records. the 1st Infusion record should have infusion number (a field in Infusion) as 1 and 2nd record should have infusion number as 2 , and the count should continue. 

How to achive this..

Thanks 
Hi Everyone.

  i need small help regarding on schedule apex.
  how we will schedule one class with different timings.
EX:i want to schedule one class :  Runs at 4:20; 7:50: 16:20; 20:50 CET these timings.

Thanks in Advance


 
Hi All ,

   i am writing test class for following schedule class 
      global class scheduleAccountWriteXML implements Schedulable{
    
    // Execute method
    
    global void execute(SchedulableContext SC) {
        
        try{
      
// Code to be executed when the schedule class wakes up

            
            CalloutAccountRequest.basicAuthCalloutRequest();
           
            String CRON_EXP = '0 0 * * * ?';
            string jobName = 'Account_Interface_Schedule_job_that_runs_every_1_hour_for_Accounts'; 
            scheduleAccountWriteXML p = new scheduleAccountWriteXML();
            system.schedule(jobName, CRON_EXP, p);              
            
        }     
        
        Catch (Exception e){            
            
            Messaging.SingleEmailMessage emailMessage = new Messaging.SingleEmailMessage();
           
            emailMessage.setToAddresses(new String[] { 'varaprasad.vemula@accenture.com'});
            emailMessage.setSubject('Subject');
            
          
            emailMessage.setPlainTextBody(e.getmessage());
         
            Messaging.SendEmailResult[] emailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { emailMessage}, true);
        }
    }
}

I received code 90%,but test execution will be fail .

@isTest
public class Test_scheduleAccountWriteXML {
    public static testmethod void testaccountxml(){
    Test.StartTest();
              
            String CRON_EXP = '0 0 * * * ?';           
            scheduleAccountWriteXML scc6= new scheduleAccountWriteXML();       
            String jobid = system.schedule('varam', CRON_EXP, scc6);  
        
     Test.StopTest();  
        
         
    }
}


Any help please.


 
Hi Everyone ,

i created one class for generating xml file and by using callouts i am sending file to external system.
Here my requirement is 
  EX : file is more than one mb 1.5 mb
          i need to split xml file one is 1MB
                                          2nd one is 0.5mb
                                           is it possible to split file,,,,  Give me some ideas

Thanks all.
 
Hi

    I need to create multiple tasks in single page and i need to assign to user.Through vf page how we will implement this one .

 We need to have a VF section  so that from same page I can create multiple tasks without navigating to different page. Essentially in new task we need to have all the fields and can only refer what is in Action plan. 

Thanks to all ....
 

 
Hi All

   A and B are objects having lookup relationship
   A is parent and having status field
   B is child having status field
here my requiremeent is parent is having n on of childs in child what is the staus field value i need to update same thing in parent....

Thanks to alll
 
Hi I have come across the below error, using JavaScript in Button.

An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. 
If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support.
 Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information.
 We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1652772134-27944 (-1092651723)
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
var r = "{!Opportunity.Opportunity_Product_Count__c}";
var oppid = "{!Opportunity.Id}";
 

if(r == 1 )
{        
                    window.location.href='/apex/VFPageName?id='+oppid;
}
else
{
    alert ("No Products exists !");

Please help me out with alternative solution ASAP
Hi All,

i need to create one validation rule..

User-added image

in each prefernce picklist field i have 3 values
primary
ok to contact
do not contact

Among all 6 fields i need to select only one field value is primary....


Any Help really Appreciate...

Thanks
varaprasad


 
Hi, 

I am new to Developing and have ran into a problem while playing around in my Dev Org. 

I am trying to create a VF page to display related records. However, I am getting the record Id instead of the Record's Name. Please help.

The issue comes from the fact that I am utilizing the Game__c's custom object Team__c  (which is retrieving the record id) . It doesn't allow me to retrieve the Game__c.Team__r.Name on the VF page as the controller is a different custom object.

Note: The Game__c object looks up to both the Team__C object and the My_Profile__c object.

Controller 
public with sharing class GamesPlayedController
{
    ApexPages.StandardController sc;
    public list <Game__c> Game {get; set;}
    public list <my_Profile__c> MyProfile {get; set;}
    
    
    public GamesPlayedController (ApexPages.StandardController sc)
    {
        this.sc = sc;
        
        Game = [SELECT Game_Outcome__C, Team__c, Player__c,  Team_Score__c, Opponent_Score__c,
                      Opponent_Team_Name__c, Player_s_Point__c,
                      Opponent_Name__c, CreatedDate, Team__r.Name, Player__r.Name
               FROM Game__c
               WHERE X2K__c IN ('2K19','2K18')
               ORDER BY CreatedDate
               DESC
               LIMIT 100];
       
       
         }     
    
    public ApexPages.PageReference SaveBoth()
    {
        insert Game;
        return sc.Save();   
        }  
            
     }

VF:
<apex:page standardController="My_Profile__c" lightningstylesheets="true" extensions="GamesPlayedController">

<Apex:form>
    <apex:pageBlock title="Games Played">
        <apex:pageBlockTable value="{!Game}" var="record">
            //<apex:repeat value="{!Game}" var="Field2">
            <apex:column>
                <apex:facet name="header"> 
                    Game Outcome
                </apex:facet>
                <apex:outputText value="{!record.Game_Outcome__C}"/>
            </apex:column>
            
            <apex:column>
                <apex:facet name="header">
                    Team
                </apex:facet>
                <apex:outputLink value="/{!record.Team__c}">                  
                        <apex:outputText value="{!record.Team__c}"/>                  
                </apex:outputLink>
            </apex:column>
            
            <apex:column>
                <apex:facet name="header">
                    Team Score
                </apex:facet>
                <apex:outputText value="{!record.Team_Score__c}"/>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Opponent Score
                </apex:facet>
                <apex:outputText value="{!record.Opponent_Score__c}"/>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Opponent Team Name
                </apex:facet>
                <apex:outputText value="{!record.Opponent_Team_Name__c}"/>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Player
                </apex:facet>
                <apex:outputLink value="/{!record.Player__c}">             
                        <apex:outputText value="{!record.Player__c}"/>
                </apex:outputLink>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Player's Point
                </apex:facet>
                <apex:outputText value="{!record.Player_s_Point__c}"/>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Opponent Name
                </apex:facet>
                <apex:outputText value="{!record.Opponent_Name__c}"/>
            </apex:column>
            
            <apex:column>
            <apex:facet name="header">
                    Created Date
                </apex:facet>
                <apex:outputText value="{!record.CreatedDate}"/>
            </apex:column>
          // </apex:repeat>

        </apex:pageBlockTable>
    </apex:pageBlock>
</Apex:form>

</apex:page>

User-added image
I have a trigger. If a user who creates a record isn't 'Manager' (UserRole.Name) - record's OwnerId change to GroupQueue.Id. I have a correct test method for scenario, where user-creator is 'Manager', but I don't know how to test if he isn't. I get an error "System.AssertException: Assertion Failed: Expected: 0,Actual 1" here. My code works right. I just can't make this test method. How can I fix it?

Helper:
public static void beforeInsert(List<Obj__c> : newList) {   //for before insert trigger

        Map<Id, User> userMap = new Map<Id, User>([SELECT Id FROM User WHERE UserRole.Name = 'Manager']);        
        Group groupQueue = [SELECT Id FROM Group WHERE Type = 'Queue' AND Name = 'Object Queue' LIMIT 1];
		
 		for(Obj__c obj: newList){
		 		if(!userMap.containsKey(obj.OwnerId)){
					obj.OwnerId = groupQueue.Id;
		 		} 
		}
	}
Test:
@isTest
    private static void createObjByNotManager(){
        
        UserRole userRole = new UserRole(Name = 'Somebody else');
        insert userRole;
        
        Profile profileId = [SELECT Id FROM Profile LIMIT 1];

        User user = new User(
            UserRoleId = userRole.Id,
            LastName = 'Test Code',
			Email = 'test@test.com',
			Alias = 'Tcode',
			Username = 'test1234444@testzsdfsdtfsdf.com',
			CommunityNickname = 'test12',
			LocaleSidKey = 'en_US',
			TimeZoneSidKey = 'GMT',
			ProfileID = profileId.Id,
			LanguageLocaleKey = 'en_US',
			EmailEncodingKey = 'UTF-8'
        );
        insert user;
        
		Group testGroup = new Group(Name = 'Object Queue', Type = 'Queue');
        insert testGroup;
        insert new QueueSobject(QueueId = testGroup.Id, SObjectType = 'Obj__c');
        
        Obj__c obj = new Obj__c(
            Name = 'Test Object'
        );
        System.runAs(user) {
            insert obj;
		}
        
        List<Obj__c> objList = [SELECT OwnerId FROM Obj__c WHERE OwnerId =: testGroup.Id];
        System.assertEquals(positionList.size(), 1);
    }
Hi Expert,

I am new to the programming world. I have a custom controller which insert a contact created on VF page. Now I am not able to write test class for this. I could only cover 56% code.
 
public class TestPopup {
    
    public list<Account> acc{get;set;} 
    public Account acc1 {get;set;} 
    public Contact contact {get;set;}
    public List<Contact> conlist;
    public Boolean displayPopup {get;set;}
    public String accid {get;set;}
       

    public TestPopup(){
        acc = [select ID, Name, AccountNumber,Type from Account];
	    acc1 = new Account();
        conlist = new List<Contact>();
        contact = new Contact();
        	
    }
   
    public list<Account> getacc(){
        return acc;
    }
    
    public void showPopup()
    { 
    	displayPopup = true;
        acc1 = [SELECT Id, Name, Phone, (SELECT lastName FROM Contacts) FROM Account WHERE Id = :accid];
    }
       
    public void closePopup() {
        displayPopup = false;
        
    }

    public PageReference save(){
        contact.AccountId= acc1.Id;
        insert contact;
        ID contactId = contact.Id;
        PageReference pr = new PageReference('/' + contactId);
   		return pr;
    }  
        
}
 
@isTest
public class TestCustomController {
     static testMethod void testMethod1() 
     {
         Account testAccount = new Account();
         testAccount.Name='Test Account';
         insert testAccount;
         
         Contact cont = new Contact();
         cont.LastName = 'Test';
         cont.FirstName = 'Contact';
         cont.AccountId = testAccount.Id;
          // insert cont;
         
         Account testAccount1 = new Account();
         testAccount1 = [SELECT Id, Name, Phone, (SELECT lastName FROM Contacts) FROM Account WHERE Id = :testAccount.Id];
       
         
         
         Test.StartTest(); 
         PageReference pageRef = Page.All_Account; // Add your VF page Name here
         pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
         Test.setCurrentPage(pageRef);
         
         TestPopup testAccPlan = new TestPopup();  
         testAccPlan.getacc();
        // testAccPlan.showPopup(); 
         testAccPlan.closePopup();
         
         Test.StopTest();
         
     } 
}

 
I was provided a Trigger for a custom object called Transaction__c, looking for a Test Step to be able to deploy this to Production?  I'm hoping it would be quick/easy but not sure how to proceed...help?

trigger eOne_SC_RTDS_Transaction_C_I on Transaction__c (after insert) {
set<ID> ids = Trigger.newMap.keyset();
    eOne_SC_RTDS.Process('Transaction__c','insert',ids);
}

Hi,

I am using process builder and have created a very simple criteria against the "Task" object.  The goal of the process is when an email is sent from a lead record to update a field on the lead record with a value of 1.   The email gets sent and I see it in the activity history, but the criteria does not get met therefore my immediate action doesn't execute.   

If I choose Task.TaskSubType of "Call" it works fine, but not with Task.TaskSubType of "Email" as shown in my screenshot for some reason.

User-added image

Any help appreciated.
 

Thanks!

  • September 18, 2018
  • Like
  • 0
// Trigger

trigger Opportunity_Misc on Opportunity (before insert, before Update) 
if(Trigger.isBefore && Trigger.isInsert){

      MyHelperClass.NewStep(Trigger.new);        
    }

// class
public with sharing class MyHelperClass  {
    public static void NewStep(List<Opportunity> newstepopps){

}


// test clas 

@isTest
    public static void testNewStep(){
   
    // create test opportunity 
        Opportunity opp = Test_Helper.CreateOpp(contact,user);
        insert(opp);

Test.startTest();

        Opportunity opp1 = opp.clone(true);
        
            List<Opportunity> newloanopps = AutoAssignCampaignHelper.NewLoan(opp1);    

        Test.stopTest();
}


 
  • September 17, 2018
  • Like
  • 0
I am looking for some help with a trigger. 

I have created a custom object Sales_Order_Line__c which has a Parent Object Exchange_Rate__c. In Sales_Order_Line__c there is a date field called Shipment_Date__c and in the Exchange_Rate__c object there are two date fields called Start_Date__c and End_Date__c.

If the Shipment Date falls within the Start Date and End Date of the Exchange_Rate__c object I would like it to automatically relate to this object.

Can anyone help me with this?
Hi All,

The code  below from (Matheus Sales Ferreira) is for 2 Objects: Registration_Layer__c and Meeting__c. It is a master-detail relationship Meeting__c to Registration_Layer__c. The code below produces several errors which appear on different lines of code, but all start with "Variable Does Not Exist" - Registration_Layer__c and then for datemeeting__c, freepoints__c and points__c.

Errors as above on lines which contain the above fields, so lines 6,7,15,16,17.18.19.20.21.22.23.24.25.26.

I think it is eactly the same issue for each line.
Trigger TrgOnMeeting on Meeting__c (before insert, before Update){
    if(Trigger.isInsert || Trigger.isUpdate) {
        Set<Id> regIds = new Set<Id>();
         
        for(Account meeting : Trigger.new) {
            if(meeting.Registration_Layer__c != null)
                regIds.add(meeting.Registration_Layer__c);
        }
         
        Map<Id, Registration_Layer__c> mapReg = new Map<Id, Registration_Layer__c>([SELECT Id, CertRegFrom__c, ObligatoryPointsObtainedYr1__c, ObligatoryPointsObtainedYr2__c, ObligatoryPointsObtainedYr3__c, ObligatoryPointsObtainedYr4__c, ObligatoryPointsObtainedYr5__c, ObligatoryPointsObtainedYr6__c
                                                                                  FROM Registration_Layer__c WHERE Id IN: regIds]);
         
        for(Account meeting : Trigger.new) {
             
            if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year()) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr1__c += meeting.Points__c;
            } else if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year() + 1) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr2__c += meeting.Points__c;
            } else if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year() + 2) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr3__c += meeting.Points__c;
            } else if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year() + 3) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr4__c += meeting.Points__c;
            } else if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year() + 4) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr5__c += meeting.Points__c;
            } else if(meeting.datemeeting__c.Year() == (mapReg.get(meeting.Registration_Layer__c).CertRegFrom__c.Year() + 5) && meeting.freepoints__c) {
                mapReg.get(meeting.Registration_Layer__c).ObligatoryPointsObtainedYr6__c += meeting.Points__c;
            }
        }
         
        update mapReg.values();
    }
}


 
Hello Guys...
Pls Help Me for this...
1. Create custom object with label 'Demo Object' and API name Demo_Object.
2. Create a 'text' field with label 'Category'.
3. Create a 'lookup' field for 'Opportunity' object.
4. Write trigger for custom object. On insert of custom object record if the value of 'Category' field is equal to 'Opportunity' create a new opportunity record via trigger.
   The opportunity lookup needs to be populated with this new opportunity.
 
Hi All,
//Class use to parse image response
public without sharing class EinsteenPredictionService {

   public cls_probabilities[] probabilities;
    public Predictions__c pdt;    //predictresponse
    class cls_probabilities {
        public String label;    //nachos
        public Double probability;    //0.9994034
    }
    public static String getImagePrediction(String imageURL){
        String stringToParse = '{"probabilities":[{"label":"nachos","probability":0.9994034},{"label":"chips","probability":5.965742E-4}],"object":"predictresponse"}';
        parseImagePrediction(stringToParse);
        return stringToParse;
    }
    
    public static String parseImagePrediction(String imageURL){
        //return (EinsteenPredictionService) System.JSON.deserialize(imageURL, EinsteenPredictionService.class);
        String json=        '{"probabilities":[{"label":"nachos","probability":0.9994034},{"label":"chips","probability":5.965742E-4}],"object":"predictresponse"}';
        return json;
    }
    
}
how to write test class for this class.
Any suggestions?
Can anyone please help to solve the below scenario.
I am having a Case object with two picklist fields
Reason
Secondary reason
The above picklist fields contains many values. I am focusing on whenver a Case is created or updated with Reason value as Test_Reason & Seconday Reason value as Test_Secondary_Reason, I would be assigning the created task by fetching the two fixed users(A & B) stored in a public group(Group name: Test_PG).
I'm trying to write a class that will call a flow. I don't understand why Dev Console won't let me save, telling me that myFlow.start() is an invalid constructor name.
User-added image
Hi, 

I have a list with the following format in apex controller. 

Custom__Object_Analysis__c:{Id=a0L1N00000L1izqUAB, Name=All Accounts, CreatedDate=2018-02-15 15:15:12, isCustom__c=false, Fields__c=0, Filter__c=Industry = '', Object_Name__c=account, Tally__c=0}

How do I serialize this? 
JSON.Serialize() gives Uncaught SyntaxError: Unexpected string 
 I have to count all the tasks or activities for every account record and update a custom account field with number. I have 20 thousand accounts and I have to do it with script not with triggers. I am facing problem while iterating aggregate results. Can anyone help me on this .. Below is my code snippet


Set<Id> Accid=new Set<Id>();
List<Integer> check=new List<Integer>();
for(Account Myacc:[SELECT Id,name FROM Account])
{
Accid.add(Myacc.Id);
}

for(List<AggregateResult> lstAR:[Select Account.name, count(Id) Cnt from Task where Activity_Type__c='member support' and Type_of_Member_Support__c ='Flash consulting' and Account.name=:Accid and AccountId!=null group by Account.name]){
    check.add(lstAR);
    Integer intdata =(integer)check[0].get('Cnt');
    Account acc= new Account();
 acc.Member_Support_Delivered__c=intdata;
}