function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shiv ShankarShiv Shankar 

How to delete a row in visualforce page.

Hi All,

 

I have one scinario. in that scinario I am making a multiple record editing page. Where user can add, Edit , delete multiple records at a time.

I have some of the fields required in that object. Please have a look of following image for better understading : 

 

https://drive.google.com/file/d/0B-kKCGMuue-fdFpqT19YMDhWbEU/edit?usp=sharing

 

Problems : 

1. suppose user hit on '+' button he will get a new row. But if he want to do undo, by selecting 2nd row and click on '-' sign than also it is asking to enter required field.

2. If i use Immediate or apex:actionregion than selected list is not passing to controller and it showing error please select a row (Which i am thorwing)

 

Can anyone provide best solution for this type of scinario

 

---- Lot of thanks for the help ---

 

 

bob_buzzardbob_buzzard

Actionregion is the correct way to do this - using immediate=true will discard any user changes.

 

How are you passing the selected information back to the controller? If you are using a parameter on a command button, you have to use the rerender attribute for it to be sent back to the controller.

 

 

 

Shiv ShankarShiv Shankar

I am checking in controller itself , what are the item selected by the user .

 

public void deleteGS(){
    Try {
      Integer deletedNoOfIntesm = 0;
      Integer vIndexNo          = 0;
      
      List<Goal_Setting__c> vLstGSToDelete = new List<Goal_Setting__c>();
      
      while(vIndexNo < vLstGoalSetting.size()){
        if(vLstGoalSetting[vIndexNo].GS_Select__c){
          if(vLstGoalSetting[vIndexNo].Id != NULL){
            vLstGSToDelete.add(vLstGoalSetting.get(vIndexNo));
          }
          vLstGoalSetting.remove(vIndexNo);
          deletedNoOfIntesm = deletedNoOfIntesm + 1;              
        }
        else {
          vIndexNo ++;
        }
      }
      if(vLstGSToDelete.size() != 0){
        Delete vLstGSToDelete;
      } 
      if(deletedNoOfIntesm == 0){
        throw new CustomException('Please select row to delete');       
      }
    }
    Catch(CustomException ex) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
    }
    Catch (Exception ex){
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,ex.getMessage()));
    }
           
  }

 When i use ActionRegion around '-'  button then i also get the same problem. I got a example of apex:region on web that was working fine. but it is not working in my scinario. Second thing ActionRegion is showing different behaviour with docType="html-5.0" . It shows validation using java script only. Eventhough example which i got on ApexRegion that becomes fails if i use html-5.0 docType.

bob_buzzardbob_buzzard

My question is still the same - how are you passing the parameter to the controller? You need to post the markup that generates the link/button that the user clicks, as that is where the parameter comes from.

Shiv ShankarShiv Shankar

Below is the markup which i have used .

 

<apex:page standardController="GMS__c" extensions="GMS" sidebar="false" docType="html-5.0">
   
     <div style="padding:0px 80px;">
     <apex:pageMessages id="Message"></apex:pageMessages>
     <apex:form >
	 
	 
       <!-- Section to add or delete goal -->
	   
          <apex:panelGroup id="GS">
            <table Class = "list"  width="100%">
            <tr>
              <td class="header" colspan="10">
                <apex:outputText style="Color : white;" Value="GOAL SETTING"/><br/>            
              </td>
            </tr>
              <tr>
                <td class="theader"></td>
                <td class="theader"><center>Goals</center></td>
                <td class="theader"><center>Target</center></td>                        
                <td class="theader"><center>Measurement Criteria</center></td>
                <td class="theader"><center>Weightage (%)</center></td>
                <td class="theader"><center>Target Date</center></td>
                <td class="theader"><center>Approach</center></td>
                <td class="theader"><center> Self Assessment Comment</center></td>
                <td class="theader"><center>Self Assessment Rating</center></td>
                <td class="theader"><center>Request for Goal Review</center></td>
               </tr>
               <apex:variable value="{!1}" var="rowcount"/> 
               <apex:repeat value="{! vLstGoalSetting}" var="goal"> 
                 <tr>
                   <td class="ListData">
                     <apex:inputfield value="{!goal.GS_Select__c}"/>
                   </td>
                   <td class="ListData">
                       <apex:inputtext style="width:96%"  value="{!goal.GS_Goals__c}"  size="10" />                  
                   </td>
                   <td class="ListData">
                       <apex:inputtext style="width:96%"  value="{!goal.Target__c}" styleClass="jSF_Required" size="10" />
                   </td>
                   <td class="ListData">
                       <apex:inputtext style="width:96%"  value="{!goal.GS_Measurement_Criteria__c}" styleClass="jSF_Required" size="10" />
                   </td>
                   <td class="ListData">                  
                       <apex:inputtext style="width:96%"  value="{!goal.GS_Weight_age__c}" styleClass="jSF_Required" size="10" />
                   </td>
                   <td class="ListData">
                       <center><apex:inputField value="{!goal.Target_Date__c}" styleClass="jSF_Required"/></center>
                   </td>
                   <td class="ListData">
                       <apex:inputField style="width:96%"  value="{!goal.Approach__c}" styleClass="jSF_Required" />
                   </td>
                   <td class="ListData">
				     <apex:inputField style="width:96%"  value="{!goal.Self_Assessment_Comment__c}" styleClass="jSF_Required"  />
				   </td>
                   <td class="ListData">
				     <apex:inputField style="width:96%"  value="{!goal.Self_Assessment_Rating__c}" styleClass="jSF_Required"  />
				   </td>
                   <td class="ListData">
				     <center><apex:inputfield value="{!goal.Request_for_Goal_Review__c}" styleClass="jSF_Required"/></center>
				   </td>
                 </tr>    
                 <apex:variable value="{!rowcount+1}" var="rowcount"/>
               </apex:repeat>       
             </table>
            </apex:panelGroup>
            
			
			<!-- these are the buttons i have used to add or remove rows -->
			
              <apex:commandButton id="GSAdd" value="Add Row" action="{!addGS}" title="Click to add row" style="height:20px;width:20px;" image="{!$Resource.AddRow}" reRender="GS,Message" />

              <apex:commandButton id="GSdel" value="Delete Row" action="{!deleteGS}" title="Click to delete row" style="height:20px;width:20px;" image="{!$Resource.DeleteRow}"  reRender="GS,Message"  />
             	 
			 
     </apex:form>
     </div>
</apex:page>

 Below is My Controller 

 

public Class GMS{
  public String vStrUserId {get; set; }
  public User vUser ;
  public string profileImageUrl{ get; set; }
  public Date vAssessmentStartDate {get; set; }
  public Date vAssessmentEndDate {get; set; }
  public Goal_Setting__c vFetchPeriodFrom {get; set; }
  public Goal_Setting__c vFetchPeriodTo {get; set; }
  public List<Goal_Setting__c> vLstGoalSetting {get; set; }
  private List<FiscalYearSettings> vLstFiscalYear ;
  public List<SelectOption> vLstFiscalYearOptions ;
  public String vStrSelectedFiscalYear {get;set;}
  public List<Goal_Setting__c> vLstGSReviewQueue ;
  public Map<String,OrganizationGoal__c> vMapFiscalYearToGoal;
  public String FiscalYearGoal{get;set;}
  public Resource__c vResourc {get;set;}
  
  public Resource__c vCurrentResource {get;set;}
  public List<Resource__c> vLstTeam {get;set;}
  
  User vUserEmployee ;
  public GMS(ApexPages.StandardController sc){
    /* instantiate variables */
    vFetchPeriodFrom = new Goal_Setting__c ();
    vFetchPeriodTo = new Goal_Setting__c ();
    vLstGoalSetting = new List<Goal_Setting__c> ();
    
    // Set Fiscal Year which is default selected in Assessment year.
    if(getvLstFiscalYear().size() != 0){
      vStrSelectedFiscalYear = vLstFiscalYear[0].Name;
    }  
    
    //Fetch fiscal year goal of the organisation
    vMapFiscalYearToGoal = OrganizationGoal__c.getAll();
    if(vMapFiscalYearToGoal != NULL && (! String.isBlank(vStrSelectedFiscalYear))){
      FiscalYearGoal = vMapFiscalYearToGoal.get(vStrSelectedFiscalYear).goal__c;
    }  
    
    /* fetch the User Id
     - If Manager comes through the e-mail or main page to review goal of Employee he will get user id in the URL.
     - If User visit his goal list for that user id will be fetched according to user login.
    */
    Try {
      if(ApexPages.currentPage().getParameters().get('UserId') != NULL ) {
        vStrUserId = ApexPages.currentPage().getParameters().get('UserId');
      }
      else {
          vStrUserId = UserInfo.getUserId();  
      }
      
      //Fetch Resource record associated with the user.
      List<Resource__c> temp = [Select id, Employee_Type__c, Name, Reporting_To__r.Name, Designation__c, Reporting_To__r.Designation__c,
                                Employee_ID_Number__c
                                FROM Resource__c WHERE User__c =: vStrUserId
                               ];
      if(temp.size() == 0){
        throw new CustomException('Your User Id is not associated with your resource record. Please fill User filed on resource record.');
      }
      else {
        vCurrentResource = temp[0];
        vLstTeam = new List<Resource__c> ();
        vLstTeam = [Select id, Employee_Type__c, Name, Reporting_To__r.Name, Designation__c, Reporting_To__r.Designation__c, User__c
                    FROM Resource__c WHERE Reporting_To__c =: vCurrentResource.id
                   ];
      }
      
      
      // Throw Error if User id not fetched
      if(String.isBlank(vStrUserId)){
        throw new CustomException('User Id is not available');
      }
    }
    Catch(CustomException ex){
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,ex.getMessage()));
    }
    Catch(Exception ex) {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,ex.getMessage()));
    }  
    
    // Creat Default list for goal settings
    fetchGoalSettings();
  }
  
  public User getvUser(){
    Try {
      If(vUser == NULL) {
        vUser = [SELECT Id, Name, Email, Department,EmployeeNumber,Title,Location__c,Region__c,Manager.name,
                 Manager.id,Manager.EmployeeNumber,Manager.Title, FullPhotoUrl FROM User WHERE Id =: vStrUserId] ;
      }
    }  
    Catch(Exception ex){
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage()));
      return null;
    }
    return vUser;
  }
  
  /*Method fetchGoalSettings
    Purpose : To make a list of goal settings for the year which is seleted in Assessment Year.
    parameters : None.
    return type : None.
  */  
  
  public void fetchGoalSettings(){
    Try{
      FiscalYearSettings vFiscalYear;
      vLstGoalSetting.clear();
      if(! String.isBlank(vStrSelectedFiscalYear )){
        vFiscalYear = [SELECT id, StartDate, EndDate, YearType, Name FROM FiscalYearSettings 
                                          WHERE Name =: vStrSelectedFiscalYear LIMIT 1];
      }
      if(vFiscalYear != NULL){                                                               
        vLstGoalSetting = [SELECT id, GS_Select__c, GS_Goals__c, Target__c, GS_Measurement_Criteria__c, GS_Weight_age__c, 
                           Target_Date__c, Approach__c, Interim_Feedback__c, Request_for_Goal_Review__c, Self_Assessment_Rating__c,
                           Manager_Assessment__c, Discussion_Points__c, Status__c, Self_Assessment_Comment__c
                           FROM Goal_Setting__c
                           WHERE Target_Date__c >=: vFiscalYear.StartDate AND Target_Date__c <=: vFiscalYear.EndDate 
                           AND CreatedBYId =: vStrUserId  AND Request_for_Goal_Review__c =: False
                          ];
      }                     
      // If there is no record for that fiscal year, add new row to add a new goal
      if(vLstGoalSetting.size() == 0){
        vLstGoalSetting.add(new Goal_Setting__c());
      } 
      
      // fetch organisation goal for the new fiscal year
      vMapFiscalYearToGoal = OrganizationGoal__c.getAll();
        if(vMapFiscalYearToGoal != NULL && (! String.isBlank(vStrSelectedFiscalYear))){
          if(vMapFiscalYearToGoal.get(vStrSelectedFiscalYear) != NULL) {
            FiscalYearGoal = vMapFiscalYearToGoal.get(vStrSelectedFiscalYear).goal__c;
          }
          else {
            FiscalYearGoal = '';
          }
        }
    }
    Catch (Exception ex){
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
    }
                  
  }
    
  /* Method : getvLstGSReviewQueue 
     Purpose : To create a list of all goal sittings which is created by the user
     Parameter : None
     Returns : List of goal setting which is submitted for review.
  */
  Public List<Goal_Setting__c> getvLstGSReviewQueue(){
    Try{
      FiscalYearSettings vFiscalYear;
      if(vLstGSReviewQueue == NULL){
        vLstGSReviewQueue = new List<Goal_Setting__c> ();
      }
      vLstGSReviewQueue.clear();
      if(! String.isBlank(vStrSelectedFiscalYear )){
        vFiscalYear = [SELECT id, StartDate, EndDate, YearType, Name FROM FiscalYearSettings 
                                          WHERE Name =: vStrSelectedFiscalYear LIMIT 1];
      }
      if(vFiscalYear != NULL){                                                               
        vLstGSReviewQueue = [SELECT id, GS_Select__c, GS_Goals__c, Target__c, GS_Measurement_Criteria__c, GS_Weight_age__c, 
                           Target_Date__c, Approach__c, Interim_Feedback__c, Request_for_Goal_Review__c, Self_Assessment_Rating__c,
                           Manager_Rating__c,Final_Rating__c , Manager_Assessment__c, Discussion_Points__c, Status__c, Self_Assessment_Comment__c
                           FROM Goal_Setting__c
                           WHERE Target_Date__c >=: vFiscalYear.StartDate AND Target_Date__c <=: vFiscalYear.EndDate 
                           AND CreatedBYId =: vStrUserId  AND Request_for_Goal_Review__c =: True
                          ];
      } 
      return vLstGSReviewQueue;
    }
    Catch (Exception ex){
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
      return null;
    }
  }   
  
  
  /* Method addGS 
     Purpose : Add Goal setting row on visual force page when user click on '+' singn.
     Parameter : None
     Returns : None
  */
  public void addGS(){
    Try {
        vLstGoalSetting.add(new Goal_Setting__c());    
    }
    catch (CustomException ex){
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage()));
    }
    Catch (Exception ex){
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, ex.getMessage()));
    }
    
  }  
  
  /* Method addGS 
     Purpose : Delete Goal setting row on visual force page when user click on '-' singn.
     Parameter : None
     Returns : None
  */
  
  public void deleteGS(){
    Try {
      Boolean GSerror           = true;
      Integer deletedNoOfIntesm = 0;
      Integer vIndexNo          = 0;
      
      List<Goal_Setting__c> vLstGSToDelete = new List<Goal_Setting__c>();
      
      for(Integer i= 0; vIndexNo < vLstGoalSetting.size() ; i++){
        if(vLstGoalSetting[vIndexNo].GS_Select__c){
          if(vLstGoalSetting[vIndexNo].Id != NULL){
            vLstGSToDelete.add(vLstGoalSetting.get(vIndexNo));
          }
          vLstGoalSetting.remove(vIndexNo);
          deletedNoOfIntesm = deletedNoOfIntesm + 1;              
        }
        else {
          vIndexNo ++;
        }
      }
      if(vLstGSToDelete.size() != 0){
        Delete vLstGSToDelete;
      } 
      if(deletedNoOfIntesm == 0){
        throw new CustomException('Please select row to delete'+deletedNoOfIntesm +vLstGoalSetting);       
      }
    }
    Catch(CustomException ex) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
    }
    Catch (Exception ex){
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,ex.getMessage()));
    }
           
  }
  
  /* Method saveGS 
     Purpose : Save List of Goal settings.
     Parameter : None
     Returns : None
  */
  
  public void savGS(){
    
    
    upsert vLstGoalSetting;
    vLstGoalSetting.clear();
    fetchGoalSettings();
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Changes are saved'));
  }
  
  //Method to return list of Fiscal Year
  Public List<FiscalYearSettings> getvLstFiscalYear(){
    Try {
      if(vLstFiscalYear == NULL){
        vLstFiscalYear = new List<FiscalYearSettings>();
        vLstFiscalYear  = [SELECT id, StartDate, EndDate, YearType, Name FROM FiscalYearSettings];
      }
      return vLstFiscalYear ;
    }
    Catch (Exception ex){
      ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, ex.getMessage()));
      return NULL;
    }
  }   
  
  // Method to return select option for the Fiscal Year
  public List<SelectOption> getvLstFiscalYearOptions() {
    if(vLstFiscalYearOptions == NULL){
      vLstFiscalYearOptions = new List<SelectOption> ();
      for(FiscalYearSettings vFiscalYear : getvLstFiscalYear()){
        vLstFiscalYearOptions.add(new SelectOption(vFiscalYear.Name,vFiscalYear.Name));
      }     
    }
    return vLstFiscalYearOptions ;
  }
  
  public void temp(){
    FiscalYearSettings d = [SELECT id, StartDate, EndDate, YearType, Name FROM FiscalYearSettings 
                            WHERE StartDate = THIS_FISCAL_YEAR];
  }
  
  /* Method : projectUpdae;
     Purpose : find out the number of projects on which user is working, time he has spent on project respectively, rework and productivity.
     Parameters : None
     Returns : none
     
     -- Some Object Information i want to incluce, since API and Label is different --
     Project -> Scrum Project : Workstream__c
     Users who are working on the projects : WorkstreamUser__c
     Time Entery : Time__c (Time Entery against the task or project etc.)
   */
  Map<Id,TimeMetric> vMapProjectIdToTimeMetric ;  
  public Map<Id,TimeMetric> getvMapProjectIdToTimeMetric(){
    Try {
      // To fetch work stream (Project) Info on which user is working.
      List<WorkstreamUser__c> vLstUserProjects = new List<WorkstreamUser__c> ();
      List<Workstream__c> vLstProject = new List<Workstream__c>(); 
      Set<String> vSetProjectIds = new Set<String> ();
      Map<String,String> vMapIdToProjectName = new Map<String,String>();
      vMapProjectIdToTimeMetric = new Map<Id,TimeMetric> ();
      if(! String.isBlank(vStrUserId) && vStrUserId != NULL && vStrUserId != '') {
        vLstUserProjects = [ SELECT id, Workstream__c, Project_Name__c FROM WorkstreamUser__c WHERE User__c =: vStrUserId] ;
        System.debug('***Workstream user :'+vLstUserProjects);
        //collecting the ids of the projects on which user is woking.
        for(WorkstreamUser__c vWSUser : vLstUserProjects){
          vSetProjectIds.add(vWSUser.Workstream__c);
          vMapIdToProjectName.put(vWSUser.Workstream__c,vWSUser.Project_Name__c);
        } 
        System.debug('***Project List ids :'+vSetProjectIds);
        //get all task on which work stream id in abour list of project and user id is this user.
        List<Task__c> vLstTask = new List<Task__c>();
        vLstTask = [SELECT Id, Work_Stream_ID__c, User_ID__c, ActualHours__c, EstimatedHours__c FROM Task__c 
                    WHERE  Work_Stream_ID__c IN : vSetProjectIds AND User_ID__c =: vStrUserId] ;
        System.debug('***user task :'+vLstTask);
        //calculate time metric
        for(Task__c vTask: vLstTask){
          if(vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c) == NULL) {
            vMapProjectIdToTimeMetric.put(vTask.Work_Stream_ID__c,new TimeMetric());
            vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).ProjectName = vMapIdToProjectName.get(vTask.Work_Stream_ID__c);
            vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntEstimatedHR = vTask.EstimatedHours__c;
            vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntSpentHR = vTask.ActualHours__c;
            
          }
          else {
            vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntEstimatedHR = vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntEstimatedHR + vTask.EstimatedHours__c;
            vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntSpentHR = vMapProjectIdToTimeMetric.get(vTask.Work_Stream_ID__c).vIntSpentHR + vTask.ActualHours__c;
          }
        }
      }
      return vMapProjectIdToTimeMetric ;
    }
    catch(Exception ex) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,ex.getMessage()));
      return null;
    }
  }
  
  //Size of project map
  public Integer vIntTimeMetricSize {
    get {
      return vMapProjectIdToTimeMetric.size();
    } set;
  }
  
  
 /* Method Name : updateMangarReview
    Purpose : To update Manger feedback on customers goal
    Parameter : None
    Returns : None
 */
  
  public void updateMangarReview(){
    update vLstGSReviewQueue; 
  }
  
  //Innter class for time metrics for particualr user.
  public class TimeMetric {
    public String ProjectName {get;set;}
    public Decimal vIntEstimatedHR {get;set;}
    public Decimal vIntSpentHR {get;set;}
    public Decimal vIntPerformance {
      get {
        return vIntSpentHR/vIntEstimatedHR ;
      } set;
    }
    public Decimal vIntRework {get;set;}
    public TimeMetric (){
      vIntEstimatedHR = 0 ;
      vIntSpentHR = 0;
      vIntPerformance = 0;
      vIntRework = 0;
    }
  }
  
   
}

 

bob_buzzardbob_buzzard

There's nothing in your commandbutton markup to indicate the row that the user is trying to delete - you'll need to embed an apex:param containing a unique identifier.

Shiv ShankarShiv Shankar
First column which i am having in my list is checkbox so when user clicks on 'DeleteButton' i reiterate the list in my controller and for which checkbox is selected, i remove that record from the list. that's the reason i am not passing any rowId from the VF Page.... If you have any other suggestion or sample code , let me know.... Thanks
Shiv ShankarShiv Shankar

I got the point sir, what you want to say. Can you little explain what is the best way to pass rowId / Record Id to Controller which i want to delete. I will be very thankfull if you can give some few line of code. Thanks

Nitish 73Nitish 73
@bob_buzzard : I have a requirement where I cannot afford to use the rerender attribute, but I have to pass the parameter id to the controller. How can I achieve this. Please advise. Thanks