• Salesforce####
  • NEWBIE
  • 90 Points
  • Member since 2016

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 12
    Questions
  • 26
    Replies

<apex:page tabStyle="Account" controller="ShowdDetailCtrl">
<apex:sectionHeader title="Inline Edit Support" subtitle="Account"/>
<apex:form >
    
<apex:pageBlock title="Account Detail Page">
   <apex:pageBlockButtons LOcation="top">
      <apex:commandButton value="Save" action="{!saveAccount}"/>
   </apex:pageBlockButtons>
   
<apex:pageBlockTable value="{!lstAccountObjs}" var="acc">
<apex:variable value="{!0}" var="count"/>



<apex:column headerValue="Select">
    <apex:facet name="header">
            <apex:outputPanel >
                Select <input type="checkbox" id="selectAll" name="selectAll" onclick="selectAllOrNone();" />
            </apex:outputPanel>
    </apex:facet>
      
     <apex:inputCheckbox styleClass="selectAccount" value="{!acc.isSelected}"/>

</apex:column>

<apex:column headerValue="Account Name">
    <apex:inputtext value="{!acc.name}"/>
</apex:column>

<apex:column headerValue="Phone">
       <apex:inputtext value="{!acc.phone}"/>
       <apex:commandLink value="Remove" action="{!removeAccount}">
        <apex:param name="c" assignTo="{!count}" value="{!count}"/>
        </apeX:commandlink><br/>
        <apex:variable value="{!count+1}" var="count"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>

<script>
    function selectAllOrNone(){
            var isSelected = document.getElementById('selectAll').checked;
            var elements = document.getElementsByClassName('selectAccount');
            for (var i = 0; i < elements.length; i++) {
                document.getElementsByClassName('selectAccount')[i].checked = false;
        }
        if(isSelected){
                var elements = document.getElementsByClassName('selectAccount');
                for (var i = 0; i < elements.length; i++) {
                    document.getElementsByClassName('selectAccount')[i].checked = true
            }
        }
    }
</script>
</apex:page>


class------------------------------------------------------------------------------------

public class ShowdDetailCtrl {
    public list<AccountObj> lstAccountObjs {get;set;}
    public Integer count { get; set; }
    
    //CONSTRUCTOR
    public ShowdDetailCtrl(){
        init();
    }
    
    public void init(){
        lstAccountObjs = new list<AccountObj>();
        for(Account acc : [select id,name,phone from account limit 5]){
            lstAccountObjs.add(new AccountObj(acc));
        }
    }
    
    public PageReference removeAccount() {
        lstAccountObjs.remove(count-1);
        return null;
    }
    
    public PageReference saveAccount() {
        List<Account> lstAccounts = new List<Account>();
        if(lstAccountObjs.size() > 0){
            for(AccountObj accObj : lstAccountObjs){
                
                if(accObj.isSelected){
                    System.debug('###CHeckBox'+accObj.name);
                    Account acc = new Account();
                    acc.Name = accObj.name;
                    acc.phone = accObj.phone;
                    acc.Id = accObj.accId;
                    lstAccounts.add(acc);
                }else{
                    System.debug('###CHeckBoxElse '+accObj.name);
                }
            }
            System.debug(lstAccounts.size());
            for(Account a : lstAccounts){
                System.debug('###listItere'+a.name);
                
            }
            if(lstAccounts.size() > 0){
                update lstAccounts;
            }
            init();
        }
        return null;
    }
    
    public class AccountObj{
        public Boolean isSelected{get; set;}
        public String name{get; set;}
        public String phone{get; set;}
        public String accId{get; set;}
        
        public AccountObj(Account acc){
            this.isSelected = false;
            this.name = acc.Name;
            this.phone = acc.Phone;
            this.accId = acc.Id;
        }
    }
}
hello Team , 
I need to create a contact table which displays name , id , phone number and edit hyperlink or button , basically need to create a wrapper .

On click of edit   on that row, i need open the contact record of that purticular row in table in a new window ,i can update phone number name and Account name . and save the record . can you please tell me how to do it in lightning component.

User-added image
Hello folks , 
Requirement:  Can any one tell me how to write a trigger on contact to check the duplicates for Name , phone , email . if any duplicate arises we need to put error message . condition is (Name OR phone OR Email).

trigger DuplicateTwoFieldsContact on Contact (before insert,before update) 
{
 if(trigger.isBefore)
 {
  map<String,Contact> mapcontact = new map<String,Contact>();
   map<String,Contact> phonemap = new map<String,Contact>();
  
  for(contact con: trigger.new) 
   {
   if(                                                 
   ((con.Email != null) && (Trigger.isInsert || con.email != trigger.oldmap.get(con.id).email )) ||
    ((con.Phone != null) && (Trigger.isInsert || con.Phone != trigger.oldmap.get(con.id).Phone ))
    )
     {                                
     if( !mapcontact.containskey(con.Email) || !phonemap.containskey(con.Phone))
      {
      mapcontact.put(con.Email ,con);
      phonemap.put(con.Phone ,con);
      
      } 
     }
   }
 
 for(contact c:[select id ,Email ,Phone from contact where Email =: mapcontact.keyset() OR Phone =: phonemap.keyset() ])
 {
 contact newcontact = mapcontact.get(c.Email);
  newcontact.Email.adderror('Duplicate Email has been detected ');
 
 contact Phonecontact = phonemap.get(c.Phone);
  Phonecontact.Phone.adderror('Duplicate Phone has been detected ');
 
 }
 }
}
how to  eliminate duplicates  name and phone number and email  using soql query in a single trigger while creating accounts ???
alternate approach is also fine other than filering in soql 
hi folks !!! 

i want to know when to use SVG icons and when to use lightning icons . 

can you correct me , in winter 17 we can use direclty lightning icons instead of SVG ... can you please clarify it 
hello Team ,
can yhou please tell me when do we use Aura :handler in lightning , what is the purpose , in what cirucmstanses we use it ??

This page has an error. You might just need to refresh it. Action failed: c$TestComp$controller$showMsg [Cannot read property 'getELement' of undefined] Failing descriptor: {c$TestComp$controller$showMsg}
currently below code is working , i want to re write the same in maps !!! 

//I'd like to update a boolean field  " CheckMate__c " on contact to True when a  specific opportunity stage is closed lost. 

trigger ClosedLost on Opportunity (after insert ,after update)
{
list<contact> cont = new list<contact>();

for(opportunity opp : trigger.new)
 {
     if(opp.stagename == 'Closed Lost')
     {
     cont = [select id , name , CheckMate__c from contact where Accountid =:opp.accountid ];
     
     for(contact  c :cont)
      {
     c.CheckMate__c = true ;
       }
      update cont; 
     }
  
 }

}
i want to display list of accounts in my org using lightning , may i konw how to write the code 
i am trying with this sample code as i am new to rest api .
http://www.oyecode.com/2014/08/start-building-your-own-rest-api-in.html

i am getting the below error , i am not getting understood whats the issue is 

class : 
/***************************************************************************
Name : OyeCode Api Service, custom designed in Apex 
Created By : Harshit Pandey (hpandey@salesforce.com)
Created Date : August 18, 2014
Description : An Apex REST service to that supports the following 
operations, related to insertion and retrieval of Contacts :
1. GET /ContactId - Return the Response as instance of custom class called ResponseClass
- Reponse class return customized information which is match Record, CustomMessage, Error (if any)
2. POST/Contact - Creates a new Contact and insert records in the database.
***************************************************************************/

@RestResource(urlMapping='/OyeCode/*')
global class OyeCodeRestAPI {
    
    //**************************************************
    //Private methods 
    //**************************************************
    
    //Check if Object is NULL or Blank
    global static boolean isNotNullOrEmpty(string str)
    {
        return str!=null || !String.isBlank(str); 
    }
    
    // Create a Contact 
    public static Contact createContact(String firstName, String lastName, String email,String Phone)
    {
        //check if the fields provided on not empty
        if(isNotNullOrEmpty(firstName) && isNotNullOrEmpty(lastName) && isNotNullOrEmpty(email) && isNotNullOrEmpty(Phone))
        {
            Contact newContact = new Contact();
            newContact.FirstName = firstName;
            newContact.LastName = lastName;
            newContact.Email = email;
            newContact.Phone=phone;
            return newContact;         
        }
        else 
        {
            System.Debug('Required field values are not provided here');
            return null;
        }
    }
    
    
    //====================================================================================
    // *** REST POST *** : Require field should not be empty, method to post a new Contact
    //====================================================================================
    @HttpPost
    global static ResponseHandler post(String firstname, String  lastname, String email, String Phone)
    {
        Contact  newContact =  createContact(firstName, lastName, email, Phone);
        ResponseHandler response = new ResponseHandler();
        try
        {
            insert newContact;
            List<sObject> thesObjectList = new List<sObject>();
            thesObjectList.add((sObject)newContact);
            response.Data = thesObjectList;
            response.Status = 'Success';
            response.ErrorCode = null;
            response.Message = null;
        } 
        catch(DmlException e) 
        {
            //Add custom error code when you could not insert a record
            response.ErrorCode = 'Oyecode - 0001';
            response.Status = 'error';
            response.Message = e.getMessage();
        }
        return response;   
    }
    
    
    //==============================================================================================
    // *** REST GET *** :  Requires the id of Contact and reutrn results as Response Type
    //===============================================================================================
    @HttpGet 
    global static ResponseHandler GET()
    {
        ResponseHandler response = new ResponseHandler();
        Contact  returnContact = getContact();
        
        if(returnContact!=null)
        {
            response.Status = 'Success';
            response.ErrorCode = '';
            List<sObject> thesObjectList = new List<sObject>();
            thesObjectList.add((sObject)returnContact);
            response.Data = thesObjectList;
            response.Message = 'Success : Found Contact';
        }
        
        else
        {
            response.ErrorCode = 'OyeCode-0002';
            response.Status = 'error';
            response.Message = 'Fail : Ahh, Contact Not Found';
            
        }
        
        return response;
    }
    
    //Adding custom Exception sub-class 
    public class NoRecordMatchException extends Exception {}
    
    public static Contact getContact()
    {
        //Read the Request from the URL
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String ContactId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); 
        Contact result;
        try{
            result = [SELECT Id, lastname, firstName, phone, email FROM Contact WHERE Id = :ContactId];
        }
        Catch(System.QueryException e)
        {
            //Add custom exception dynamically to the ErrorMap
            throw new NoRecordMatchException('Unable to find the record maching Id : '+ContactId);
        }
        return result;
    }
    
}
i am giving the values in opportunity and when i click on the button "create aopportunity " it should create an opportunity record in the database and it should appear in the pageblock table which i am displaying . but some how it is not happening  can you please modify my code . 

vf page : 
<apex:page controller="JSexmpleOptyCont" id="page">
   <apex:form id="form">
     <script>
     alert("test1 success");
     function validateOpp()
     {
     alert("function inside  success");
     var optyName = document.getElementById('{!$Component.page.form.pgblck.pbsec.item1.optyname}').value;
     alert("optyName   success");
      var optyStage =   document.getElementById('{!$Component.page.form.pgblck.pbsec.item2.optyStage}').value;
    alert("optyStage success");
    var optyAccount = document.getElementById('{!$Component.page.form.pgblck.pbsec.item3.optyAccount}').value;
      alert("optyAccount success");
     var optyAmount= document.getElementById('{!$Component.page.form.pgblck.pbsec.item4.optyAmount}').value;
     alert("optyAmount success");
     
       alert ("optyAmount value "+optyAmount);
       
       
         
        if(optyAmount == null || optyAmount == '')
            {
                alert("amount cannot be empty");
            }
            else 
            {
            alert("no error");
            Createopp();
            }
     
        }
    
      </script>  
     

<apex:pageMessages id="msgs"/>
    
        <apex:sectionHeader title="Opportunity" subtitle="Opportunity List View"/>
   <apex:pageBlock mode="edit" id="pgblck">
                <apex:pageBlockButtons location="top">
                   <apex:commandButton value="Create Opportunity" onclick="validateOpp();" />
                   
                   <apex:actionFunction name="Createopp" id="Createopp" action="{!SaveRec}" /> 
                   <!--- <apex:actionStatus startText=" (incrementing...)"  id="counterStatus"/>-->
                </apex:pageBlockButtons>
        
        <apex:pageBlockSection title="Create New Opportunites" id="pbSec">
                
                <apex:pageBlockSectionItem id="item1">
                <apex:outputLabel value="Opportunity Name" for="Opportunity_Name"/>
                  <apex:inputField value="{!opty.name}" id="optyname"/>
                 </apex:pageBlockSectionItem>
             
              
                <apex:pageBlockSectionItem id="item2">
                <apex:outputLabel value="Stage" for="Stage"/>
                <apex:inputField value="{!opty.stagename}" id="optyStage"/>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem id="item3">
                <apex:outputLabel value="Account" for="Account"/>
                <apex:inputField value="{!opty.AccountId}" id="optyAccount"/>
                </apex:pageBlockSectionItem>
                
                 <apex:pageBlockSectionItem id="item4">
                <apex:outputLabel value="Amount" for="Account"/>
                <apex:inputField value="{!opty.Amount}" id="optyAmount"/>
                </apex:pageBlockSectionItem>
         </apex:pageBlockSection>    
           
      
            <apex:pageBlockSection title="List of existing opportunities" columns="1">
                 <apex:pageBlockTable value="{!optylist}" var="opp" id="pbtable" >
                 <apex:column value="{!opp.Name}" />
                 <apex:column value="{!opp.AccountId }" />
                 <apex:column value="{!opp.stagename}" />
                 <apex:column value="{!opp.Amount}" />
                 
                 </apex:pageBlockTable>
           </apex:pageBlockSection>
           
   </apex:pageBlock>
</apex:form>
</apex:page>

========
controller : 
public with sharing class JSexmpleOptyCont 
{
public list<opportunity> optylist {set;get;}
public opportunity opty{set;get;}

public JSexmpleOptyCont()
{

optylist  = new list<opportunity>([select id ,AccountId ,Name,Amount , StageName from opportunity order by Name Asc]);
opty = new opportunity();
}

public PageReference SaveRec()
{  
    
    system.debug(opty+'here in controller');
    system.debug('========test2======'+opty);
    database.insert(opty,false );
    optylist  = new list<opportunity>([select id,Name,Type,Amount,StageName,AccountId  from opportunity  ]);
    Apexpages.addmessage(new apexpages.message(ApexPages.Severity.confirm,'Opportunity created succesfully'));
   // opty = null;
    
   return null; 



}
getting this error in test class : can you tell me how to reolve the error and how to get 100 % code coverage .
Constructor not defined: [wrapperAccountCont.wrapAccount].<Constructor>(Account, Boolean) at line 20 column 37

My Test class: 
@isTest

public class wrapperAccountCont_test
{
public testmethod static void ttestmeth()
{
wrapperAccountCont wac = new wrapperAccountCont();
wac.processSelected();
wac.reset();

//wrapper funct
boolean checkbox =true;
Account ac = new account();
ac.name='test1';
ac.BillingState = 'actttt';
ac.phone='12345';
insert ac; 

  wrapperAccountCont.wrapAccount wc = new wrapperAccountCont.wrapAccount(ac,true); // getting error 
//taking test variables
Account acc = new Account();
acc.name = 'test1';
acc.phone = '123456';
insert acc;


}
}
=======================================
my class: 
public with sharing class wrapperAccountCont 
{
public List<wrapAccount> wrapAccountList {get; set;}
    public List<Account> selectedAccounts{get;set;}
     public integer accountreset {get;set;}
    
    public wrapperAccountCont()
    {
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) 
            {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapAccountList.add(new wrapAccount(a));
            }
        }
    }
    public void reset()
    {
    accountreset = 0;
    
    }
    public void processSelected() {
    selectedAccounts = new List<Account>();
 
        for(wrapAccount wrapAccountObj : wrapAccountList) 
        {
            if(wrapAccountObj.selected == true) 
            {
                selectedAccounts.add(wrapAccountObj.acc);
            }
        }
    }
 
    // This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        public wrapAccount(Account a) 
        {
            acc = a;
            selected = false;
        }
    }
}

vf page: 
<apex:page controller="wrapperAccountCont">
  
  <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 >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!processSelected}" rerender="table2"/>
                   <apex:commandButton value="Reset All Accounts" action="{!reset}" rerender="table2"/>
            </apex:pageBlockButtons>
 
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
 
                <apex:pageBlockTable value="{!wrapAccountList}" var="accWrap" id="table" title="All Accounts">
                
                    <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="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.BillingState}" />
                    <apex:column value="{!accWrap.acc.Phone}" />
                </apex:pageBlockTable>
 
                <apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
                    <apex:column value="{!c.Name}" headerValue="Account Name"/>
                    <apex:column value="{!c.BillingState}" headerValue="Billing State"/>
                    <apex:column value="{!c.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
 
            </apex:pageblockSection>
        </apex:pageBlock>
 
  </apex:form>
</apex:page>
===============================
hi all , 

in a vf page , i have a custom button , if i click that button i need to get a pop up which displays all account fields name, phone with a check box  in a column . can you please give me an example how to do this ??
hello Team ,
can yhou please tell me when do we use Aura :handler in lightning , what is the purpose , in what cirucmstanses we use it ??
Hello folks , 
Requirement:  Can any one tell me how to write a trigger on contact to check the duplicates for Name , phone , email . if any duplicate arises we need to put error message . condition is (Name OR phone OR Email).

trigger DuplicateTwoFieldsContact on Contact (before insert,before update) 
{
 if(trigger.isBefore)
 {
  map<String,Contact> mapcontact = new map<String,Contact>();
   map<String,Contact> phonemap = new map<String,Contact>();
  
  for(contact con: trigger.new) 
   {
   if(                                                 
   ((con.Email != null) && (Trigger.isInsert || con.email != trigger.oldmap.get(con.id).email )) ||
    ((con.Phone != null) && (Trigger.isInsert || con.Phone != trigger.oldmap.get(con.id).Phone ))
    )
     {                                
     if( !mapcontact.containskey(con.Email) || !phonemap.containskey(con.Phone))
      {
      mapcontact.put(con.Email ,con);
      phonemap.put(con.Phone ,con);
      
      } 
     }
   }
 
 for(contact c:[select id ,Email ,Phone from contact where Email =: mapcontact.keyset() OR Phone =: phonemap.keyset() ])
 {
 contact newcontact = mapcontact.get(c.Email);
  newcontact.Email.adderror('Duplicate Email has been detected ');
 
 contact Phonecontact = phonemap.get(c.Phone);
  Phonecontact.Phone.adderror('Duplicate Phone has been detected ');
 
 }
 }
}
Hi All,

I created one Lightning component and use that component on vfpage.There is one button in lightning component. I just want to refresh the Page on button click.I have used force:refreshView and Window.reload(). But nothing seems to work.

Any help is much appreciated
Thanks,

 
Hi All,

I'm a begginer in Apex Triggers. The following is a trigger I used but its not working. My Trigger should not allow ANY USERS to delete the record if the record creater (User) becomes INACTIVE. This trigger never allowed me to delete a record eventhough the User is active. Help n Thanks.

trigger  preventdelete  on  Loan__c (before delete){
    for(Loan__c  loan:Trigger.old){
          if(loan.CreatedBy.IsActive == FALSE ){
         loan.addError('You cant delete this record since it is created by an inactive user');
       }
     }
   }
Below is my trigger and I am not sure how to write test class for trigger with validations and adding errors. Please help.
My trigger:
trigger PreventTaskDelete on Task (before delete) 
{
    String ProfileId = UserInfo.getProfileId();  
   List<Profile> profiles=[select id from Profile where name='System Administrator'];

   if (profiles.size() == 1)
   {
      for (Task a : Trigger.old)      
       {            
          if (profileId != profiles[0].id)
          {  a.addError('Activities should not be deleted, it can only be Closed');
          }
       }
   }
  • October 28, 2016
  • Like
  • 0
Hi ,

I need some help. i have written an apex class and trigger code which counts the number of attachments on my task object. I need to write  a test class so that i can deploy this in my production. i am unable to do so. Kindly help me in writing the test class.

Below is the codes written -

Trigger 1 –
 
trigger CountAttachment on Attachment (after insert, after update, after delete, after undelete) {
    // Contains the IDs of all the parent tasks
    Set<Id> parentTaskIdSet = new Set<id>();
 
    if (trigger.new != null)
    {
        for (Attachment a: trigger.new)
        {
            parentTaskIdSet.add(a.parentId);
        }
    }
   
    if (trigger.old != null)
    {
        for (Attachment a: trigger.old)
        {
            parentTaskIdSet.add(a.parentId);
        }
    }   
    
    // List of tasks that needs to be updated
    List<Task> parentTaskList = [SELECT id, (SELECT id FROM Attachments) FROM Task WHERE id in: parentTaskIdSet];
   
    for (Task t: parentTaskList)
    {
        t.NumberOfAttachments__c = t.Attachments.size();
    }
   
    update parentTaskList;
}
 
 
***************************************************************************************************************************************************

Trigger 2 –
 
trigger UpdateAttachmentCount on Task (after insert, after update) {
   
    if (checkRecursive.runOnce())
    {
        List<Task> taskList = new List<Task>();
        Set<ID> taskIDSet = new Set<ID>();
       
        if (trigger.old != null)
        {
            for (Task t: trigger.old)
            {
                taskIDSet.add(t.ID);
            }
        }
       
        if (trigger.new != null)
        {
            for (Task t: trigger.new)
            {
                taskIDSet.add(t.ID);
            }
        }
       
        // Query for the attachment children of the taskspublic Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
        if (run){
            run = false;
            return true;
        }
        else
        {
            return run;
        }
    }
}        taskList = [SELECT id, (SELECT id FROM attachments) FROM Task WHERE ID in: taskIDSet];
   
        for (Task t: taskList)
        {
            t.NumberOfAttachments__c = t.Attachments.size();
        }
       
        update taskList;
    }
}
 
 
 
 
**********************************************************************************************************************************************

Class –
 
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
        if (run){
            run = false;
            return true;
        }
        else
        {
            return run;
        }
    }
}
 
 
PLEASE HELP. URGENT!!
Hello, I am trying to improve given controller class. Can anybody tell me how can I improve given controller class for this VF page which is redirected from account using custom button. I want to improve this class code as per coding standards.

Thank you.
 
ManageContacts.vfp
<apex:page standardController="Account" extensions="ManageContactController" >
    <div style="position:absolute;top:15px;left: 50%;">
        <apex:actionStatus id="actionProcess" >
            <apex:facet name="start" >
                <apex:image url="{!$Resource.Load_white}" height="40px" />
            </apex:facet>
        </apex:actionStatus>
    </div>
    <apex:form > 
    	<apex:pageBlock title="Contacts of Account : {!account.Name}" id="contactList">
    	    <apex:pageBlockButtons >
                <apex:commandButton action="{! saveAll }" value="Save all"/>
                <apex:commandButton action="{! cancel }" value="Cancel"/>
            </apex:pageBlockButtons>
             <apex:variable value="{!0}" var="rowNum"/> 
            <!--<apex:pageBlockSection columns="5">-->
                <apex:pageBlockTable id="pb1" value="{!listContacts}" var="contact" align="center">
                    <apex:column headerValue="Action" >
                        <apex:commandButton action="{!deleteRow}" value="Delete" immediate="true" reRender="contactList" status="actionProcess">
                            <apex:param value="{!rowNum}" name="rowNumId" assignTo="{!rowNumId}"/>
                        </apex:commandButton>
                        <apex:variable var="rowNum" value="{!rowNum + 1}" />
                    </apex:column>    
      	        	<apex:column headerValue="First Name"><apex:inputField value="{!contact.FirstName}" /></apex:column>
      	    	    <apex:column headerValue="Last Name"><apex:inputField value="{!contact.LastName}"/></apex:column>
      	        	<apex:column headerValue="Phone"><apex:inputField value="{!contact.Phone}"/></apex:column>
      	    	    <apex:column headerValue="Email"><apex:inputField value="{!contact.Email}"/></apex:column>
   		        </apex:pageBlockTable>
   		        <br/><apex:commandLink value="Add Contact Row" action="{!addContactRow}" immediate="true" reRender="contactList" status="actionProcess"/>
            <!--</apex:pageBlockSection>-->
	    </apex:pageBlock>
    </apex:form>
</apex:page>

ManageContactController.apxc

public class ManageContactController {
    public List<Contact> listContacts       {   get;set;    }
    public List<Contact> deleteContacts  = new List<Contact>();
    public Set<Contact> CompareContacts = new Set<Contact>();    
    private Account objAccount;
    public ManageContactController(ApexPages.StandardController stdController){
        objAccount = (Account) stdController.getRecord();
        listContacts = getContacts(objAccount.Id);
        compareContacts.addAll(listContacts);
    }
    // To fatch contacts from database using AccountId
    private List<Contact> getContacts(String accountId){
        return [SELECT Id, 
                       FirstName, 
                       LastName, 
                       Phone, 
                       Email 
                  FROM Contact 
                 WHERE AccountId =:accountId];
    }
    // To add new row to table
    public void AddContactRow(){
        listContacts.add(new Contact(AccountId = objAccount.Id));
    }
    // To update database
    public void saveAll(){
        List<Contact> listContactsAdd = new List<Contact>();
        for(Contact objContact : listContacts ) if(objContact.LastName !=null) listContactsAdd.add(objContact);
        upsert listContactsAdd;
        if(! deleteContacts.isEmpty()) delete deleteContacts;
    }
    // To delete row from table
    public void deleteRow(){
        Integer rowId = Integer.valueOf(apexpages.currentpage().getparameters().get('rowNumId'));
            if(compareContacts.contains(listContacts.get(rowId))) deleteContacts.add(listContacts.get(rowId));
            listContacts.remove(rowId);
    }
}

<apex:page tabStyle="Account" controller="ShowdDetailCtrl">
<apex:sectionHeader title="Inline Edit Support" subtitle="Account"/>
<apex:form >
    
<apex:pageBlock title="Account Detail Page">
   <apex:pageBlockButtons LOcation="top">
      <apex:commandButton value="Save" action="{!saveAccount}"/>
   </apex:pageBlockButtons>
   
<apex:pageBlockTable value="{!lstAccountObjs}" var="acc">
<apex:variable value="{!0}" var="count"/>



<apex:column headerValue="Select">
    <apex:facet name="header">
            <apex:outputPanel >
                Select <input type="checkbox" id="selectAll" name="selectAll" onclick="selectAllOrNone();" />
            </apex:outputPanel>
    </apex:facet>
      
     <apex:inputCheckbox styleClass="selectAccount" value="{!acc.isSelected}"/>

</apex:column>

<apex:column headerValue="Account Name">
    <apex:inputtext value="{!acc.name}"/>
</apex:column>

<apex:column headerValue="Phone">
       <apex:inputtext value="{!acc.phone}"/>
       <apex:commandLink value="Remove" action="{!removeAccount}">
        <apex:param name="c" assignTo="{!count}" value="{!count}"/>
        </apeX:commandlink><br/>
        <apex:variable value="{!count+1}" var="count"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>

<script>
    function selectAllOrNone(){
            var isSelected = document.getElementById('selectAll').checked;
            var elements = document.getElementsByClassName('selectAccount');
            for (var i = 0; i < elements.length; i++) {
                document.getElementsByClassName('selectAccount')[i].checked = false;
        }
        if(isSelected){
                var elements = document.getElementsByClassName('selectAccount');
                for (var i = 0; i < elements.length; i++) {
                    document.getElementsByClassName('selectAccount')[i].checked = true
            }
        }
    }
</script>
</apex:page>


class------------------------------------------------------------------------------------

public class ShowdDetailCtrl {
    public list<AccountObj> lstAccountObjs {get;set;}
    public Integer count { get; set; }
    
    //CONSTRUCTOR
    public ShowdDetailCtrl(){
        init();
    }
    
    public void init(){
        lstAccountObjs = new list<AccountObj>();
        for(Account acc : [select id,name,phone from account limit 5]){
            lstAccountObjs.add(new AccountObj(acc));
        }
    }
    
    public PageReference removeAccount() {
        lstAccountObjs.remove(count-1);
        return null;
    }
    
    public PageReference saveAccount() {
        List<Account> lstAccounts = new List<Account>();
        if(lstAccountObjs.size() > 0){
            for(AccountObj accObj : lstAccountObjs){
                
                if(accObj.isSelected){
                    System.debug('###CHeckBox'+accObj.name);
                    Account acc = new Account();
                    acc.Name = accObj.name;
                    acc.phone = accObj.phone;
                    acc.Id = accObj.accId;
                    lstAccounts.add(acc);
                }else{
                    System.debug('###CHeckBoxElse '+accObj.name);
                }
            }
            System.debug(lstAccounts.size());
            for(Account a : lstAccounts){
                System.debug('###listItere'+a.name);
                
            }
            if(lstAccounts.size() > 0){
                update lstAccounts;
            }
            init();
        }
        return null;
    }
    
    public class AccountObj{
        public Boolean isSelected{get; set;}
        public String name{get; set;}
        public String phone{get; set;}
        public String accId{get; set;}
        
        public AccountObj(Account acc){
            this.isSelected = false;
            this.name = acc.Name;
            this.phone = acc.Phone;
            this.accId = acc.Id;
        }
    }
}
i want to display list of accounts in my org using lightning , may i konw how to write the code 
Hi guys.

Looking to create an Apex trigger to fire on the Opportunity to convert a Long Text Area String to opportunityLineItems. I have a pricebook set on the opportunity already, so i think i am looking for a type of map that looks at the pricebook entry from the name and supplies a PricebookEntryID, then creating a loop of Opportunity Line Items with the entrys.

E.g. On Opportunity - Product_Names__c - Product 1, Product 2, Product 3

I can have the string seperated/formated in a number of ways, semi colon, no space etc.

Does anyone have any idea how this would look? sorry, still new with Maps.

Nick
Hi Everyone,
        I have written an apex trigger that fetches the contact email from a caser, matches that email with users in salesforce and assigns the matched user the ownership of that case. Please find the code given below:

The code works well, the map is coming out to be as expected in debug statement . But I am getting a null pointer in the bold lines. Can anyone please help me?

trigger AssignFDMCaseOwner on Case (after insert) {
   //create an empty list to hold the contact email IDs
   List<String> contactmailIds = new List<String>();
    for (Case c :Trigger.new) {    
        if ( c.SuppliedEmail!=null) {
            //add the contact ids to the list
            contactmailIds.add(c.SuppliedEmail);         
        }
    }

    //Query for the contacts and add them to a map
   

    Map<String,User> UserMap = new Map<String,User>([SELECT Email,Id  FROM User WHERE FirstName ='Shrey' AND Email IN :contactmailIds Limit 1]);
    system.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaa'+ UserMap);
    
    for(Case c :Trigger.new) {
       if(c.SuppliedEmail!=Null && UserMap.get(c.SuppliedEmail).Id!=null){
           c.OwnerId = UserMap.get(c.SuppliedEmail).Id;

           update c;
       }
              
    }
}
Hi All,
I have written a trigger on Account.
I am storing mutiple phone number values in phone number field and I am splitting those values into three different fields.
It is working fine. If I update any phone number in phone field, I want to see the same change in those fields. This updation is not working.

Please suggest me the changes

This is the code I have written.

trigger AccountPhoneTrigger on Account (before insert) {
 List<String> descriptionValues;
 List<Id> accountIds = new List<Id>(); 
        for(Account acc: Trigger.New){
        if(!String.isBlank(acc.Phone)){
           descriptionValues = acc.Phone.split(',');
            
           for(Integer count = 0; count < descriptionValues.size(); count ++){
                    acc.Pho1__c = descriptionValues[0].trim();
                       acc.Pho2__c = descriptionValues[1].trim();
                       acc.Pho3__c = descriptionValues[2].trim();
                        
           }
        }
            
   
    }
}