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


  • Chatter
    Feed
  • 381
    Best Answers
  • 3
    Likes Received
  • 14
    Likes Given
  • 16
    Questions
  • 1297
    Replies
Hello, I am displaying custom object records in Datatable via @wire, Since account is a lookup, it displays account id instead of account name. How can I display the name of the account in the colum. 

I have tried the following but it doesn't work. Please suggest.
 {
        label: 'My Accounts',
        fieldName:'My_Account__r.Name
        type: 'text',
        sortable: true
  }
 
Using Apex class to Insert contact and return inserted contact values, i have write component inside a component.
I am getting a Error as : 
" Action failed: c:QuickContact$controller$dosave [action.setparams is not a function] Failing descriptor: {c:QuickContact$controller$dosave} "
Kindly Suggest how to resolve this Issue.
Apex Class : 
public class ContactListController {
    @auraEnabled
    public static contact createContact(Contact con, Id AccountId){
        con.AccountId = AccountId;
        insert con;
        return con;
    }
}
Comp 1 :
<aura:component Controller="ContactListController" 
                implements="force:hasRecordId,force:hasSobjectName,flexipage:availableForAllPageTypes" >
    <aura:attribute name="ContactList" type="Contact[]"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <c:QuickContact accountId ="{!v.recordId}" />
    
    <div class="slds-p-around_xxx-small">
        <div class="slds-grid slds-wrap">
        <aura:iteration items="{!v.ContactList}" var="con">
        
              <div class="slds-col slds-size_1-of-3 slds-p-around_xxx-small"> 
        <lightning:card footer="{!con.Email}" title="{!con.LastName}" iconName="action:add_contact">
            <aura:set attribute="actions"> 
            <lightning:button name="{!con.Id}" variant="brand" label="View Details" onclick="{!c.DoRedirect}"/>
            </aura:set>
            <p class="slds-p-horizontal_xxx-small">
                {!con.FirstName}&nbsp; {!con.LastName} <br/>
                {!con.phone}
            </p>
        </lightning:card>
            </div>
            
       </aura:iteration>
       </div> 
    </div>   
     
</aura:component>
Comp 2 :
<aura:component Controller="ContactListController">
    <aura:attribute name="accountId" type="String" />
    <aura:attribute name="CreateContact" type="Contact" default="{ 
                                                                 SObjectName : 'Contact',
                                                                 FirstName : '',
                                                                 LastName : '',
                                                                 Email : '',
                                                                 Phone : ''
                                                                 }"/>
    <div class='slds-p-around_xx-small'>
        <lightning:input type="text" value="{!v.CreateContact.FirstName}" label="First Name" required="true"/>
        <lightning:input type="text" value="{!v.CreateContact.LastName}" label="Last Name" required="true"/>
        <lightning:input type="Email" value="{!v.CreateContact.Email}" label="Email ID" required="true"/>
        <lightning:input type="Phone" value="{!v.CreateContact.Phone}" label="Phone Number" required="true"/><br/>
        <lightning:button label="Create Contact" variant="brand" onclick="{!c.dosave}"/>
    </div>
</aura:component>
Controller code for comp 2 :
({
    dosave : function(component, event, helper) {
        var action = component.get('c.createContact');
        action.setparams({
            con : component.get('v.CreateContact'),
            AccountId : component.get('v.accountId')
        });
        action.setcallback(this,function(response){
            var state = response.getState();
            alert(state);
            if(state === 'SUCCESS' || state ==='DRAFT'){
                var responseValue = response.getReturnValue();
                
            }else if(state === 'INCOMPLETE'){
                
            }else if(state === 'ERROR'){
                
            }            
        }, 'ALL');
        $A.enqueueAction(action);
    }
})
 
I am using styleClass to disable the button. In UI it is showing as disabled. But when I click on the button, I am able to perform an action. Please suggest me a solution.

  <apex:commandButton id="canceldone" value="Cancel" onclick="OpenModel();return false;" styleClass="searchClass ordervalue btn btn-primary disabled {!IF( Industry == 'Enterprise','','sectionHeader')}" rerender="" ></apex:commandButton>
 
  • April 07, 2021
  • Like
  • 0
I have written the following trigger for the above question but it didn't work.
what is wrong in this trigger.
Member__c (Master Object)  
Maintenance_Amount__c(TextField)

Maintenance__c(Detail Object)
Amount_Paid__c(CheckBox)

trigger UpdateMaintenance on Maintenance__c (After insert, After Update) {
Map<id, Member__c> MapList=new Map<id, Member__c>();
    For(Maintenance__c M: Trigger.new)
    {
        if(M.Member__r.id != Null)
        {
            if(M.Amount_Paid__c = True)
            {  
            MapList.put(M.Member__r.id,new Member__c(id=M.Member__r.id, Maintenance_Amount__c='Amount Paid'));
            }
        }
        else
        {
            MapList.put(M.Member__r.id,new Member__c(id=M.Member__r.id, Maintenance_Amount__c='Amount Unpaid'));
        }
        if(MapList.size()>0)
        {
            try{
            Update MapList.values();
            }
            catch(DmlException e)
            {
                System.debug(e.getMessage());
            }
        }
    }
}
Aura Component:-

<aura:component controller="createAccount" implements="force:hasRecordId,flexipage:availableForRecordHome" >
    <aura:attribute name="createAccount" type="Account[]" default="{
                                                                   
                                                          'sObjectType' : 'Account',
                                                          'FirstName'   : ' ' ,
                                                          'LastName'    : ' ',
                                                          'BillingAddress' : ' ',
                                                          'Rating' : ' '        
                    
                                                                        }" />
  <aura:attribute name="starRating" type="List" default="[
    {'label': 'Hot', 'value': 'Hot'},
    {'label': 'Warm', 'value': 'Warm'},
    {'label': 'Cold', 'value': 'Cold'},
    ]"/> 
    
    <lightning:input aura:id="input1" label="FirstName" value="{!v.createAccount.FirstName}" required="True"/>
    <lightning:input aura:id="input2" label="LastName" value="{!v.createAccount.LastName}" required="True"/>
    <lightning:input aura:id="input3" label="Address" value="{!v.createAccount.BillingAddress}" required="True"/>
     <lightning:combobox name="sRating" label="Rating" value="None" placeholder="Select Progress" options="{!v.starRating }" 
                                                            onchange="{!c.handleChange }"/> 

     <lightning:button title="Neutral action" 
                                  label="Save"   
                                  onclick="{!c.handleClick}"/>
    
    </aura:component>

JS Controller:-
({
    handleChange : function(component, event, helper) {
        
        let selectedOptionValue = event.getParam("value"); 
        component.set("v.createAccount.Rating",selectedOptionValue);
        let values= component.get("v.createAccount.Rating");
        alert(values); 
        console.log(values);
    },
    
    handleClick : function(component, event, helper) {
        var target = event.getSource();
        var id = target.get("v.label");     
        alert(id);
        
         var action = component.get("c.createAcc");
        action.setParams({ 
         Acc : component.get("v.createAccount") });
 
        // Create a callback that is executed after 
        // the server-side action returns
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                alert('Record added');// Alert the user with the value returned 
                // from the server
                alert("From server: " + response.getReturnValue());
                 console.log('Sucessfully added content to Object');
                // You would typically fire a event here to trigger 
                // client-side notification that the server-side 
                // action is complete
            }
            else if (state === "INCOMPLETE") {
              alert("Incomplete");  // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
 
        // optionally set storable, abortable, background flag here
 
        // A client-side action could cause multiple events, 
        // which could trigger other events and 
        // other server-side action calls.
        // $A.enqueueAction adds the server-side action to the queue.
        $A.enqueueAction(action);
    

    
    }     
})

Apex Code:-

public class createAccount {
    
    @AuraEnabled
    public static Account createAcc(Account Acc){
                  
            insert Acc;
       
        return Acc;
    }
}
Will someone help me with writing a test class for my email class?
 
public with sharing class PDF_EmailController {
    
    @auraEnabled

    public static void SendAttachment(String recordId){
           
        for(Purchase_Order_Request__c por : [SELECT Id, Email_Address__c FROM Purchase_Order__c
        WHERE Id =: recordId]){
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();

            PageReference pref = page.POPDF;
            pref.getParameters().put('Id',por.Id);
            pref.setRedirect(true);
            Blob b = pref.getContent();
            attach.setFileName('POR.pdf');
            attach.setBody(b);
            semail.setSubject('Purchase Order Request Details');
            semail.setToAddresses(new String[] { por.Email_Address__c });
            semail.setPlainTextBody('Please find the attached POR details');
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});

        }

        for(Purchase_Order_Request__c por : [SELECT Id, Email_Address__c,Version__c FROM Purchase_Order__c
                                             WHERE Id =: recordId]){
            PageReference PDf =  Page.PORequestPDF;
            PDf.getParameters().put('Id',por.Id);
            PDf.setRedirect(true);
            Attachment attach = new Attachment();
            Blob b ;
            b = PDf.getContent();
            attach.Body = b;
            attach.Name = 'Purchase Order Confirmation ' + System.today();
            attach.IsPrivate = false;
            attach.ParentId = por.Id;
            insert attach;

        }
    }
 }



Visualforce Page

<apex:page controller="PDF_EmailController" standardStylesheets="false" showHeader="false">    
    <center>
        <P style="font-size:22px;"><u>Send Purchase Order Request</u></P>
        <input type="text" value="" id="txtEmailAddress"/><br/><br/>
        <input type="button" onclick="SendEmailAttachment();" value="Send"/>
    </center>
    <script>
    function SendEmailAttachment(){
        var PORId = '{!$CurrentPage.parameters.Id}';
        var emailAddress=document.getElementById('txtEmailAddress').value;
        if(emailAddress!=null && emailAddress!=''){
            TestHandler.SendAttachment(emailAddress,porId,function(result,event){
                if(event.status){
                    if(result=='SUCCESS'){
                        alert('Email sent successfully.');
                    }
                    else{
                        alert(result);
                    }
                }
            })
        }
        else{
            alert('Please provide email address!');
        }
    }
    </script>
 </apex:page>

Thank you,
P

Ive created an apex class that pulls in certain leads and then feeds all the IDs into a round robin assigner apex class. Im not a developer but Ive been able to hack together enough to get this running as intended, my only problem now is the text class I have doesnt have enough code coverage to get into production. I assume part of this problem is the List that is created does not have its own method and therefore is hard to create a test for? But agian Im not a developer, Ive included both the class as well as the test code. If someone could point me in the right direction that would be greatly appreciated!

CODE:

public with sharing class RRAOnline {

    list<roundRobinAssigner.RoundRobinAssignment> rras = new list<roundRobinAssigner.RoundRobinAssignment>();

    List<User> users = [SELECT Id FROM User WHERE Lead_Reassignment__c = true AND IsActive = true AND ProfileId = '00e4P000000KDMk'];
 
    List<Lead> leads = [SELECT Id 
                        FROM Lead
                        WHERE OwnerID IN : users
                        AND Next_Business_Date__c <= TODAY 
                        AND (
                        Program_of_Interest__c = 'Animation' OR
                        Program_of_Interest__c = 'Fashion Design' OR
                        Program_of_Interest__c = 'Fine Arts' OR
                        Program_of_Interest__c = 'Game Art' OR
                        Program_of_Interest__c = 'Graphic Design' OR
                        Program_of_Interest__c = 'Illustration' OR
                        Program_of_Interest__c = 'Illustrative Design' OR
                        Program_of_Interest__c = 'Interior Design' OR
                        Program_of_Interest__c = 'Non-Degree Seeking' OR
                        Program_of_Interest__c = 'Photography' OR
                        Program_of_Interest__c = 'Summer Camp' OR
                        Program_of_Interest__c = 'Undeclared' OR
                        Program_of_Interest__c = 'Certificate Program - Graduate'
                        )
                        AND (
                        Status__c = 'New' OR 
                        Status__c = 'Attempting Contact 1' OR
                        Status__c = 'Attempting Contact 2' OR
                        Status__c = 'Attempting Contact 3' OR
                        Status__c = 'Attempting Contact 4' OR
                        Status__c = 'Attempting Contact 5')
                        LIMIT 50
                        ];
                  
     public void createrrassigns(){
        for (lead a:leads){
            roundRobinAssigner.RoundRobinAssignment rra = new roundRobinAssigner.RoundRobinAssignment();
            rra.groupName = 'Online Round Robin';
            rra.recordId = a.id;
            rra.fieldName = 'OwnerId';
            rras.add(rra);
            }
        if (rras.size() > 0){
            roundRobinAssigner.assign(rras);
            } 
         else {
            system.debug('list is empty');
            }
      }


}



TEST CODE:


@isTest
private class RRAOnline_Test{
  @testSetup
  static void setupTestData(){
    test.startTest();
    
    // Setup 4 Test Leads
    List<Lead> leads = new List<Lead>();

    while (leads.size() < 5) {
      Blob b = Crypto.GenerateAESKey(128);
      String h = EncodingUtil.ConvertTohex(b);
      String uid = h.SubString(0,8);
      Lead l = new Lead(FirstName = 'FirstName'+ uid, LastName = 'LastName'+ uid, Status = 'New Inquiry', Status__c = 'New', Program_of_Interest__c = 'Graphic Design', 
            Next_Business_Date__c = System.today());      
      leads.add(l);
    }
    insert(leads);
    
    
     
    // Setup 4 Test Users
    Profile p = [SELECT Id FROM Profile WHERE Name='Admissions User']; 
    List<User> user_Obj = new List<User>();

    while (user_Obj.size() < 5) {
      Blob b = Crypto.GenerateAESKey(128);
      String h = EncodingUtil.ConvertTohex(b);
      String uid = h.SubString(0,8);
      User u = new User(Alias = uid, Email= uid + '@myorg.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', ProfileId = p.Id, 
          TimeZoneSidKey='America/New_York', UserName= uid + '@myorg.com', Lead_Reassignment__c = true, IsActive = true);      
      user_Obj.add(u);
    }
    insert(user_Obj);

    test.stopTest();
  }
  
    static testMethod void test_createrrassigns_UseCase1(){
    RRAOnline obj01 = new RRAOnline();
    obj01.createrrassigns();
  }
  
//    static testMethod void test_createrrassigns_UseCase2(){
//    RRAOnline users = new RRAOnline();
//    users.getUsers();
//  }
  

}
i wrote an apex class and created emailservices but it is only working when i send the email to the very long salesforce generated email address and lead is generating but i need to generate lead when i give small address like abc@gmail.com    is this possible?
Sorry experts, I am still having some issues with basic formulas. If you could please assist with these two, I would truly appreciate it.

1. When 'Ready_Set_Go_Pack_Printed__c' (date field) OR when 'Stage' = 'RSG Sent' 'Booking_Confirmed__c' (checkbox) becomes mandatory.
 
2. When Stage = 'Fundraising Phase',  'Have_Confirmed_Materials_Are_Out__c' (date) becomes mandatory.

I'm working through a range of different formulas, so I'm hoping with these two examples, I'll be able to work it from there.

Thank you so much in advance!
Hi All - Below is the controller class for my custom component, can someone help me with test class for this controller.

public inherited sharing class CFRNotesControllerPOC {
    public class CFRNotesControllerException extends Exception {}

    @AuraEnabled(cacheable=true)
    public static NotesFieldWrapper getFieldInfo(String recordId, String fieldName){
        return new NotesFieldWrapper(recordId, fieldName);
    }

    @AuraEnabled
    public static void saveNotesInfo(String recordId, String fieldName, String fieldValue){
        SObject sobjectRecord = ((Id)recordId).getSObjectType().newSObject(recordId);
        sobjectRecord.put('Id', recordId);
        sobjectRecord.put(fieldName, fieldValue);
        Database.update(sobjectRecord);
    }

    public class NotesFieldWrapper {
        @auraEnabled
        public String fieldValue;
        @AuraEnabled
        public String fieldDescribe;
        //to check FLS
        @AuraEnabled
        public Boolean fieldAccess;
            
        public NotesFieldWrapper(String recordId, String fieldName) {
            Schema.DescribeSObjectResult objDescribe = ((Id)recordId).getSObjectType().getDescribe();
            String objName = objDescribe.getName();

            Map<String, Schema.SObjectField> fields = objDescribe.fields.getMap();
            if(String.isNotEmpty(fieldName)){
                Schema.SObjectField fieldToken = fields.get(fieldName);
                this.fieldDescribe = JSON.serialize(fieldToken.getDescribe());
                this.fieldAccess = fieldToken.getDescribe().isAccessible();

                String query = 'SELECT Id, ' + fieldName + ' FROM ' + objName + ' WHERE Id = \'' + recordId + '\'';
                SObject sobj = (SObject) Database.query(query);
                if(sobj != null){
                    this.fieldValue = (String) sobj.get(fieldName);
                }
            }
        }
    }
Hello everybody !!
How can I deserealize this JSON? 
 
{
    "infopay": [
        {
            "chavebanco": 4020.0,
            "codigocliente": "2000746",
            "tipotitulo": null,
            "valortitulo": 0.0,
            "datapagamento": "2021-02-20T00:00:00",
            "status": 4
        },
        {
            "chavebanco": 8886.0,
            "codigocliente": "2000466",
            "tipotitulo": null,
            "valortitulo": 0.0,
            "datapagamento": "2021-04-20T00:00:00",
            "status": 6
        },
        {
            "chavebanco": 8842.0,
            "codigocliente": "2000466",
            "tipotitulo": null,
            "valortitulo": 0.0,
            "datapagamento": "2021-04-20T00:00:00",
            "status": 8
        },
        {
            "chavebanco": 8887.0,
            "codigocliente": "2000466",
            "tipotitulo": null,
            "valortitulo": 0.0,
            "datapagamento": "2021-04-20T00:00:00",
            "status": 6
        }]
}

I have the public class TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData and I tried to do this:
 
TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData resp = (TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData) JSON.deserialize(response.getBody(), TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData.class);

List<TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData> respList = new List<TemplateDataIntegrationFieldsGATEC.InformacoesPagamentoINData>{resp};
          
IntegrationInboundInformacoesPagamento.upsertPaymentInfo(respList);

But it gives:
 
(InformacoesPagamentoINData:[chavebanco=null, codigoFazenda=null, codigocliente=null, datapagamento=null, status=null, tipotitulo=null, valortitulo=null])

Thanks in advance :)
I created a trigger that outputs error if checkbox is true and no document is attached. 

It's working great. However, I've read here that I should bulkify it so that I don't hit SOQL query limits. 

I need help bulkifying the below code. Thank you :)
trigger ReportRequestTrigger on Report_Request__c (before update, after update) {
    for(Report_Request__c rr:Trigger.New) {
        if(rr.Will_Receive_Provider_Facility_Claims__c== TRUE) {
            LIST<ContentDocumentLink> attachments = [SELECT ContentDocumentId, LinkedEntityId  FROM ContentDocumentLink where LinkedEntityId = : rr.Id];
            if(attachments.size()<=0){
                rr.adderror('You cant select "Will Receive Provider Facility Claims" without attaching a Zip Census');
            }
        }
    }
}

 
  • February 18, 2021
  • Like
  • 0

Hello, I created the following custom setting:
User-added imageI have a list of translated words for German and Spanish and they are strictly dependent on what the English word will be entered in the record. On my object I have 3 fields, for English, German and Spanish.
How to make a logic in a trigger that whenever the field(which is in English) has some values than automatically the German field and Spanish field should populate with the corresponding value.
Example, let's say I change a record and I put 'Car' in the field which is used for English language.

 

User-added imageLike so... After saving it I want to populate the Task Type(DE) with 'Wagen' and Task Type(ES) with 'Automombile' because that's how I defined in the custom setting.
I tried to write the logic by myself but I failed. 

 

public static void onBeforeUpdate(Map<Id, SVMX_PS_PM_Task_Template__c> newMap)
    {
        Map<string,Translations__c > translation = Translations__c.getAll();
        
        for(SVMX_PS_PM_Task_Template__c newTemplate : newMap.values()){
            String storeValue = newTemplate.SVMX_PS_Task_Type__c;
            
         
              try{
                String germanTranslation = translation.get(storeValue).German__c;
                String englishTranslation = translation.get(storeValue).English__c;
                System.debug('english' + englishTranslation);
                String spanishTranslation = translation.get(storeValue).Spanish__c;
                newTemplate.Task_Type_DE__c = germanTranslation;
                newTemplate.Task_Type_ES__c = spanishTranslation;
              }
               catch(exception e) {
               newTemplate.Task_Type_DE__c = '';
               newTemplate.Task_Type_ES__c = '';
              }
        }
       
    }

Thanks
I am new to writing validation rules and am stuck.  I need to write a rule so that a person can not change a project status to active unless a picklist field called foundation type is filled out. This would only apply to projects that fall within certain departments.

User-added image
 
Can someone help me writing a test class for the following trigger:

trigger updateAttach on Attachment (after insert) {
Map<Id, Id> mapCSId = new map<Id, Id>();
    List<Recrutamento__c> lstCSUpdate = new List<Recrutamento__c>();
    String objectName = '';
    for(Attachment atc: trigger.new){
        String myIdPrefix = string.valueOf(atc.ParentId).substring(0,3);
        Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
        for(Schema.SObjectType stype : gd.values()){
            Schema.DescribeSObjectResult r = stype.getDescribe();
            String prefix = r.getKeyPrefix();
            if(prefix!=null && prefix.equals(myIdPrefix)){
                objectName = r.getName();
            }
        }
        if(objectName == 'Recrutamento__c'){
            mapCSId.put(atc.ParentId, atc.id);
        }
    }
    if(!mapCSId.isEmpty()){
        List<Recrutamento__c> updateAtt = [select id from Recrutamento__c where id in: mapCSId.keyset()];
        for(Recrutamento__c cs: updateAtt){
            cs.AttachmentId__c = mapCSId.get(cs.id);
        }
        if(!updateAtt.isEmpty()){
            update updateAtt;
        }
    }
}



Thanks
  • February 10, 2021
  • Like
  • 0
Hi

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

Thanks in Advance.
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.
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.
Hi, 
I'm very new to APEX so please bear with me.  I have 2 different map strings objects and I'm trying to concatenate them using the map method .putAll, however it's replacing instead of concatenating.   

if(aresp.getBody() != null ||  bresp.getBody() != null ){
                Map<String, Object> aretVal;
                Map<String, Object> bretVal;
                if(aresp.getBody() != null)
                {
                    System.Debug('****** raw a Response: ' + aresp.getBody());
                    aretVal = (Map<String, Object>) JSON.deserializeUntyped(aresp.getBody());
                }
                System.Debug('****** aretVal: ' + aretVal.size());
                System.Debug('****** aretVal: ' + aretVal);
                if(bresp.getBody() != null)
                {
                    System.Debug('****** raw b Response: ' + bresp.getBody());
                    bretVal = (Map<String, Object>) JSON.deserializeUntyped(bresp.getBody());
                    System.Debug('****** bretVal: ' + bretVal.size());
                    System.Debug('****** bretVal: ' + bretVal);
                }
                
                if(!bretVal.isEmpty())
                    aretVal.putAll(bretVal);


putAll(sobjectArray)
Adds the list of sObject records to a map declared as Map<ID, sObject> or Map<String, sObject>.
Hello, I am displaying custom object records in Datatable via @wire, Since account is a lookup, it displays account id instead of account name. How can I display the name of the account in the colum. 

I have tried the following but it doesn't work. Please suggest.
 {
        label: 'My Accounts',
        fieldName:'My_Account__r.Name
        type: 'text',
        sortable: true
  }
 
Hello, I am working on a VF page, on which users can upload files. After clicking save, I am getting shown a screen with this message: 

Maximum view state size limit (170KB) exceeded. Actual view state size for this page was 1,006.033KB

Any idea how I can stop this error message? The strange thing is that the file seems to be getting uploaded anyways, so I'm not sure what to do with that message.
Hi
Help please, I made the following trigger on Opportunity, where to being in a specific stage, create a record of a random user of a specific profile in the Opportunity Team
This is my trigger
trigger SLInsertOppTeam on Opportunity (before insert, before update) {
	for(Opportunity opp : trigger.New){	
		if(opp.StageName == 'A' && opp.is_new__c == false)
		{
            List<OpportunityTeamMember> member = [SELECT TeamMemberRole FROM OpportunityTeamMember 
                                                  Where OpportunityId = : opp.Id
                                                 AND TeamMemberRole = : 'Analist'];
            if(member.size() == 0 )
            {
				OpportunityTeamMember OTM = new OpportunityTeamMember();
            	OTM.OpportunityId = opp.Id;
				OTM.TeamMemberRole = 'Analist';
				OTM.OpportunityAccessLevel = 'Edit';       
            	List<User> uList = [SELECT Id FROM User Where IsActive = true and ProfileId = '00e4x000000NCX0AAO'];
            	if(uList.size() > 0){
                	Integer Ran = (integer)(Math.random() * (uList.size()));
            		OTM.UserId = uList[Ran].id;
            	}
            	insert OTM; 
             }   
		}   
    }  
}
When doing the trigger test, there is no error and it completes it well, but in the coverage it stays at 0%, could you help me to know what is wrong in the test or know how I can improve it so that it gives me a percentage of coverage feasible for you to take it as good
This is my Test
@isTest
private class SLTestInsertOMT {
    @isTest(SeeAllData=true)
    static void TestInsert() 
    {
        Test.startTest();
        Opportunity opp = [select Id, StageName, is_new__c from Opportunity where id_sf__c = '21022600147' LIMIT 1];
        if(opp.StageName == 'A' && opp.is_new__c == false)
        {
        	OpportunityTeamMember otm = new OpportunityTeamMember (OpportunityId= opp.Id, 
                                                             TeamMemberRole = 'Analist',
                                                             OpportunityAccessLevel = 'Edit',
                                                             UserId ='0054x000004Hu2xAAC');
        	insert otm;
        }
        System.assert(true); 
        Test.stopTest();
    }
}


 
Using Apex class to Insert contact and return inserted contact values, i have write component inside a component.
I am getting a Error as : 
" Action failed: c:QuickContact$controller$dosave [action.setparams is not a function] Failing descriptor: {c:QuickContact$controller$dosave} "
Kindly Suggest how to resolve this Issue.
Apex Class : 
public class ContactListController {
    @auraEnabled
    public static contact createContact(Contact con, Id AccountId){
        con.AccountId = AccountId;
        insert con;
        return con;
    }
}
Comp 1 :
<aura:component Controller="ContactListController" 
                implements="force:hasRecordId,force:hasSobjectName,flexipage:availableForAllPageTypes" >
    <aura:attribute name="ContactList" type="Contact[]"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <c:QuickContact accountId ="{!v.recordId}" />
    
    <div class="slds-p-around_xxx-small">
        <div class="slds-grid slds-wrap">
        <aura:iteration items="{!v.ContactList}" var="con">
        
              <div class="slds-col slds-size_1-of-3 slds-p-around_xxx-small"> 
        <lightning:card footer="{!con.Email}" title="{!con.LastName}" iconName="action:add_contact">
            <aura:set attribute="actions"> 
            <lightning:button name="{!con.Id}" variant="brand" label="View Details" onclick="{!c.DoRedirect}"/>
            </aura:set>
            <p class="slds-p-horizontal_xxx-small">
                {!con.FirstName}&nbsp; {!con.LastName} <br/>
                {!con.phone}
            </p>
        </lightning:card>
            </div>
            
       </aura:iteration>
       </div> 
    </div>   
     
</aura:component>
Comp 2 :
<aura:component Controller="ContactListController">
    <aura:attribute name="accountId" type="String" />
    <aura:attribute name="CreateContact" type="Contact" default="{ 
                                                                 SObjectName : 'Contact',
                                                                 FirstName : '',
                                                                 LastName : '',
                                                                 Email : '',
                                                                 Phone : ''
                                                                 }"/>
    <div class='slds-p-around_xx-small'>
        <lightning:input type="text" value="{!v.CreateContact.FirstName}" label="First Name" required="true"/>
        <lightning:input type="text" value="{!v.CreateContact.LastName}" label="Last Name" required="true"/>
        <lightning:input type="Email" value="{!v.CreateContact.Email}" label="Email ID" required="true"/>
        <lightning:input type="Phone" value="{!v.CreateContact.Phone}" label="Phone Number" required="true"/><br/>
        <lightning:button label="Create Contact" variant="brand" onclick="{!c.dosave}"/>
    </div>
</aura:component>
Controller code for comp 2 :
({
    dosave : function(component, event, helper) {
        var action = component.get('c.createContact');
        action.setparams({
            con : component.get('v.CreateContact'),
            AccountId : component.get('v.accountId')
        });
        action.setcallback(this,function(response){
            var state = response.getState();
            alert(state);
            if(state === 'SUCCESS' || state ==='DRAFT'){
                var responseValue = response.getReturnValue();
                
            }else if(state === 'INCOMPLETE'){
                
            }else if(state === 'ERROR'){
                
            }            
        }, 'ALL');
        $A.enqueueAction(action);
    }
})
 
I am using styleClass to disable the button. In UI it is showing as disabled. But when I click on the button, I am able to perform an action. Please suggest me a solution.

  <apex:commandButton id="canceldone" value="Cancel" onclick="OpenModel();return false;" styleClass="searchClass ordervalue btn btn-primary disabled {!IF( Industry == 'Enterprise','','sectionHeader')}" rerender="" ></apex:commandButton>
 
  • April 07, 2021
  • Like
  • 0
getRequest(){
        Request({recordId : this.recordId})
        .then(data => {
            alert('1');
            this.newRecordId = data;
        })
        .catch(error=>{
            alert(error)
        })
            this.navigateNext();
}
 
navigateNext() {
        alert('2');
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.newRecordId,
                actionName: 'view'
            }
        });
    }


Hi All,

I want to call navigateNext() from getRequest() in LWC, In some cases, the page is navigating some times it is not.

I put 2 alert statements to understand flow For the first time when i call the getRequest() for the first time alert('2') which is in navigatinNext() and then alert('1')  is getting printed, from the second time output is as alert('1') then alert('2');

Can someone help me where I went wrong?
 

Hello-

We have a junior developer who wrote a very large lightning component that has over 1,000 references to:

<aura:if isTrue="{!v.profileName =='System Administrator'}"

The issue we have is now we need additional profiles, all containing "Admin" in the name to this. Is there a way to copy/replace all so I don't have to go through each individual reference and add || or && conditions to it? Is something like this doable:

<aura:if isTrue="{!CONTAINS(v.profileName, 'Admin'}"

or

<aura:if isTrue="{!v.profileName == '%Admin'}"

In some cases we may need an || condition in some cases we may need an && condition. So i cannot just to a global replace to add the additional profile names here.

Thanks
I am getting a success response from OMDB API and having a issue in my VF Page. Can any one find out where I have gone wrong. Any help would be appreciated. Thank you in anticipated!!   
My error ----->  Unknown property 'moviesWrap.Search.Title'
movieCallout.apxc
---------------------------------------------------------------------------------------

public class movieCallout {
    public String result {get;set;}
    public List<Object> movies {get;set;}
    public String element {set;get;}
    public list<string> title {set;get;}
    public list<moviesWrap.Search> finalmovies {get;set;}
    public movieCallout(){ 
        finalmovies = new list<moviesWrap.Search>();
    }
    
    
    public Object  makeGetCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('http://www.omdbapi.com/?s='+element+'&apikey=ebe6fdf2');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            this.result = response.getBody();
            moviesWrap mv = moviesWrap.parse(response.getBody());
            finalmovies = mv.Search;
            System.debug(mv.Search);

            
        }
        return null;
    }
}




moviesWrap.apxc
-----------------------------------------------------------------------------------

public class moviesWrap {

	public List<Search> Search;
	public String totalResults;
	public String Response;

	public class Search {
		public String Title;
		public String Year;
		public String imdbID;
		public String Type;
		public String Poster;
	}

	
	public static moviesWrap parse(String json) {
		return (moviesWrap) System.JSON.deserialize(json, moviesWrap.class);
        
	}
}




eazzymovie.vfp
.....................................................................

<apex:page controller="movieCallout"  lightningStyleSheets="true">
    <head>
        <apex:slds />
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"/>
    </head>
    <apex:form >
        <center><h1 style="font-size:20px">
            Eazzymovie
            </h1></center>
<!-- Search bar and Button --> 

        <div class="container mt-3">
            <apex:inputText id="theTextInput" value="{!element}" html-placeholder="Search Movie With..." />
            <apex:commandButton value="Search" action="{!makeGetCallout}" id="theButton"/>
        </div>

<!-- Results -->
        <div class="container">	
            <div class="row">
                <apex:repeat var="abc" value="{!finalmovies}">
                    <div class="col-3 p-3">
                        <div class="card" style="width: 18rem;"> 
                            <div class="card-body"> 
                                <h4 class="card-title mt-1">Movie Name : <b>{!abc.Title}</b></h4>
                               <center> <a href="#" class="btn btn-primary">Book Now</a> </center>
                            </div>
                        </div> 
                    </div>
                </apex:repeat>
            </div>
        </div>
    </apex:form>
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <!--
    <apex:form >
        <center><h1 style="font-size:20px">
            Eazzymovie
            </h1></center>
        <div class="container mt-3">
            <apex:inputText id="theTextInput" value="{!searchKey}" html-placeholder="Search Movie With..." />
            <apex:commandButton value="Search" action="{!search}" id="theButton"/>
        </div>
        <div class="container">	
            <div class="row">
                <apex:repeat var="a" value="{!movie}">
                    <div class="col-3 p-3">
                        <div class="card" style="width: 18rem;">
                            <div class="card-body">
                                <img id="theImage" src="https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg" width="220" height="55" alt="Description of image here"/> 
                                <h4 class="card-title mt-1">Movie Name : <b>{!a.Name}</b></h4>
                                <p class="card-text">Genre : {!a.Genre__c}</p>
                               <center> <a href="#" class="btn btn-primary">Book Now</a> </center>
                            </div>
                        </div>
                    </div>
                </apex:repeat>
            </div>
        </div>
    </apex:form>
    -->
</apex:page>
I have written the following trigger for the above question but it didn't work.
what is wrong in this trigger.
Member__c (Master Object)  
Maintenance_Amount__c(TextField)

Maintenance__c(Detail Object)
Amount_Paid__c(CheckBox)

trigger UpdateMaintenance on Maintenance__c (After insert, After Update) {
Map<id, Member__c> MapList=new Map<id, Member__c>();
    For(Maintenance__c M: Trigger.new)
    {
        if(M.Member__r.id != Null)
        {
            if(M.Amount_Paid__c = True)
            {  
            MapList.put(M.Member__r.id,new Member__c(id=M.Member__r.id, Maintenance_Amount__c='Amount Paid'));
            }
        }
        else
        {
            MapList.put(M.Member__r.id,new Member__c(id=M.Member__r.id, Maintenance_Amount__c='Amount Unpaid'));
        }
        if(MapList.size()>0)
        {
            try{
            Update MapList.values();
            }
            catch(DmlException e)
            {
                System.debug(e.getMessage());
            }
        }
    }
}
Aura Component:-

<aura:component controller="createAccount" implements="force:hasRecordId,flexipage:availableForRecordHome" >
    <aura:attribute name="createAccount" type="Account[]" default="{
                                                                   
                                                          'sObjectType' : 'Account',
                                                          'FirstName'   : ' ' ,
                                                          'LastName'    : ' ',
                                                          'BillingAddress' : ' ',
                                                          'Rating' : ' '        
                    
                                                                        }" />
  <aura:attribute name="starRating" type="List" default="[
    {'label': 'Hot', 'value': 'Hot'},
    {'label': 'Warm', 'value': 'Warm'},
    {'label': 'Cold', 'value': 'Cold'},
    ]"/> 
    
    <lightning:input aura:id="input1" label="FirstName" value="{!v.createAccount.FirstName}" required="True"/>
    <lightning:input aura:id="input2" label="LastName" value="{!v.createAccount.LastName}" required="True"/>
    <lightning:input aura:id="input3" label="Address" value="{!v.createAccount.BillingAddress}" required="True"/>
     <lightning:combobox name="sRating" label="Rating" value="None" placeholder="Select Progress" options="{!v.starRating }" 
                                                            onchange="{!c.handleChange }"/> 

     <lightning:button title="Neutral action" 
                                  label="Save"   
                                  onclick="{!c.handleClick}"/>
    
    </aura:component>

JS Controller:-
({
    handleChange : function(component, event, helper) {
        
        let selectedOptionValue = event.getParam("value"); 
        component.set("v.createAccount.Rating",selectedOptionValue);
        let values= component.get("v.createAccount.Rating");
        alert(values); 
        console.log(values);
    },
    
    handleClick : function(component, event, helper) {
        var target = event.getSource();
        var id = target.get("v.label");     
        alert(id);
        
         var action = component.get("c.createAcc");
        action.setParams({ 
         Acc : component.get("v.createAccount") });
 
        // Create a callback that is executed after 
        // the server-side action returns
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                alert('Record added');// Alert the user with the value returned 
                // from the server
                alert("From server: " + response.getReturnValue());
                 console.log('Sucessfully added content to Object');
                // You would typically fire a event here to trigger 
                // client-side notification that the server-side 
                // action is complete
            }
            else if (state === "INCOMPLETE") {
              alert("Incomplete");  // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
 
        // optionally set storable, abortable, background flag here
 
        // A client-side action could cause multiple events, 
        // which could trigger other events and 
        // other server-side action calls.
        // $A.enqueueAction adds the server-side action to the queue.
        $A.enqueueAction(action);
    

    
    }     
})

Apex Code:-

public class createAccount {
    
    @AuraEnabled
    public static Account createAcc(Account Acc){
                  
            insert Acc;
       
        return Acc;
    }
}
public class SOQL3_1 {
    public List<Account> accounts{set;get;}
    public SOQL3_1(){
        List<String> listField=new List<String>{'Name','Phone','Rating'};
          String queryString='SELECT Id';
        for(String s:listField){
            queryString=queryString+','+s;
        }
        queryString=queryString+'from Account';
        accounts=Database.query(queryString);
    }
}


<apex:page controller="SOQL3_1">
    <apex:pageBlock title="Accounts Details">
        <apex:pageBlockTable value="{!accounts}" var="a">
         <apex:column value="{!a.name}"/>
         <apex:column value="{!a.phone}"/>
         <apex:column value="{!a.rating}"/>
         <apex:column value="{!a.industry}"/> 
       </apex:pageBlockTable>
    </apex:pageBlock>

</apex:page>
I am trying to pass a prior value as a param to a flow that I need to call from apex because I need to cover the inability to deal with deleted records without apex triggers.  Can someone lend guidance as to how to access a record's prior value? thanks

I need something like this (I know it's not that simple)

  For (Animal_Location_History__c Animal : Trigger.Old) {
      // Call the Flow
        Map<String, Object> params2 = new Map<String, Object>();
        params2.put('varInputAnimalLocation', Animal_Location_History__c.Animal_Location__c);
        params2.put('varPriorLocation', PRIORVALUE(Animal_Location_History__c.Animal_Location__c));
        params2.put('varInputAnimalLocation', Animal_Location_History__c.Location__r.Id);
           Flow.Interview.Update_Location_Inventory Update_Location_Inventory = new Flow.Interview.Update_Location_Inventory(params2);
        Update_Location_Inventory.start();
        // System.debug('Animal Location '  + Animal_Location_History__c.Animal_Location__c    );
        
        }
Will someone help me with writing a test class for my email class?
 
public with sharing class PDF_EmailController {
    
    @auraEnabled

    public static void SendAttachment(String recordId){
           
        for(Purchase_Order_Request__c por : [SELECT Id, Email_Address__c FROM Purchase_Order__c
        WHERE Id =: recordId]){
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();

            PageReference pref = page.POPDF;
            pref.getParameters().put('Id',por.Id);
            pref.setRedirect(true);
            Blob b = pref.getContent();
            attach.setFileName('POR.pdf');
            attach.setBody(b);
            semail.setSubject('Purchase Order Request Details');
            semail.setToAddresses(new String[] { por.Email_Address__c });
            semail.setPlainTextBody('Please find the attached POR details');
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});

        }

        for(Purchase_Order_Request__c por : [SELECT Id, Email_Address__c,Version__c FROM Purchase_Order__c
                                             WHERE Id =: recordId]){
            PageReference PDf =  Page.PORequestPDF;
            PDf.getParameters().put('Id',por.Id);
            PDf.setRedirect(true);
            Attachment attach = new Attachment();
            Blob b ;
            b = PDf.getContent();
            attach.Body = b;
            attach.Name = 'Purchase Order Confirmation ' + System.today();
            attach.IsPrivate = false;
            attach.ParentId = por.Id;
            insert attach;

        }
    }
 }



Visualforce Page

<apex:page controller="PDF_EmailController" standardStylesheets="false" showHeader="false">    
    <center>
        <P style="font-size:22px;"><u>Send Purchase Order Request</u></P>
        <input type="text" value="" id="txtEmailAddress"/><br/><br/>
        <input type="button" onclick="SendEmailAttachment();" value="Send"/>
    </center>
    <script>
    function SendEmailAttachment(){
        var PORId = '{!$CurrentPage.parameters.Id}';
        var emailAddress=document.getElementById('txtEmailAddress').value;
        if(emailAddress!=null && emailAddress!=''){
            TestHandler.SendAttachment(emailAddress,porId,function(result,event){
                if(event.status){
                    if(result=='SUCCESS'){
                        alert('Email sent successfully.');
                    }
                    else{
                        alert(result);
                    }
                }
            })
        }
        else{
            alert('Please provide email address!');
        }
    }
    </script>
 </apex:page>

Thank you,
P

Ive created an apex class that pulls in certain leads and then feeds all the IDs into a round robin assigner apex class. Im not a developer but Ive been able to hack together enough to get this running as intended, my only problem now is the text class I have doesnt have enough code coverage to get into production. I assume part of this problem is the List that is created does not have its own method and therefore is hard to create a test for? But agian Im not a developer, Ive included both the class as well as the test code. If someone could point me in the right direction that would be greatly appreciated!

CODE:

public with sharing class RRAOnline {

    list<roundRobinAssigner.RoundRobinAssignment> rras = new list<roundRobinAssigner.RoundRobinAssignment>();

    List<User> users = [SELECT Id FROM User WHERE Lead_Reassignment__c = true AND IsActive = true AND ProfileId = '00e4P000000KDMk'];
 
    List<Lead> leads = [SELECT Id 
                        FROM Lead
                        WHERE OwnerID IN : users
                        AND Next_Business_Date__c <= TODAY 
                        AND (
                        Program_of_Interest__c = 'Animation' OR
                        Program_of_Interest__c = 'Fashion Design' OR
                        Program_of_Interest__c = 'Fine Arts' OR
                        Program_of_Interest__c = 'Game Art' OR
                        Program_of_Interest__c = 'Graphic Design' OR
                        Program_of_Interest__c = 'Illustration' OR
                        Program_of_Interest__c = 'Illustrative Design' OR
                        Program_of_Interest__c = 'Interior Design' OR
                        Program_of_Interest__c = 'Non-Degree Seeking' OR
                        Program_of_Interest__c = 'Photography' OR
                        Program_of_Interest__c = 'Summer Camp' OR
                        Program_of_Interest__c = 'Undeclared' OR
                        Program_of_Interest__c = 'Certificate Program - Graduate'
                        )
                        AND (
                        Status__c = 'New' OR 
                        Status__c = 'Attempting Contact 1' OR
                        Status__c = 'Attempting Contact 2' OR
                        Status__c = 'Attempting Contact 3' OR
                        Status__c = 'Attempting Contact 4' OR
                        Status__c = 'Attempting Contact 5')
                        LIMIT 50
                        ];
                  
     public void createrrassigns(){
        for (lead a:leads){
            roundRobinAssigner.RoundRobinAssignment rra = new roundRobinAssigner.RoundRobinAssignment();
            rra.groupName = 'Online Round Robin';
            rra.recordId = a.id;
            rra.fieldName = 'OwnerId';
            rras.add(rra);
            }
        if (rras.size() > 0){
            roundRobinAssigner.assign(rras);
            } 
         else {
            system.debug('list is empty');
            }
      }


}



TEST CODE:


@isTest
private class RRAOnline_Test{
  @testSetup
  static void setupTestData(){
    test.startTest();
    
    // Setup 4 Test Leads
    List<Lead> leads = new List<Lead>();

    while (leads.size() < 5) {
      Blob b = Crypto.GenerateAESKey(128);
      String h = EncodingUtil.ConvertTohex(b);
      String uid = h.SubString(0,8);
      Lead l = new Lead(FirstName = 'FirstName'+ uid, LastName = 'LastName'+ uid, Status = 'New Inquiry', Status__c = 'New', Program_of_Interest__c = 'Graphic Design', 
            Next_Business_Date__c = System.today());      
      leads.add(l);
    }
    insert(leads);
    
    
     
    // Setup 4 Test Users
    Profile p = [SELECT Id FROM Profile WHERE Name='Admissions User']; 
    List<User> user_Obj = new List<User>();

    while (user_Obj.size() < 5) {
      Blob b = Crypto.GenerateAESKey(128);
      String h = EncodingUtil.ConvertTohex(b);
      String uid = h.SubString(0,8);
      User u = new User(Alias = uid, Email= uid + '@myorg.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', ProfileId = p.Id, 
          TimeZoneSidKey='America/New_York', UserName= uid + '@myorg.com', Lead_Reassignment__c = true, IsActive = true);      
      user_Obj.add(u);
    }
    insert(user_Obj);

    test.stopTest();
  }
  
    static testMethod void test_createrrassigns_UseCase1(){
    RRAOnline obj01 = new RRAOnline();
    obj01.createrrassigns();
  }
  
//    static testMethod void test_createrrassigns_UseCase2(){
//    RRAOnline users = new RRAOnline();
//    users.getUsers();
//  }
  

}
Hellow,
i am facing an error with a lightning component since this weekend. I can't figure out why this message occures.
User-added image
Appilcation:
<aura:application extends="force:slds" >
    <c:additioncomponent/>
</aura:application>
​​​​​​​
component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
<lightning:input label="enter val1" aura:id="value1" type="number"/>
    <lightning:input label="enter val2" aura:id="value2" type="number"/>
    <lightning:input label="result" aura:id="res" type="number"/>
    <lightning:button label="add" onclick="{!c.show}"/>  
</aura:component>

Controller:
({
    show :function(component, event, helper) {
        var val1=component.find("value1").get("v.value");
        alert("val1::"+val1);
        var val2=component.find("value2").get("v.value");
        alert("val1::"+val1);
        var result=parseInt(val1)+parseInt(val2);
        alert("result::"+result);
        var val1=component.find("res").set("v.res",result);
    }
})

I am able to pring the result value. not sure what is the issue with below the line.
  var val1=component.find("res").set("v.res",result);

Could some one please help me on this isuse.
 
I am new to Apex development and have the following code. I'd appreciate any help or suggestions.

Requirements: 
I will be uploading Opportunities periodically through Dataloader, all of record type "Outbound Call Opportunity." The file will contain the following info for each opp:
  • RecordTypeID
  • TIN__c (Tax ID Number)
  • Product__c
  • Outbound_Call_Score__c
I need my code to do the following:
  • Query Contacts where the Opp's TIN__c matches Contact's Tax_ID_Number__c and set Contact as Opp Owner
  • Confirm before insert that there are no other Outbound Call Opportunities with the same Contact and Product, in other words, there can only be one Outbound Call Opportunity per Contact per Product.
  • Give error if a Outbound Opportunity exists already with that contact and product, else update pertinent fields
I think I have that sorted out, but I have one remaining requirement:
  • Rollup Outbound_Call_Score__c to related Contact. Each Opp with have a numeric weight signifying how "important" it is. I want that number to aggregate and rollup to the Contact on a field also named Outbound_Call_Score__c. I am not sure how to accompish that, any help would be appreciated!
Trigger:
trigger OpportunityTrigger on Opportunity (before insert) {

  if (Trigger.isBefore) {
    if (Trigger.isInsert) {
      OpportunityHandler.insertOutboundCallLists(Trigger.new);
    } 
  }
}

Handler class:
 
public class OpportunityHandler {
    
    public OpportunityHandler() { }
    
    public static void insertOutboundCallLists(List<Opportunity> newOpps){
        Set<String> oppTINs = new Set<String>();
        String outboundCallRecTypeID = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Outbound Call Opportunity').getRecordTypeId();
        
        for(Opportunity opp : newOpps){
            oppTINs.add(opp.TIN__c);
        }        
        //system.debug(oppTINs);
        
        List<Contact> contacts = [SELECT Id, OwnerId, Tax_ID_Number__c, Outbound_Call_Score__c 
                                  FROM Contact WHERE Tax_ID_Number__c IN :oppTINs]; 
        List<Opportunity> existingOutboundOpps = new List<Opportunity>([SELECT Id, Product__c, Contact__r.Id, Contact__r.Tax_ID_Number__c 
                                                                        FROM Opportunity WHERE RecordTypeId = :outboundCallRecTypeId 
                                                                        AND Contact__r.Id IN :contacts]);
        system.debug(contacts);
        system.debug(existingOutboundOpps);
        
        if(contacts.size() > 0){
            for(Opportunity opp : newOpps){
                for(Integer i = 0; i < existingOutboundOpps.size(); i++){
                    if(opp.TIN__c == existingOutboundOpps[i].Contact__r.Tax_ID_Number__c && opp.Product__c == existingOutboundOpps[i].Product__c){
                        opp.addError('Outbound Opportunity Already Exists.');
                    } else {
                        for(Integer j = 0; j < contacts.size(); j++){
                            if(opp.TIN__c == contacts[j].Tax_ID_Number__c && opp.RecordTypeId == outboundCallRecTypeID){
                                opp.Name = 'test';
                                opp.CloseDate = system.today() + 14;
                                opp.StageName = 'Prospecting';
                                opp.OwnerId = contacts[j].OwnerId;
                                opp.Contact__c = contacts[j].Id;
                                //contacts[j].Outbound_Call_Score__c = contacts[j].Outbound_Call_Score__c + opp.Outbound_Call_Score__c;
                            }   
                        }
                    }
                }  
            } 
        } 
    }     
}



 
I am new to writing validation rules and am stuck.  I need to write a rule so that a person can not change a project status to active unless a picklist field called foundation type is filled out. This would only apply to projects that fall within certain departments.

User-added image
 

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