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
Srinivas223Srinivas223 

Refresh the page with search keywords after saving the record

Hello All,
I am very new to lightning and trying hard to understand few things.
I created a lightning component which has few filter fields and a search button to search for records, which displays opportunity records based on the filters. I have Save button on each opportunity. When a user click on Save button, it should update the opportunity and refresh the page which should refresh the list of opportunities. Everything works perfect except the Save functionality and rendering the updated list.
I appreciate your time and effort.
Thank you!
<aura:component controller="ControllerOpportunitiesList"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
   <aura:handler event="force:refreshView" action="{!c.doInit}" />

   <!-- <aura:attribute name="Opportunities" type="List" /> -->
    <aura:attribute name="searchResult" type="List" description="use for store and display Opportunities list return from server"/>
    <aura:attribute name="Owner" type="String" />
    <aura:attribute name="Stage" type="String" />
    <aura:attribute name="Division" type="String" />
    <aura:attribute name="ProductName" type="String" />
    <aura:attribute name="Message" type="boolean" default="false" description="use for display no record found message"/>
    <aura:attribute name="TotalNumberOfRecord" type="integer" default="0" description="use for display Number of records"/>
    
    <!-- SHOW LOADING SPINNER --> 
    <lightning:spinner variant="brand" size="large" aura:id="Id_spinner" class="slds-hide" />
    <div class="slds-m-around_medium slds-container_x-large" >
       <!-- SEARCH INPUT AND SEARCH BUTTON--> 
        <lightning:layout multipleRows="true">
            <lightning:layoutItem >
                <lightning:input value="{!v.Owner}"                                 
                                 aura:id="OwnerName"
                                 label="Owner Name"/>
            </lightning:layoutItem><br/>
            <lightning:layoutItem >
                <lightning:select value="{!v.Stage}"
                                 aura:id="searchStage"
                                 label="Stage Name"> 
            <!--   <lightning:select name="select1" label="How many tickets?" required="true"> -->
                    <option value="">choose one...</option>
                    
                </lightning:select> 
            </lightning:layoutItem>
            <lightning:layoutItem >
                <lightning:select value="{!v.Division}"
                                 aura:id="searchDivision"
                                 label="Division">
                    <option value="">Select Division</option>
                	
				</lightning:select>
            </lightning:layoutItem> 
            <lightning:layoutItem >
                <lightning:select value="{!v.ProductName}"
                                 aura:id="searchProductName"
                                 label="ProductName">
                    <option value="">Select Product</option>
                   
	      </lightning:select>
            </lightning:layoutItem>
            <br/>
            <lightning:layoutItem size="2" padding="around-small">
                <lightning:button onclick="{!c.Search}"
                                  variant="brand"
                                  label="Search"
                                  iconName="utility:search"/> 
            </lightning:layoutItem>
        </lightning:layout>
    </div>
        <!-- TOTAL RECORDS BADGES--> 
        <div class="slds-m-around_x-small">
            <lightning:badge label="{!v.TotalNumberOfRecord}" />
        </div>
        
        <!-- ERROR MESSAGE IF NOT RECORDS FOUND--> 
        <aura:if isTrue="{!v.Message}">
            <div class="slds-notify_container slds-is-relative">
                <div class="slds-notify slds-notify_toast slds-theme_error" role="alert">
                    <div class="slds-notify__content">
                        <h2 class="slds-text-heading_small">No Records Found...</h2>
                    </div>
                </div>
            </div>
        </aura:if> 
       
        <!-- TABLE CONTENT--> 
        <aura:iteration items="{!v.searchResult}" var="opp">
                <div class="slds-col slds-m-around--medium slds-container_x-large"> 
					<th scope="row"><div class="slds-truncate" title="{!opp.Division_Stage_OpptyName__c}">{!opp.Division_Stage_OpptyName__c}</div></th><br />
         <lightning:layout horizontalAlign="spread" multipleRows="true"> 
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Stage">Stage</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Stage" class="slds-input" value="{!opp.StageName}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Forecasted">Forecasted</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Forecasted" class="slds-input" value="{!opp.Forecasted__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="MustSellFirst__c">MustSellFirst</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="MustSellFirst__c" class="slds-input" value="{!opp.MustSellFirst__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="TradeQuoteValue__c">TradeQuoteValue</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="TradeQuoteValue__c" class="slds-input" value="{!opp.TradeQuoteValue__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Current_Offer__c">Current_Offer</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Current_Offer__c" class="slds-input" value="{!opp.Current_Offer__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="DemoDate__c">DemoDate</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="DemoDate__c" class="slds-input" value="{!opp.DemoDate__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Next_Step__c">NextStep</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Next_Step__c" class="slds-input" value="{!opp.Next_Step__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Last_Step__c">LastStep</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Last_Step__c" class="slds-input" value="{!opp.Last_Step__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Next_Step__c">Next_Step</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Next_Step__c" class="slds-input" value="{!opp.Next_Step__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="Targeted_Serial__c">TargetedSerial</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Targeted_Serial__c" class="slds-input" value="{!opp.Targeted_Serial__c}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="CloseDate">CloseDate</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="CloseDate" class="slds-input" value="{!opp.CloseDate}" />
                  </div>
              </div>
             <div class="slds-form-element">
                  <label class="slds-form-element__label" for="CloseDate">Delivery</label>
                  <div class="slds-form-element__control">
                    <input type="text" id="Delivery__c" class="slds-input" value="{!opp.Delivery__c}" />
                  </div>
              </div>
             <lightning:button value="{!opp}"
					label="Save" onclick="{!c.saveOpportunity}"/>  
       </lightning:layout>
    </div>
   </aura:iteration>
</aura:component>
Controller
({
      
    Search: function(component, event, helper) {
        var Owner = component.find('OwnerName');
        var Stage = component.find('searchStage');
        var Division = component.find('searchDivision');
        var Product = component.find('searchProductName');
        var isValueMissing = Owner.get('v.validity').valueMissing;
        // if value is missing show error message and focus on field
        if(isValueMissing) {
            Owner.showHelpMessageIfInvalid();
            Owner.focus();
        }else{
          // else call helper function 
            helper.SearchHelper(component, event);
        }
    },
    saveOpportunity : function(component, event, helper) {
        helper.updateHelper(component, event);
    }
})

Helper:
({
	SearchHelper: function(component, event) {
        // show spinner message
         component.find("Id_spinner").set("v.class" , 'slds-show');
        var action = component.get("c.fetchOpportunities");
        action.setParams({
             
            'Owner': component.get("v.Owner"),
            'Stage': component.get("v.Stage"),
            'Division': component.get("v.Division"),
            'Product': component.get("v.ProductName")
        });
        action.setCallback(this, function(response) {
           // hide spinner when response coming from server 
            component.find("Id_spinner").set("v.class" , 'slds-hide');
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                
                // if storeResponse size is 0 ,display no record found message on screen.
                if (storeResponse.length == 0) {
                    component.set("v.Message", true);
                } else {
                    component.set("v.Message", false);
                }
                
                // set numberOfRecord attribute value with length of return value from server
                component.set("v.TotalNumberOfRecord", storeResponse.length);
                
                // set searchResult list with return value from server.
                component.set("v.searchResult", storeResponse); 
                
            }else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
     updateHelper : function(component, event) {
        var opp = event.getSource().get("v.value")
        console.log('oppty-- > ' + JSON.stringify(opp));
        
        var action1 = component.get("c.saveOpp");
        action1.setParams({ "op" : opp });
        action1.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
              //  $A.get('e.force:refreshView').fire();
                console.log('server- > ' + resp.getReturnValue());
                alert('Success');
            }
            else if (state === "ERROR") {
                var errors = resp.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } 
                else {
                    console.log(resp.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action1);
    }
})

Apex
Public Class ControllerOpportunitiesList{
    @AuraEnabled
    public static List<Opportunity> returnList {get;set;}
    @AuraEnabled
    public static String Owner{get;set;}
    @AuraEnabled
    public static String Stage{get;set;}
    @AuraEnabled
    public static string Division{get;set;}
    @AuraEnabled
    public static string Product{get;set;}
    @AuraEnabled
    public static Opportunity op{get;set;}
    @AuraEnabled
     
     public static List<Opportunity> fetchOpportunities(String Owner,String Stage,String Division,String Product) {
      system.debug('------------------ ' + Owner +' 0000 '+ Stage);
      user u = new user();
      u =[select id, name from user where  name =: Owner limit 1];
      system.debug('9999999999999 ' + u.id + '---- '+ Division +' --- '+ Product);
      list<product2> prodIds =[select id, name from  Product2 where name =: Product ];
      set<id> Product2Ids = new set<id>();
      for(product2 pd: prodIds )Product2Ids.add(pd.id);
     // list<OpportunityLIneItem> LineItems =[select id, product2Id, opportunity.name, opportunity.id from OpportunityLIneItem];
      set<id> oppIds = new set<id>();
      list<OpportunityLIneItem> lineItems = [select id, product2id,opportunity.name,opportunity.id from  OpportunityLIneItem where product2id in:Product2Ids];
        for(OpportunityLIneItem item: lineItems){oppIds.add(item.opportunity.id); system.debug('-------- '+ item.opportunity.id);}
        system.debug('-------- '+ oppIds);
      returnList = new List<Opportunity>();
      string query = ' SELECT Id, name, stageName,MustSellFirst__c,TradeQuoteValue__c,Current_Offer__c,DemoDate__c,Next_Step__c,Last_Step__c,Targeted_Serial__c, CloseDate,Delivery__c, OwnerId,Division_Stage_OpptyName__c, Opportunity_Delivery_Quarter__c, Forecasted__c,Division__c FROM Opportunity where '; 
       if(u.id != null)query = query+ ' ownerId = \'' + u.id +'\' '; //  and
         // Opportunity_Delivery_Quarter__c=:Opportunity_Delivery_Quarter and 
        if(stage != '' && stage !=null) query = query+ ' and StageName=\''+ Stage+'\' '  ;
        if(division!= ''&&division!= null) query=query+ ' and Division__c =\''+ Division+'\' ';
        if(!oppIds.isEmpty())query += ' and id in:  oppIds ';
      system.debug('complete query ' + query);  
      List<Opportunity> lstOfOpps = database.query(query);
      for (Opportunity opp: lstOfOpps) {
       returnList.add(opp);
       system.debug('pppppp '+ opp.name + '--- ' + opp.id);
      }
      return returnList;
     }
  
    @AuraEnabled
      public static List<Opportunity> saveOpp() {
        
        update op;
       // fetchOpportunities(Owner,Stage,Division,Product);
        return returnList;
    }
   
        
}

:

Here is my code.
Best Answer chosen by Srinivas223
Srinivas223Srinivas223
Resp in the helper should be replaced with Response.

Thanks

All Answers

Santosh Bompally 8Santosh Bompally 8
Hi Srinivas, 

Try this, 
Call Search method in Saveopportunity method. 

Add this In Component 
<aura:method name="search" action="{!c.Search}" description="search method" />

Update In Controller 
 
saveOpportunity : function(component, event, helper) { 
helper.updateHelper(component, event); 
component.search();
​}
All the Best. 

Marks as BA if it helps. 

Thanks
 
Srinivas223Srinivas223
Hello Santhosh,

Thank you for your time.
The error I got is in the call back. I modified the code as you said as well.

Thanks,
SrinivasUser-added image

 
Srinivas223Srinivas223
Resp in the helper should be replaced with Response.

Thanks
This was selected as the best answer