• Maharajan C
  • ALL STAR
  • 11014 Points
  • Member since 2015
  • Sr.Associate Consultant
  • Infosys


  • Chatter
    Feed
  • 364
    Best Answers
  • 3
    Likes Received
  • 13
    Likes Given
  • 16
    Questions
  • 1250
    Replies
Hi,

Looking from some guidance on how to pre-populate account id on a custom aura component to create contacts. 

I would like to pre-populate account id on the component, when a user clicks on "New Contact", on Account's related contact list. I have declared "force:hasRecordId on the component. but nothing is returned for recordId:
 
<aura:component implements="force:lightningQuickAction,force:hasRecordId">  
     <lightning:input value={!v.recordId}
</aura:component>
However, this does work when i add new contact button to Account's record detail page. 

Any idea why this would not work from related page?

Thanks,
Navin
 
Hi All,
I have a task where I need to create LWC that has two if statements and NavigationMixin. 
The logic is if the account has account number and it's revenue is not less than $1000, then open a window with a new account that has some predefined values. 
Please, see attached code. 
 
import { LightningElement, api, track, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import getAccounts from '@salesforce/apex/accountAura.getAccounts';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class HelloWorld extends NavigationMixin(LightningElement)  {
    @api recordId;

    @track activeStatus='';
    @track accNumber=0;
    @track accRevenue=0;
    @track error=undefined; 
   
    //accessing fields and assigning them to variables
    @wire(getAccounts, {accountID:'$recordId'})
     wiredRecord(result) {
       
       if (result.data) {
         this.error = undefined;
         
         this.activeStatus = result.data.Active__c;
         this.accNumber = result.data.AccountNumber;
         this.accRevenue=result.data.AnnualRevenue;
         
       } else if (result.error) {
         this.error = result.error;
         console.log(result.error);
         this.dispatchEvent(
           new ShowToastEvent({
               title: 'error',
               message: result.error.body.message,
               variant: 'error'
           })
       );     
       }
     }
     
 
     //fire event when user push the button 
     connectedCallback(){
 
         if (this.accNumber==null)
   {
     this.dispatchEvent(
         new ShowToastEvent({
             title: 'error',
             message: 'Account Number cant be null',
             variant: 'error'
         })
     );  
        
     return;    
   }  
 
   else if (this.accRevenue<1000){
    
     this.dispatchEvent(
         new ShowToastEvent({
             title: 'error',
             message: 'You cant submit because Account Revenue is less than $1,000',
             variant: 'error'
         })
     );  
      
     return;  
     
 
   }
   
     else { 
 
           navigateToNewContactWithDefaults();
    
          }
 
   }
 
     //function with default values
     navigateToNewContactWithDefaults() {
         const defaultValues = encodeDefaultFieldValues({
             AccountNumber: this.accNumber,
             AnnualRevenue: this.accRevenue,
             Active__c: 'Yes'
         });
 
         console.log(defaultValues);
 
         this[NavigationMixin.Navigate]({
             type: 'standard__objectPage',
             attributes: {
                 objectApiName: 'Account',
                 actionName: 'new'
             },
             state: {
                 defaultFieldValues: defaultValues
             }
         });
     }
}



For some reason, the LWC ignores if statements and open the window anyway. 

Can I use NavigationMixin and if statements in one LWC?
How can I fix this issue?

  
Thank you, in advance. 
I am new to Flows and having a hard time to implement the logic I am working on. I have a requirement to update the child records(object : Group Segment) picklist field to Status : 'Completed' when the parent record(object : Case) Status is 'Closed' using Flows.
Can someone please guide/help me on this.
This is code apex 
public class displayImageController {
   @AuraEnabled  
    public static List<String> getImage(Id CurrentId){
          List<String> files =new List<String>();
        List<ContentDocumentLink> cdLinks =[SELECT Id,ContentDocument.LatestPublishedVersionID,ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId=:CurrentId];
        for(ContentDocumentLink cdl: cdLinks){
             String FileExtension =[SELECT FileExtension FROM ContentVersion WHERE ContentDocumentId=:cdl.ContentDocumentId].get(0).FileExtension;
            if(Pattern.matches('(png|jpg|jpeg|gif|svg)', FileExtension)){
                  files.add(URL.getSalesforceBaseUrl().toExternalForm() +'/sfc/servlet.shepherd/version/download/'+cdl.ContentDocument.LatestPublishedVersionID);  
            }
        }
        return files;
    }
}

Apex test I don't know what write next

@isTest
public class displayImageControllerTest {
    private static testMethod void testCreate() {
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        Contact cont = new Contact ();
        cont.FirstName = 'FirstName';
        cont.LastName = 'LastName';
        cont.Email='email233@email.com';
        cont.phone='12345678';
        insert cont;
        
        Account acct = new Account(Name='TEST');
        insert acct;
        
        ContentVersion contentVersion = new ContentVersion(
            Title = 'Penguins',
            PathOnClient = 'Penguins.jpg',
            VersionData = Blob.valueOf('Test Content'),
            IsMajorVersion = true
        );
        insert contentVersion;    
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
        
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = acct.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
  }
}
Help to write test class for htttp request  I i can't figure it out
public  with sharing class currencyRates {
    @AuraEnabled
    public static List<Object> getRates(){
        
        String requestData='https://www.nbrb.by/api/exrates/rates?periodicity=0';
        
        Http http =new Http();
        HttpRequest request = new HttpRequest();
        request.setEndPoint(requestData);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        List<Object> result =null;
        if(response.getStatusCode()==200){
            result =(List<Object>)JSON.deserializeUntyped(response.getBody());
        }else{
            ApexPages.Message mes =new ApexPages.Message(ApexPages.Severity.ERROR,'There was an error in reading Data');
        }
        return result;
    }
}
This is code trriger
trigger changeFieldProduct on Product2 (after insert,after update) { 
    List<Task> taskList = new List<Task>();
    for(Product2 prod: Trigger.New){
        if(prod.IsActive__c == false){
         List<OpportunityLineItem> obj = [SELECT OpportunityId,Opportunity.Account.Phone, Product2Id FROM OpportunityLineItem WHERE Product2Id=:prod.id];
            for(OpportunityLineItem  opp :obj){
                 taskList.add(new Task(
                                    Subject='new',
                                    whatId = opp.OpportunityId,
                                       Status='New',
                                    Auto_Created__c=true,
                                    ActivityDate = date.today,
                                    Phone__c = opp.Opportunity.Account.Phone,
                                    Priority = 'High'));
            }
        }
   }
    if(taskList.size()>0){
        insert taskList;
    }
}
Test class write only to 40% but I need get 100% help to solve 

@isTest
public class changeFieldProductTest {
@isTest
    public static void testing(){
       List<Task> taskList = new List<Task>();
       List<Product2> prod = new List<Product2>();
        for(Integer i=0;i<10;i++){
           Product2 p = new Product2(Name='test ' +i, IsActive__c = false);
            prod.add(p);
        }
        Test.startTest();
            insert prod;
        Test.stopTest();
        
       System.assertEquals(10, prod.size()); 
        
       List<OpportunityLineItem> obj = [SELECT OpportunityId,Opportunity.Account.Phone, Product2Id FROM OpportunityLineItem WHERE Product2Id IN:prod];
       
       System.assertEquals(10, prod.size());
    }
}

Hello,

I am stuck on a validation rule -

If Sub Category is either 'Attestation Form Complete' or 'Attestation Form Incomeplete', all the other fields listed must not be blank.

The current formula will not let me create the record even if all the fields listed are completed.  Any suggestions would be helpful.
 

Thanks!
User-added image

Hi,

I have finish button..which when clicked the field status in case object shd get updated to Resolved..I tried the following code but dint work..Can anyone help me with this.

<lightning:recordEditForm 
        recordId="{!v.recordId}"
        objectApiName="Case">
        <lightning:messages />
            <div class="slds-grid">
                <div class="slds-col slds-size_1-of-2 slds-hide">
                    <lightning:inputField fieldName ="Status__c" aura:id ="Consent" value ="" />
                </div>
    </div>
    
                    <lightning:button label="Finish" variant="brand" onclick="{!c.update}"/>
                    </lightning:recordEditForm>

Controller
component.find("Consent").set("v.value", "Resolved");

when i tried alert(component.find("Consent"));

I am getting error like
SecureComponentRef: InteropComponent: markup://lightning:inputField{ key: {"namespace":"c"} }
HI All,
I would like to prevent a user from creating a task against transactional accounts (Account Record Type = TransactionalAccount). So all the other Account records types are fine, just transactional should not have tasks. I found the trigger below. Could anyone change it for me with the Record type instead of the Type picklist? I will also need one like that for Events. I would appreciate your help.
Many thanks
Ewa

trigger TaskCanbeCreatedforSoldtoOnly on Task (before insert, before update) { set<id>accids=new set<id>(); for(task t:trigger.new){ accids.add(t.whatid); } if(!accids.isempty()){ List<Account>lstacc=[select id,Type from account where id in:accids AND Type=:'Bill To Customer']; Map<id,String>mapofaccts=new Map<id,string>(); for(account acc:lstacc){ mapofaccts.put(acc.id,acc.Type); } for(task t:trigger.new){ if(mapofaccts.containsKey(t.whatid)){ t.addError ('Please select the Sold to Customer'); } } } }
Hi All, 

I have created a custom object which I am trying to report on. I am able to create the custom report without any issue. However, The fields in which I have a formula are not showing up in my drag and drop side bar. Can anyone help on why this is happening? 
Hello everyone,
I am very new to the Lightning side of salesforce I have been working with classic mostly but now I also want to switch to Lightning and i want to learn how  to develop lightning components (Aura) and lean about it can you please suggest the best resources from where i can learn it.
Thanks in advance.
I have a use case to create a corresponding Contact every time a User is created. I wanted to use the standard ContactId field on User with a flow so that after the Contact record is created, update ContactId lookup on User, however this does not seem possible?

When I attempt this in execute anonymous, it gives the error "System.DmlException: Update failed. First exception on row 0 with id <id>; first error: UNKNOWN_EXCEPTION, You can't create a contact for this user because the org doesn't have the necessary permissions. Contact Salesforce Customer Support for help.: []"

Does anyone know what the necessary permissions are to write to this field? I can't seem to find any answers yet, probably will contact support after the weekend as well.

Hi I'm looking to find the number of items in a lighting web components for each loop from an apex class?

 

// html
<template for:each={caselist.data} for:item="c" for:index="index">
<div class="ca-table-row cc_table_row" key={c.Id}>
    {c.name}
    </div>
</template>

// JS
</div>
import { LightningElement, api, wire, track } from 'lwc';
import retrieveCases from '@salesforce/apex/Controller.getCaselist';
export default class lightningComp extends LightningElement {
    @wire(retrieveCases)
    caselist; 
    // find how many items are in caselist for each loop
}


 

 

Hi everyone!

I am trying to test this code to obtain 100% coverage, but i can't figure out the problem. When i test it, I don't get an error but the code is still not 100%, kindly seeking your help, Thank you!


Code:
public Pagereference newPage() {
        Id cohortRecordTypeId = Schema.SObjectType.class__c.getRecordTypeInfosByName().get('Cohort').getRecordTypeId();
        String url = 'https://bitwisecommunity.force.com/instructorportal/CohortianRoster?id=' + classId;
        if(classType == cohortRecordTypeId) {
            url += '&type=Cohort';
            
        } 
        
        return new PageReference(url);
    }


Test Class: 
static testMethod void testPagereference(){
        
        class__c newClass = new class__c(name = 'Test Class', class_nights__c = 'Monday / Wednesday', start_date__c = date.today() - 10, end_date__c = date.today() + 45);
        insert newClass;
        Test.startTest();
        // String cohRecordType = Schema.SObjectType.class__c.getRecordTypeInfosByName().get('Cohort').getRecordTypeId();
        PageReference pref = Page.CohortianSelector;
        

        Test.setCurrentPage(pref);
        pref.getParameters().put('id',newClass.Id);
        ApexPages.StandardController sc = new ApexPages.StandardController(newClass);
        CohortianSelectorController myPage = new CohortianSelectorController(sc);
        myPage.newPage();
        Test.stopTest();
}

I keep getting the following error while running my Apex Test Class. If I could please get assistance in resolving the problem I would appreciate it. I continue getting the following error:

System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: Sminull90 (max length=8): [Alias]

Below is my code:

Apex Class:

public  class NewUtilStaffProcess {
       @future
       public static void createUtlUser(Id recid) {
            
           Contact gcon = [SELECT Email, Lastname, Firstname, Middlename, AcctId
                            FROM   Contact
                            WHERE  Id = :recid];
           
           Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
           
           Id acctsTypeId = [SELECT Id
                            FROM   RecordType
                            WHERE  SObjectType = 'Account'
                            AND    Name = 'Account Source'].Id;
           
           String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;
           
           
           String formatUsrName;
           String setUsrLoc;
           
           Account retAcct = [SELECT Id, HAVNA_Country__r.HAVNA_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                               FROM   Account
                               WHERE  Id = :gcon.AcctId
                               AND    recordTypeId = :acctsTypeId
                               LIMIT 1];
           
           if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+retAcct.Hav_Locality__c;
        
           if (retAcct.Hav_Street__c == 'City/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C1';
         
           if (retAcct.Hav_Street__c == 'State/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C2';
        
             
           if (gcon.middlename == null) {
               formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               Integer midSize = gcon.Middlename.length();
               if (midSize == 1) {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }

           System.debug('Formatted Username: '+formatUsrName);
      
           User u       = new User(Alias    = gcon.Lastname.deleteWhitespace().trim().length() > 4 ? gcon.Lastname.deleteWhitespace().trim().substring(0,3)+setUsrLoc: gcon.lastname+setUsrLoc,
                         Email              = gcon.Email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = gcon.Lastname,
                         FirstName          = gcon.Firstname,
                         MiddleName         = gcon.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);
           
           UtilStaffPermSet.assgnPermissionSet(recId, u.Id);  
           System.resetPassword(u.Id, True);

      }
}

Apex Test Class:

@isTest
public class NewUtilStaffProcessTest {

   public static testMethod void InitialTest() {

        /* Get Record Id Type */   
        Id conTypeId;
        Id acctTypeId;
        String formatUsrName;
        String setUsrLoc;
        
        conTypeId = [SELECT Id  
                     FROM   RecordType
                     WHERE  SObjectType = 'Contact'
                     AND    Name = 'Utility Staffer'].Id;  

       
        Id acctsTypeId = [SELECT Id
                      FROM   RecordType
                      WHERE  SObjectType = 'Account'
                          AND    Name = 'Account Source'].Id;

        Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
        String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;

        Integer midsize;
       
        //Create new State record; initialize required field(s), then insert
        HAV_State_and_Country__c state  = new HAV_State_and_Country__c();
        state.Name                = 'Oregon';
        state.HAV_Letter_Code__c = 'OR';
        state.HAV_Type__c        = 'State';
        Insert state;
        
        //Create new Account record; initialize required field(s), then insert
        Account acct = new Account(Name='Oregon Local 7');
        acct.Hav_Locality__c     = '90';
        acct.Hav_Street__c     = 'Local/Surveyor';
        acct.RecordTypeId     =  AcctTypeId;
        acct.HAV__Country__c    = state.id;
    insert acct;

        //Create new Contact record; initialize required field(s), then insert
        Contact con  = new Contact();   
        con.FirstName       = 'Ralph';  
        con.LastName        = 'Smith';
        con.Middlename      = 'Otis';
        con.RecordTypeId    =  conTypeId;
        con.email           = 'rsmith8@verizon.com';
        con.AcctId          = acct.id;
          
        //Insert Contact
        Insert con ;
       
          System.debug(con.id);
 
       Account retAcct = [SELECT Id, HAV_Country__r.HAV_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                          FROM   Account
                          WHERE  Id           = :con.AcctId
                          AND    recordTypeId = :nomsTypeId
                          LIMIT 1];
                          
       if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAV_Country__r.HAV_Letter_Code__c+retAcct.Hav_Locality__c;
 
       if (con.middlename == null) {
           System.debug('3: '+setUsrLoc);
               formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               System.debug('4: '+setUsrLoc);
               midSize = con.Middlename.length();
               if (midSize == 1) {
                   System.debug('5: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   System.debug('6: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }
           
 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
 system.runAs(thisUser){
         User u       = new User(Alias      = con.LastName.deleteWhitespace().trim().length() > 4 ? con.LastName.deleteWhitespace().trim().substring(0,4)+setUsrLoc: con.LastName+setUsrLoc,
                         Email              = con.email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = con.LastName,
                         FirstName          = con.Firstname,
                         MiddleName         = con.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);  

                        
        Test.startTest();
       
        NewUtilStaffProcess.createUtlUser(con.id);
 
        Test.stopTest();
        system.debug('Done');
    }
     }
}

Thanks.
User cannot change record owner If user is not System Admin, Industry is null and Account created after 1/1/2017
I tried this formula where the Profile Id is for System Administrator  but it fires even if the System Admin is editing the record.
$User.ProfileId  <> "0ei0000001DLN6"&&
 ISCHANGED( OwnerId )&&
 ISBLANK(TEXT(Industry ))&&
  DATEVALUE(CreatedDate) > DATE(2017,01,01)
 
My test case for a before insert/update trigger on Contact should be very simple, which means I am missing something obvious...the trigger itself takes the City, State Code, and Zip and pulls the county name from a custom county object.  This trigger is working as intended and populates the county name with no issue.  

What I can't figure out is why my test class does not return a value for the county after the insert.  (The insert code and requery works perfectly when running in an Execute Anonymous window). 

Below is the code for the insert test.  After inserting a new contact, when I try to requery for the new hed__Mailing_County__c value, the value is null, but it does pull the new contact id.  Any help is much appreciated!  :-)
 
@isTest
private class Contact_County_Test {
    static testMethod void TestInsertContact() {
        // Create contact with city, state, zip populated
        Contact con = new Contact(FirstName = 'TestInsert', 
                                  LastName = 'TestContact', 
                                  MailingCity = 'My City', 
                                  MailingStateCode = 'WI', 
                                  MailingPostalCode = '12345',
                                  MailingCountryCode = 'US',
                                  hed__Mailing_County__c = '');
        Insert con;

        //Requery to pull in new county name
        con = [SELECT hed__Mailing_County__c FROM Contact WHERE Id = :con.Id LIMIT 1];

         //Verify County Name is populated correctly
         System.assertEquals('County Name', con.hed__Mailing_County__c);
    }
}

 
I've successfully plotted the accounts on Google Map with Lightning Component and it works in Sandbox...but don't know how to write a test code for the ApexClass.

I describe the codes below and hope anyone can help with the test code part. Thank you!

Component (MapNearbyAccount.cmp)
<aura:component controller="MapNearbyAccountController" implements="flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="mapMarkers" type="Object"/>
    <aura:attribute name="selectedMarkerValue" type="String" />
    
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    
    <div class="slds-box slds-theme--default">
        <lightning:map 
                       mapMarkers="{! v.mapMarkers }"
                       selectedMarkerValue="{!v.selectedMarkerValue}"
                       markersTitle="accounts nearby"
                       listView="auto"
                       showFooter="false"
                       onmarkerselect="{!c.handlerMarkerSelect}" />
    </div>
</aura:component>
Controller (MapNearbyAccount.js)
({
    init: function (cmp, event, helper) {
        var recordId = cmp.get("v.recordId");     
        var action = cmp.get("c.getAccounts");
        action.setParams({recordId :recordId});
        cmp.set('v.mapMarkers', [{location: {}}]);

        action.setCallback(this, function(response){
            
            var accounts = response.getReturnValue();
            var markers = [];
            for(var i = 0; i < accounts.length; i++){
                var acc = accounts[i];
                markers.push({
                    location: {
                        Country : acc.BillingCountry,
                        State : acc.BillingState,
                        City: acc.BillingCity,
                        Street: acc.BillingStreet
                    },
    
                    icon : "standard:account",
                    value: acc.Id,
                    title: acc.Name,
                    description:acc.Description
                });
            }
            
            if(markers.length != 0){
                cmp.set('v.mapMarkers', markers);
            }
        });

        $A.enqueueAction(action);
    },

    handlerMarkerSelect: function (cmp, event, helper) {
        console.log(event.getParam("selectedMarkerValue"));
    }
});
ApexClass (MapNearbyAccountController)
public class MapNearbyAccountController {
    @AuraEnabled
    public static List<Account> getAccounts(String BillingCity, String BillingState, String recordId){
        Account acct = [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet, Industry FROM Account WHERE Id =:recordId];
        
        return [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet,Description
                FROM Account 
                WHERE BillingState = :acct.BillingState AND BillingCity LIKE :('%' + acct.BillingCity + '%') AND Industry = :acct.Industry LIMIT 10];
    }
}
TestClass
@isTest
public class MapNearbyAccountControllerTest {
@isTest
    static void testMapNearbyAccountController() {
        Account acc1 = new Account();
        acc1.Name='acc1';
        acc1.BillingCity='Shibuya';
        acc1.BillingState='Tokyo';
        insert acc1;
        
        MapNearbyAccountController ctrl = new MapNearbyAccountController();
        
        Test.startTest();
            List<Account> getAccounts = ctrl.getAccounts();
            System.assertEquals(false,getAccounts.isEmpty());
        Test.stopTest();
    }
    
}
I have a trigger that works, but I want to add criteria.
If the Sales Engineering Request “Status” does not equal “Approved” or “Unable to Meet Request”, then trigger this.
How do I modify this? Thank you for your help.

My Trigger:
trigger FeedCommentTest on FeedComment (after insert) 
{
    for(FeedComment f : Trigger.New)
    {
        if(UserInfo.getProfileId()  == '00e6w000000FjiUAAS')
        {
            Sales_Engineering_Request__c SalesEngineeringRequestToUpdate = [SELECT ID FROM SALES_ENGINEERING_REQUEST__c WHERE ID =: f.ParentId];
            SalesEngineeringRequestToUpdate.Status__c = 'Approved';
            Update SalesEngineeringRequestToUpdate;
        }          
    }
}
I am trying to get code coverage for the class below:
public class redirectToWebinarPageController{
    public pageReference redirectURL(){
        
        //get the external id from the URL
        String externalId = ApexPages.currentPage().getParameters().get('externalId');
        
        //query the record.
        Webinar__c webinarRecord = [select id from Webinar__c where Webinar_Count__c =: externalId];
        
        //redirect to detail page of the above record.
        return new pageReference('/'+webinarRecord.id);
       
    }
}
Here is the test I have and am getting 75% coverage but I would prefer to know how to get 100%
@isTest 
public class redirectToWebinarPageControllerTest {
    public static testMethod void testredirectURL() {
        test.startTest();
        PageReference pageRef = Page.redirectToWebinarDetailPage;
        
        //Your test data logics
        Account testAccount = new Account();
        testAccount.Name = 'Account Name';
        insert testAccount;
        
        Contact testContact = new Contact();
        testContact.LastName = 'Contact';
        testContact.FirstName = 'Test';
        testContact.Email = 'testContact@testing.com';
        insert testContact;
        
        Webinar__c w = new Webinar__c();
        w.Name = 'Test Webinar';
        w.Account__c = testAccount.id;
        w.Communication_Type__c = 'Client 4';
        w.Delivery_Method__c = 'Self Study';
        w.Contact__c = testContact.id;
        insert w;
        
        String testExternalId = w.Webinar_Count__c;

        Test.setCurrentPage(pageRef);
			
			pageRef.getParameters().put('externalId',testExternalId);
			
			redirectToWebinarPageController controller = new redirectToWebinarPageController();
			controller.redirectURL();
        
   		test.stopTest();
     }
}
Thank you in advance, I am really new to writing test classes and would love to know what I am missing here.
Handle force:refreshView Event in LWC: (<aura:handler event="force:refreshView" action="{! c.action }"/> in LWC)

For $A.get('e.force:refreshView').fire(); we have some alternate in LWC  --->  eval("$A.get('e.force:refreshView').fire();");
https://www.sfdcpanther.com/how-to-refresh-page-using-lightning-web-component/
https://salesforce.stackexchange.com/questions/251299/force-refresh-view-in-lwc


But force:refreshView Event handle there is no alternate as of now in LWC. If there is any find out please post below.

For this i have three working idea:

1. using broker Aura and broker LWC Compoenent, pubsub communication. 
https://github.com/mitchspano/LWCRefreshDemo
2. Using Aura Component and Lightning Messaging Service.
3. using Platform Event to directly refresh the LWC Component.


For a demo purpose i have took the below scenario:

1. Created the standard quick action to create contact from Account Page.
2. Created the custom LWC Lightning datatable to show the related contacts under account and placed this component in Lightning Account Detail Page.
3. So, whenever i create contact from quick action my datatable needs to refresh without any manual page refresh.

If this post helps any one give me your likes on this post.

Code is added in below same post.

Thanks,
Maharajan.C
Hi Guys,

From last month itself I am not recieving any replies from Salesforce developer forum if i posted answers for someones's questions.

Before a month it's working fine. And also forum page not  loading fully only am able to see 10 - 20 Questions. Number of replies and Solved button also not visible in questions.

Any idea how to solve this...

Thanks,
Maharajan.C
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
We have the managed package which is created by us so we are try to install this package  some other org.

It works fine in all orgs but in one org we have the error message like below:

 (UpdateAcc-2) myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified

The UpdateAcc is the Process builder which call the Apex Class.

In the package also we have these components but we got the Error!!!

Any one please help on this!!!

Thanks,
Raj
Hi Experts,

Hope some one wil help me:

Salesforce going to update the certificates. Please refer the below Link.

https://help.salesforce.com/articleView?id=000269027&language=en_US&type=1

So Here i have to do the test compatibility  in my environment for MiddleWare and Integration:

Can any one please let me know how to perform the below steps: 

For Middleware/Integrations
To test the compatibility of an API client that uses SOAP to communicate with Salesforce:
  • Set up an API client in a test environment.
  • In that test environment, change the API client's login endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com tohttps://certtest.force.com.
  • As an example, changehttps://login.salesforce.com/services/Soap/u/32.0 to https://certtest.force.com/services/Soap/u/32.0 while leaving the path as-is.
  • Log in with that API client.
  • If you see an error message that resembles the following: "INVALID_LOGIN: Invalid username, password, security token; or user locked out." or “Content is not allowed in prolog.”, then this test passed and your integration trusts DigiCert-signed certificates.
    • The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
  • If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
 
To test the compatibility of an API client that uses REST to communicate with Salesforce: Thanks,
Raj

 
We are using the chatter answers in community which is going to retire after Winter 18 release. Wanted some suggestions to perform the migration...below are the research...
Investigated on Q&A Migration App but wanted to know if someone has used this and its outcome. Was there any data impact? If yes, then how can we overcome that?.
What is the alternative? Is data loader an option?
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(Job Location : Any where).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(India or Any Country).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
 
Hi All,

Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup

Thanks,
Raj
Hi All,

Can anyone please give a example third party app name to calculate the Opportunity Stage Duration (inbetween stages also).
Example : Proposal,Qualified,Ready Invoice,Negoatiation,Closed won.
In there i want to calculate the stage duration from Qualified to Closed won.Starting stage must be Qualified End stage Closed won
Qualified to Ready Invoice =?
Ready Invoice to Negoatiation =?
Negoatiation to Closed won =?

And also for Sales vs Quota report third party App.

Thanks,
Raj
Hi All,

Can you please anyone give a test class for me to the below Apex Class.

Public class AccountDisplatRecClsExtn{
Public id Current_Acc_Id;
    public AccountDisplatRecClsExtn(ApexPages.StandardController controller) {
Current_Acc_Id = controller.getRecord().id;
    }
     

  public List<Question__c> getcontList(){
   List<Question__c> accList = [select id,Name,AssessmentId__c,AssessmentId__r.Name,External_ID__c,Friendly_Name__c,Question_Plain__c,Question_Style__c,Sort_Order__c,(Select Id,Name,Red_Flag__c,Scoring__c from answers__r) from Question__c where AssessmentId__c=:Current_Acc_Id ORDER by Sort_Order__c ASC];
   return accList;
  
  }
    }

Thanks,
Raj
 
Hi,

In my salesforce org when i convert a lead it creates multiple account,contacts and opportunities at the same time and when i see the created by timings and created by user both are same.

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_sales_leads_edit_converted_leads.htm

In above link there is an article i studied about permission set which will enalble us to create multiple account,contacts and opportunities and we can able to view lead again in salesforce detail page but i disabled this options.

Even though i disabled this option i have duplicates created in my salesforce org and i have lead which i can edit on detail page after it converted...I didn't have any trigger.

Please help !!!!!!!!

Thanks,
Raj
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
Hi All,

Please Help!!!
Evaluation Criteria : Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
Rule Criteria Opportunity :  StageEQUALSClosed Won
Workflow Action : Email Alert

>Here First my record meet the above rule criteria based on the evaluation criteria it sends an an Email i.e Opportunity stage equals Closed   Won
>After that in that same record i change the Opportunity stage to Need Analysis so now the record dont met the criteria so there is a no        Email
>Then i changed that Opportunity record stage to Closed Won now the record meet the criteria so its send an email again but i want to stop    the Sending an Email Now.


Thanks in Advance!!!
Raj.
Hi All,

Any One  please help me to code coverge because i got only 43% coverage

ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }


Thanks,
Raj.
Hi All,

Can any one Please help to write a test class to my Trigger


trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Test_Setting__c tm;//Assinging Custom setting To the variable tm
    tm=Test_Setting__c.getorgdefaults();
    String Template=tm.Template__c;
    Decimal Days=tm.Threshold_Days__c;
     
    
    for(CampaignMember campMem : Trigger.new){//
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
         
            }
            
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
    if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
       mail.setTargetObjectId(ld.Ownerid);                           
      mails.add(mail);
  Messaging.sendEmail(mails);
}
}
}

Thanks
​Raj.
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
How write test class for the following code it:-
    
        public static void script(){
            List<OpportunityLineItem> oppLine= new List<OpportunityLineItem>();
    oppLine=[Select TotalPrice from OpportunityLineItem where Name like '%abc%' AND OpportunityId IN (Select id from Opportunity Where StageName='Closed Won')];
     System.debug(oppLine);

     Decimal tp=0;

    for(OpportunityLineItem op1:oppLine){
        tp=tp+op1.TotalPrice;
    }
    System.debug(tp);
        }
    
    I could not reach the 75% for above code.
    Thanks
Hi

can anyone tell me how to throw error message in record triggered flow?

Thanks in Advance.
Hi - I'm not good with formulae...

I have a number field - Support, 
I'd like a new formula field - 
if value is <10, "low"
if value 10-18 "high"
if value >18 "incomplete"

I can see how to do an if based on <10, going low/high... but needing the 3rd option has got me stuck.
Hi all,

I am trying to run a validation rule, but this is not even allowing me to set the required field and the message is only showing 'Snag it'.
Here the requirements first (object Case):
Case Subtype should be filled if Case Status is either ('On Hold' and substatuses 'On Hold X'/'On Hold Y'/'On Hold Z/On Hold W'
OR
Case Status ('Escalated'  and Substatuses 'Escalated A'/'Escalated B'/'Escalated C'/'Escalated D')
OR
Case Status ('Assigned' and Substatuses 'Assigned-Support'/'Assigned-Production')
OR Case Status ('Closed' and Substatuses 'Closed A'/'Closed B')

The Case Substatus field is based on a picklist value set of the same name.

Here my validation rule:
 
AND(
ISBLANK(TEXT(CaseType__c)),  
OR(
OR(AND(ISPICKVAL(Status, 'On Hold'), ISPICKVAL(SubStatus__c, 'On Hold - X')),
AND(ISPICKVAL(Status, 'On Hold'), ISPICKVAL(SubStatus__c, 'On Hold - Y')),
AND(ISPICKVAL(Status, 'On Hold'), ISPICKVAL(SubStatus__c, 'On Hold - Z')),
AND(ISPICKVAL(Status, 'On Hold'), ISPICKVAL(SubStatus__c, 'On Hold - W'))
),
OR(AND(ISPICKVAL(Status, 'Escalated'), ISPICKVAL(SubStatus__c, 'On Hold - A')),
AND(ISPICKVAL(Status, 'Escalated'), ISPICKVAL(SubStatus__c, 'On Hold - B')),
AND(ISPICKVAL(Status, 'Escalated'), ISPICKVAL(SubStatus__c, 'On Hold - C')),
AND(ISPICKVAL(Status, 'Escalated'), ISPICKVAL(SubStatus__c, 'On Hold - D'))
),
OR(AND(ISPICKVAL(Status, 'Closed'), ISPICKVAL(SubStatus__c, 'Closed - A')),
AND(ISPICKVAL(Status, 'Closed'), ISPICKVAL(SubStatus__c, 'Closed - B'))
),
OR(AND(ISPICKVAL(Status, 'Assigned'),
ISPICKVAL(SubStatus__c, 'Assigned - Production')),
AND(ISPICKVAL(Status, 'Assigned'),
ISPICKVAL(SubStatus__c, 'Assigned - Support')))
)
)
)

 
Hi,

Looking from some guidance on how to pre-populate account id on a custom aura component to create contacts. 

I would like to pre-populate account id on the component, when a user clicks on "New Contact", on Account's related contact list. I have declared "force:hasRecordId on the component. but nothing is returned for recordId:
 
<aura:component implements="force:lightningQuickAction,force:hasRecordId">  
     <lightning:input value={!v.recordId}
</aura:component>
However, this does work when i add new contact button to Account's record detail page. 

Any idea why this would not work from related page?

Thanks,
Navin
 
I am trying to run a pair of vaildations rules, but they are not working good.
Here the requirements first (object Case):
Case Subtype should be filled if Case Status is either 'On Hold', 'Escalated' or (Case Status = 'Assigned' and Case Substatus = 'Assigned-Support')
Work-Size should be filled if Case Subtype is filled
All these are picklists.
The Case Substatus field is based on a picklist value set of the same name.

These are my validation rules:

1. Empty_Case_Type:
 
IF(OR(ISPICKVAL(Status, 'On Hold'),
ISPICKVAL(Status, 'Escalated'),
AND(ISPICKVAL(Status, 'Assigned'),ISPICKVAL(SubStatus__c, 'Assigned - Support'))),
true, false)
2. Empty_Work_Size:
 
IF(NOT(ISBLANK(TEXT(CaseType__c))),
true, false)
Unfortunately the combination is not working.
If I have already a value in the field Case Type and I choose Status=Assigned and Substatus='Assigned-Support' the validation rule is still asking me for selecting a value in the field Case Type OR

If I have already a value in both fields Case Type and Work Size and I choose Status= Assigned and Substatus='Assigned-Support' the validation rule still asks for selecting a value in the field Case Type.

No idea what can be wrong in my validation rules.
I would appreciate any advice.

 
I am allocating a customer community user license whenever a lead is converted into contact and it's working fine. below is my code:
trigger CreateCommunityUser on Contact (After insert) {
    
if(Trigger.isInsert){
         for(Contact co : trigger.new){
Contact con = [select id,email,firstName,lastname,accountId from Contact where Id =:co.Id];         
Database.DMLOptions dmo = new Database.DMLOptions();
dmo.EmailHeader.triggerUserEmail = false;       
dmo.EmailHeader.triggerOtherEmail = false;
dmo.EmailHeader.triggerAutoResponseEmail = false;       
dmo.optAllOrNone = false; */

// create portal user
string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):'';
nick += Datetime.now().getTime();
User newUser1 = new User(alias=con.firstName, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_US',contactId = con.Id,timezonesidkey = 'Asia/Dubai',username = con.email,CommunityNickname = nick,ProfileId ='00e6F000001kZ4C', IsActive = true);
newUser1.setOptions(dmo); 
insert newUser1;
         }
     }
}

Because of this code, most of my other test classes are failing with these errors:
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateCommunityUser: execution of AfterInsert
caused by: System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: FirstName (max length=8): [Alias]
Trigger.CreateCommunityUser: line 16, column 1: []

Please guide me where am I going wrong.
Thanks already.
I have a trigger that adds a case comment depending on the field Macro option chosen.  Here's the trigger snippet 
trigger CW_DSS_CaseTrigger on Case (after update) {
  if(CWcheckRecursive.runOnce())
    {
    
   
   List<caseComment> caseCommentList = new List<caseComment>();
    for (Case c: Trigger.new)
    {
        
        caseComment cc = new caseComment();
        if(c.Macros__c == 'Application Support information'){
                cc.parentid = c.ID;
                cc.commentbody = 'For application (DSSi and Relay Server) support and troubleshooting requests, please provide the following information.'+'\n' +
                                    'Minimum DSS Ticket Information requirements:'+'\n' +
                                    'Site Name:' +'\n' +
                                    'Site Contact: (For possible Site IT related issues)' +'\n' +
                                    'DSSi Software Version:' +'\n' +
                                    'Problem/Inquiry:' +'\n' +
                                    'Troubleshooting Steps Taken:' +'\n' +
                                    'This information is required with all DSS support requests. Failure to provide this requested information may delay your request.';
                cc.ispublished = true;
                casecommentlist.add(cc);
               
        }
How do I get this covered in a test class?  Here's a snippet of my test class
private class TestCW_DSS_CaseTrigger{
    
    
    
    static testMethod void CW_DSS_CaseTriggerTest(){
        Id caseRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Detect - Fatigue Management (DSS)').getRecordTypeId();
        ID accRecordTypeID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Worksite').getRecordTypeId();
        Account a1 = new Account(Name='Carlin Test', RecordTypeID = accRecordTypeID, DSS_Account__c = true);
        insert a1;
      
        Case cs1 = new Case();
cs1.RecordTypeId = caseRecordTypeId;
cs1.Site_Dealer_Name_DSS__c = a1.Id;
cs1.OwnerId = UserInfo.getUserId();
cs1.CW_Type__c = 'Question';
cs1.Status = 'New';
cs1.Subject = 'This is my case';
cs1.Description = 'This is my description';
cs1.Incident_Start__c=Date.today();
cs1.Priority = 'Normal';
cs1.Subsystem_Type__c = 'Detect Analytics - API';
insert cs1;
    }

    static testMethod void testCaseMacros1() {
    Id ortId = [SELECT Id, Name FROM RecordType WHERE Name='Detect - Fatigue Management (DSS)'].id;
    RecordType rtAcct = [select Id from RecordType WHERE Name = 'Worksite' and SobjectType = 'Account' limit 1];
    //create account
    Account a1 = new Account(Name='Carlin Test', RecordType = rtAcct, DSS_Account__c = true);
    User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];        
    test.startTest();
    System.runAs (thisUser) {
        
        Case cse = new Case(RecordTypeId = ortId, Site_Dealer_Name_DSS__c = a1.Id, CW_Type__c = 'Incident', Subsystem_Type__c = 'Detect Analytics - API',
        Status = 'New', Subject = 'This is my case', Description = 'This is my description', Incident_Start__c=Date.today());
        Database.insert(cse);
        cse.Macros__c = 'Application Support information';
        Database.update(cse);
        cse.Macros__c = '';
        Database.update(cse);
        
      test.stopTest();

    }}


 
  • January 06, 2021
  • Like
  • 0
Hello everyone. I created a flow today using the flow builder flowId=30129000000ULTsAAO and added the flow to the lightning page layout. My question is there a way to instead of adding the flow to the page layout could you add a button to the page layout instead to execute the flow see the image I am gathering two pieces of information
User-added image 
Hi All,
I have a task where I need to create LWC that has two if statements and NavigationMixin. 
The logic is if the account has account number and it's revenue is not less than $1000, then open a window with a new account that has some predefined values. 
Please, see attached code. 
 
import { LightningElement, api, track, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import getAccounts from '@salesforce/apex/accountAura.getAccounts';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class HelloWorld extends NavigationMixin(LightningElement)  {
    @api recordId;

    @track activeStatus='';
    @track accNumber=0;
    @track accRevenue=0;
    @track error=undefined; 
   
    //accessing fields and assigning them to variables
    @wire(getAccounts, {accountID:'$recordId'})
     wiredRecord(result) {
       
       if (result.data) {
         this.error = undefined;
         
         this.activeStatus = result.data.Active__c;
         this.accNumber = result.data.AccountNumber;
         this.accRevenue=result.data.AnnualRevenue;
         
       } else if (result.error) {
         this.error = result.error;
         console.log(result.error);
         this.dispatchEvent(
           new ShowToastEvent({
               title: 'error',
               message: result.error.body.message,
               variant: 'error'
           })
       );     
       }
     }
     
 
     //fire event when user push the button 
     connectedCallback(){
 
         if (this.accNumber==null)
   {
     this.dispatchEvent(
         new ShowToastEvent({
             title: 'error',
             message: 'Account Number cant be null',
             variant: 'error'
         })
     );  
        
     return;    
   }  
 
   else if (this.accRevenue<1000){
    
     this.dispatchEvent(
         new ShowToastEvent({
             title: 'error',
             message: 'You cant submit because Account Revenue is less than $1,000',
             variant: 'error'
         })
     );  
      
     return;  
     
 
   }
   
     else { 
 
           navigateToNewContactWithDefaults();
    
          }
 
   }
 
     //function with default values
     navigateToNewContactWithDefaults() {
         const defaultValues = encodeDefaultFieldValues({
             AccountNumber: this.accNumber,
             AnnualRevenue: this.accRevenue,
             Active__c: 'Yes'
         });
 
         console.log(defaultValues);
 
         this[NavigationMixin.Navigate]({
             type: 'standard__objectPage',
             attributes: {
                 objectApiName: 'Account',
                 actionName: 'new'
             },
             state: {
                 defaultFieldValues: defaultValues
             }
         });
     }
}



For some reason, the LWC ignores if statements and open the window anyway. 

Can I use NavigationMixin and if statements in one LWC?
How can I fix this issue?

  
Thank you, in advance. 
Hi Team,

I am doing a trailhead module on  Aura Component to Override a Standard Action i am getting the below error . can someone help me why i am getting the below eroor .

A Component Error has occured! Error: Unable to find action 'getPickListValuesIntoList' on the controller of c:PickListValues Component: c:PropertyDialog . Caused by: Unable to find action 'getPickListValuesIntoList' on the controller of c:PickListValues.


a.G.get()@https://static.lightning.force.com/ap24/auraFW/javascript/dDIdorNC3N22LalQ5i3slQ/aura_prod.js:375:248
Object.value [as get]()@https://static.lightning.force.com/ap24/auraFW/javascript/dDIdorNC3N22LalQ5i3slQ/aura_prod.js:37:131667
doInit()@https://brave-badger-a5q453-dev-ed.lightning.force.com/lightning/r/Property__c/a065g000000pyldAAA/components/c/PickListValues.js:11:32

Property Dialog component :


<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="PickListController" >
  
    <aura:attribute name="picklistValues" type="Object" />
    <force:recordData aura:id="forceRecord"
                recordId="{!v.recordId}"
                targetFields="{!v.propertyRecord}"
                fields="Id,Name,Beds__c,Baths__c,Price__c,Status__c"
                mode="EDIT" />
    <aura:attribute name="propertyRecord" type="Property__c"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
   <c:PickListValues sObjectName="Property__c" fieldName="Status__c" picklistValues="{!v.picklistValues}" />
    <lightning:input aura:id="propName" name="propName" label="Proprty Name" required="true"/>
    <lightning:input aura:id="propBeds" name="propBeds" label="Beds" />
    <lightning:input aura:id="propBaths" name="propBaths" label="price" />
    <lightning:select aura:id="propStatus" name="propStatus" label="Status">
        <aura:iteration items="{!v.picklistValues}" var="item">
    <option value="{!item}">{!item}</option>
</aura:iteration>
</lightning:select>
<lightning:button variant="neutral" label="Cancel" />
<lightning:button variant="brand" label="Submit" />
    
</aura:component>


PickListvalues component:
<aura:component controller="PickListController" access="global" >
    <aura:attribute name="sObjectName" type="String" />
<aura:attribute name="fieldName" type="String" />
<aura:attribute name="picklistValues" type="Object" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
</aura:component>

PickList Controller:


global class PickListController{
@AuraEnabled 
public static List<String> getPicklistValues(String ObjectApi_name,String Field_name){ 
  List<String> lstPickvals=new List<String>();
  Schema.SObjectType targetType = Schema.getGlobalDescribe().get(ObjectApi_name);//From the Object Api name retrieving the SObject
    Sobject Object_name = targetType.newSObject();
  Schema.sObjectType sobject_type = Object_name.getSObjectType(); //grab the sobject that was passed
    Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
    Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
    List<Schema.PicklistEntry> pick_list_values = field_map.get(Field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
    for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
      lstPickvals.add(a.getValue());//add the value  to our final list
   }

  return lstPickvals;
}}

PickListValuesController:

({
    doInit : function(component) {
        var action = component.get("c.getPickListValuesIntoList");
        action.setParams({
            objectType: component.get("v.sObjectName"),
            selectedField: component.get("v.fieldName")
        });
        action.setCallback(this, function(response) {
            var list = response.getReturnValue();
            component.set("v.picklistValues", list);
        })
        $A.enqueueAction(action);
    }
})
I am new to Flows and having a hard time to implement the logic I am working on. I have a requirement to update the child records(object : Group Segment) picklist field to Status : 'Completed' when the parent record(object : Case) Status is 'Closed' using Flows.
Can someone please guide/help me on this.
Lightning Data Table issue :

i have a LWC component on Inquiry Obj (Parent) which is having look up relation with the child (Relavent Proprties).
My component will display all the child records of the parent obj with inline edit functionality.
Also i have "create relavent Proprty" standerd quick action button that craetes a New relevent Prop record.

Problem is that , when a new record is created from quick action button . my data table is not getting refreshed. data table shuld show all the values in the Db. why so 

Please help 

JavaScript : 
import { LightningElement, wire, api,track  } from 'lwc';
import getRelProp from '@salesforce/apex/selectRelPropController.getRelProp';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateRelProp from '@salesforce/apex/selectRelPropController.updateRelProp';
import { getRecordNotifyChange } from 'lightning/uiRecordApi';
const COLS = [
    { label: 'SL.No', 
    fieldName: "recordLink", 
    type: 'url',
    typeAttributes: { label: { fieldName: "Name" }, tooltip:"Relavent Property", target: "_blank" }
    
    },
    { label: 'Property Name',
     fieldName: 'recordLinkProp',
     type: 'url',
     typeAttributes: { label: { fieldName: "PropertyRel" }, tooltip:"Property", target: "_blank" }
    
    },
    { label: 'Price', fieldName: 'Price__c' ,  type: 'currency' },
    { label: 'Created Date', fieldName: 'CreatedDate' , type: 'date' },
    { label: 'Include this in PDF', fieldName: 'Include_This_in_PDF__c' , editable: true, type: 'boolean' }
    
    
];


export default class DatatableUpdate extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];
    @track wiredPropList = [];
    error;  
    @track relList = [];
    
      @wire(getRelProp, { accId: '$recordId' })
    getRelPropList(result) { 
        this.wiredPropList = result;
     if (result.data) { 
         
        console.log(result.data.length);
      var temprelList = [];  
      for (var i = 0; i < result.data.length; i++) {  
       let tempRecord = Object.assign({}, result.data[i]); //cloning object  
       tempRecord.recordLink = "/" + tempRecord.Id;       
       tempRecord.PropertyRel =  tempRecord.Property__r.Name;
       tempRecord.recordLinkProp = "/" + tempRecord.Id;       
       temprelList.push(tempRecord); 
       console.log(temprelList) ;
      }  
      this.relList = temprelList;  
      this.error = undefined;  
     } else if (result.error) {  
      this.error = error;  
      this.relList = undefined;  
     }  
    }
     
    async handleSave(event) {
        const updatedFields = event.detail.draftValues;
        console.log("chk1" +JSON.stringify(updatedFields));
        // Prepare the record IDs for getRecordNotifyChange()
        const notifyChangeIds = updatedFields.map(row => { return { "recordId": row.Id } });
        console.log("chk2" +JSON.stringify(notifyChangeIds));
    
       // Pass edited fields to the updateContacts Apex controller
        await updateRelProp({data: updatedFields})
        .then(result => {
            console.log(JSON.stringify("Apex update result: "+ result));
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Included for PDF Generation',
                    variant: 'success'
                })
            );
    
        // Refresh LDS cache and wires
        getRecordNotifyChange(notifyChangeIds);
    
        // Display fresh data in the datatable
        refreshApex(this.wiredPropList).then(() => {
            // Clear all draft values in the datatable
            console.log();
            this.draftValues = [];
          });
    
        
       })
        .catch(error => {
         this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Error updating or refreshing records',
                  message: error.body.message,
                  variant: 'error'
              })
          );
      });
       
    }
}

Component : 

<template>
    <lightning-card title="Relevant Properties" icon-name="custom:custom63">
    
       
     <div > 
        <template if:true={relList}>
            <lightning-datatable
                key-field="Id"
                data={relList}
                columns={columns}
                onsave={handleSave}
                show-row-number-column
                draft-values={draftValues}>
            </lightning-datatable>  
        </template>
        
        <template if:true={relList.error}>
            <!-- handle Apex error -->
        </template>
    </div>
        
    </lightning-card>
    </template>

User-added image

apex controller : 

public with sharing class selectRelPropController {
    
    @AuraEnabled(cacheable=true)
    public static List<Relevant_Property__c> getRelProp(String accId) {
        
        return [
            SELECT Id, Name, Property__r.Name , Property__c, Price__c , Include_This_in_PDF__c ,CreatedDate 
            FROM Relevant_Property__c
            WHERE Inquiry__c  = :accId
            WITH SECURITY_ENFORCED
        ];
    }
    
    @AuraEnabled
    public static string updateRelProp(Object data) {
        List<Relevant_Property__c> relPropRecForUpdate = (List<Relevant_Property__c>) JSON.deserialize(
            JSON.serialize(data),
            List<Relevant_Property__c>.class
        );
        try {
            system.debug('Records' +relPropRecForUpdate);
            update relPropRecForUpdate;
            return 'Success: pls click on Generate PDF Button to generate the Document';
        }
        catch (Exception e) {
            return 'The following exception has occurred: ' + e.getMessage();
        }}
}

pls helpppppppppp

Hello,

I am stuck on a validation rule -

If Sub Category is either 'Attestation Form Complete' or 'Attestation Form Incomeplete', all the other fields listed must not be blank.

The current formula will not let me create the record even if all the fields listed are completed.  Any suggestions would be helpful.
 

Thanks!
User-added image

I keep getting the following error while running my Apex Test Class. If I could please get assistance in resolving the problem I would appreciate it. I continue getting the following error:

System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Alias: data value too large: Sminull90 (max length=8): [Alias]

Below is my code:

Apex Class:

public  class NewUtilStaffProcess {
       @future
       public static void createUtlUser(Id recid) {
            
           Contact gcon = [SELECT Email, Lastname, Firstname, Middlename, AcctId
                            FROM   Contact
                            WHERE  Id = :recid];
           
           Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
           
           Id acctsTypeId = [SELECT Id
                            FROM   RecordType
                            WHERE  SObjectType = 'Account'
                            AND    Name = 'Account Source'].Id;
           
           String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;
           
           
           String formatUsrName;
           String setUsrLoc;
           
           Account retAcct = [SELECT Id, HAVNA_Country__r.HAVNA_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                               FROM   Account
                               WHERE  Id = :gcon.AcctId
                               AND    recordTypeId = :acctsTypeId
                               LIMIT 1];
           
           if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+retAcct.Hav_Locality__c;
        
           if (retAcct.Hav_Street__c == 'City/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C1';
         
           if (retAcct.Hav_Street__c == 'State/Surveyor')
              setUsrLoc = retAcct.HAVNA_Country__r.HAVNA_Letter_Code__c+'C2';
        
             
           if (gcon.middlename == null) {
               formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               Integer midSize = gcon.Middlename.length();
               if (midSize == 1) {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   formatUsrName = gcon.Lastname.deleteWhitespace().toLowercase().trim()+'.'+gcon.Firstname.deleteWhitespace().toLowercase().trim()+'.'+gcon.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }

           System.debug('Formatted Username: '+formatUsrName);
      
           User u       = new User(Alias    = gcon.Lastname.deleteWhitespace().trim().length() > 4 ? gcon.Lastname.deleteWhitespace().trim().substring(0,3)+setUsrLoc: gcon.lastname+setUsrLoc,
                         Email              = gcon.Email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = gcon.Lastname,
                         FirstName          = gcon.Firstname,
                         MiddleName         = gcon.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);
           
           UtilStaffPermSet.assgnPermissionSet(recId, u.Id);  
           System.resetPassword(u.Id, True);

      }
}

Apex Test Class:

@isTest
public class NewUtilStaffProcessTest {

   public static testMethod void InitialTest() {

        /* Get Record Id Type */   
        Id conTypeId;
        Id acctTypeId;
        String formatUsrName;
        String setUsrLoc;
        
        conTypeId = [SELECT Id  
                     FROM   RecordType
                     WHERE  SObjectType = 'Contact'
                     AND    Name = 'Utility Staffer'].Id;  

       
        Id acctsTypeId = [SELECT Id
                      FROM   RecordType
                      WHERE  SObjectType = 'Account'
                          AND    Name = 'Account Source'].Id;

        Profile p = [SELECT Id FROM Profile WHERE Name='HAVNA City Public Utility Group'];
        String groleId = [SELECT Id FROM UserRole WHERE Name = 'Utility Staff' LIMIT 1].Id;

        Integer midsize;
       
        //Create new State record; initialize required field(s), then insert
        HAV_State_and_Country__c state  = new HAV_State_and_Country__c();
        state.Name                = 'Oregon';
        state.HAV_Letter_Code__c = 'OR';
        state.HAV_Type__c        = 'State';
        Insert state;
        
        //Create new Account record; initialize required field(s), then insert
        Account acct = new Account(Name='Oregon Local 7');
        acct.Hav_Locality__c     = '90';
        acct.Hav_Street__c     = 'Local/Surveyor';
        acct.RecordTypeId     =  AcctTypeId;
        acct.HAV__Country__c    = state.id;
    insert acct;

        //Create new Contact record; initialize required field(s), then insert
        Contact con  = new Contact();   
        con.FirstName       = 'Ralph';  
        con.LastName        = 'Smith';
        con.Middlename      = 'Otis';
        con.RecordTypeId    =  conTypeId;
        con.email           = 'rsmith8@verizon.com';
        con.AcctId          = acct.id;
          
        //Insert Contact
        Insert con ;
       
          System.debug(con.id);
 
       Account retAcct = [SELECT Id, HAV_Country__r.HAV_Letter_Code__c, Hav_Locality__c, Hav_Street__c
                          FROM   Account
                          WHERE  Id           = :con.AcctId
                          AND    recordTypeId = :nomsTypeId
                          LIMIT 1];
                          
       if (retAcct.Hav_Street__c == 'Local/Surveyor')
              setUsrLoc = retAcct.HAV_Country__r.HAV_Letter_Code__c+retAcct.Hav_Locality__c;
 
       if (con.middlename == null) {
           System.debug('3: '+setUsrLoc);
               formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
           } else {
               System.debug('4: '+setUsrLoc);
               midSize = con.Middlename.length();
               if (midSize == 1) {
                   System.debug('5: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().toLowercase().trim()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               } else {
                   System.debug('6: '+setUsrLoc);
                   formatUsrName = con.Lastname.deleteWhitespace().toLowercase().trim()+'.'+con.Firstname.deleteWhitespace().toLowercase().trim()+'.'+con.middlename.deleteWhitespace().trim().substring(0,1).toLowercase()+'.cnastaff'+setUsrLoc+'@HAVNA.gmail';
               }    
           }
           
 User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
 system.runAs(thisUser){
         User u       = new User(Alias      = con.LastName.deleteWhitespace().trim().length() > 4 ? con.LastName.deleteWhitespace().trim().substring(0,4)+setUsrLoc: con.LastName+setUsrLoc,
                         Email              = con.email,
                         EmailEncodingKey   = 'UTF-8',
                         LastName           = con.LastName,
                         FirstName          = con.Firstname,
                         MiddleName         = con.Middlename,         
                         LanguageLocaleKey  = 'en_US',
                         LocaleSidKey       = 'en_US',
                         ProfileId          = p.Id,
                         UserRoleId         = groleid,          
                         TimeZoneSidKey     = 'America/New_York',
                         UserName           = formatUsrName);
          
           Insert(u);
           System.debug(u.id);  

                        
        Test.startTest();
       
        NewUtilStaffProcess.createUtlUser(con.id);
 
        Test.stopTest();
        system.debug('Done');
    }
     }
}

Thanks.
Trying to find out if i can rotate an image once the visualforce page is rendered as a PDF, when it is rendered as HTML the image shows correctly the way you take the image also the css below works with it on HTML but not PDF which is strange because the other style is working for the page when it is in PDF. 
<style type="text/css" media="print">
			@page {
				size: landscape
			}
.imageClass {
				-webkit-transform: rotate(90deg);
				-moz-transform: rotate(90deg);
				-o-transform: rotate(90deg);
				-ms-transform: rotate(90deg);
				transform: rotate(90deg);
				height: 200px;
				width: 200px;
			}

<img src="{!'/sfc/servlet.shepherd/version/download/' + Document_Id__c}" alt="before photo" class="imageClass"


-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
Hi,
I am having trouble with my Visualforce page and Apex Class. Everything seems to be fine apart from the error Unknown Property 'NFOSDisplayDivisions2Controller.Division_Space2__c'. I can't seem to figure out what is going on, could someone please help me out. Thank you.

Apex Class:
public with sharing class NFOSDisplayDivisions2Controller {
    
    public List<DivisionWrapper> listDivisionWrapper{get;set;}
    public List<Division_Space2__c> selectedDivisions{get;set;}

    public NFOSDisplayDivisions2Controller ()
    {
            listDivisionWrapper = new List<DivisionWrapper>();
            searchRecord();
    }
    
    public void searchRecord()
    {
        listDivisionWrapper.clear();
            for(Division_Space2__c a: [select Id, Name,Number_of_Competitors__c, Availability__c, RecordTypeID ,Active__c from Division_Space2__c limit 30]) 
            {
                listDivisionWrapper.add(new DivisionWrapper(a));
            }
    }

    public void processSelected() 
    {
        selectedDivisions = new List<Division_Space2__c>();
        selectedDivisions.clear();
        for(DivisionWrapper wrapDivisionObj : listDivisionWrapper) 
        {
            if(wrapDivisionObj.selected == true) 
            {
                selectedDivisions.add(wrapDivisionObj.acc);
                // Here you can add the counter or you check the selectedAccounts.size()
            }
        }
    }

    public void ActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c= true;
        }
        update selectedDivisions ;
        searchRecord();
    }

    public void DeActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c = false;
        }
        update selectedDivisions ;
        searchRecord();
    }
    


    // This is our wrapper/container class. 
    public class DivisionWrapper 
    {
        public Division_Space2__c acc {get;set;}
        public Boolean selected {get;set;}
        public DivisionWrapper(Division_Space2__c a) 
        {
            acc = a;
            selected = false;
        }
    }

}

Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!Division_Space2__c.acc.Name}" />
                    <apex:column value="{!Division_Space2__c.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Availability__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Active__c}" />
                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>
Can someone help me with a report formula?  How can I get a net of the PAYMENT - REFUND for each payment type?   



User-added image
trigger Opps_trigger1 on Opportunity (after insert) {
List<Contact>conlist=new List<Contact>();
List<Opportunity>oppslist=new List<Opportunity>([SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountID IN:Trigger.new]);
for(Opportunity o:Trigger.new)
{
c.AccountID=o.AccountID;
c.FirstName='aryan';
c.LastName='jha';
conlist.add(c);
}
insert conlist;
}
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
I'm getting the following error when attempting to created this custom formula field on the Opportunity object:

LMS Opportunity Owner Auto-Poulate = 
IF(
INCLUDES(Products_of_interest__c, "Learning Management System (LMS)"),
INCLUDES(Products_of_interest__c, "Schoology LMS"), 
Account.LMS_Account_Owner__c)

Conditions are to set the LMS Opportunity Owner to the LMS Account Owner if Opprotunity Products of Interest = Learning Management System (LMS) or Schoology LMS.

The formula above is giving me the following error:  Incorrect parameter type for function 'IF()'. Expected Boolean, received Lookup(User)

What am I doing wrong?

Hi, folks!

Could you please help me with the following scenario?

I have created a <lightning-datatable> tag in my <template> and I need to hidden the dropdown list with the options Wrap Text and Clip Text.

Screenshot:

As far as I know, there isn't any OOTB class that could help me with that.

When trying to apply a custom style, nothing happens:

.THIS slds-button slds-button_icon-baree{
    display: none ;
}

Has anyone any idea of how to solve that?

Thanks in advance.

 

Hello,

Did anyone else notice that the view state limit in Visualforce pages has been increased from 135 to 170 KB in the new release of Spring 2019