• d.tejdeep@nicomatic.in
  • NEWBIE
  • 125 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 6
    Likes Received
  • 0
    Likes Given
  • 109
    Questions
  • 68
    Replies
<aura:attribute name="selectRecordName" type="String" description="text" ></aura:attribute>
    <aura:attribute name="selectRecordId" type="String" description="text" ></aura:attribute>

<tbody>      
                    <aura:iteration items="{!v.QliList}" var="Qli" indexVar="index">
                        <tr>
                            <td> 
                                {!index + 1}
                            </td>
        <td>    
           <div clas="slds-truncate" data-index="{!index}">
        <c:autocompletelwc objectName="US_DB_QLI__c" fieldName="Name" selectRecordId="{!v.selectRecordId}" selectRecordName="{!v.selectRecordName}"  onselected="{!c.selectedRecords}" aura:id="Qliname" />
         Selected Record Name: {!v.selectRecordName} <br/>                                 
            </div>
               <lightning:input   size="8" type="text" required="true"  value="{!Qli.Name}" onclick="{!c.echo}"/>

            </td>
<td>
<lightning:buttonIcon iconName="utility:add"  size="large" variant="bare" alternativeText="Add" onclick="{!c.addRow}"/>    
<a onclick="{!c.removeRow}" data-record="{!index}">
<lightning:icon iconName="utility:delete" size="small" alternativeText="Delete"/>
                                    <span class="slds-assistive-text">Delete</span>
                                </a>
                                
                            </td> 
                        </tr>
                    </aura:iteration>
 
echo: function(component, event, helper) {
     //var ind = event.target.closest("data-index").dataset.value;    
    // alert (ind);   
       //  var searchInput = component.find("Qliname");
   // var searchValue = searchInput.get("v.selectRecordName");   
    let Index =  event.getSource().get("v.name");    
       var qlistring='v.QliList['+Index+'].Name';  
      var searchValue=  component.get("v.selectRecordName");
        if(searchValue!=null){
        component.set(qlistring,searchValue);
        }    
    },
    
    selectedRecords : function(component, event, helper) {
        var selectRecName = event.getParam('selectName');
        var selectRecId = event.getParam('currentRecId');
        if(selectRecName != undefined) {
            component.set("v.selectRecordName", selectRecName);
            component.set("v.selectRecordId", selectRecId);
        }
    }

I am using autocomplete textbox field in a dynamic add and remove records table i am copying value of <c:autocompletelwc to <lightning:input value="{!Qli.Name}
I can able set value dynamically to {!Qli.Name} But i cant to retrive value from the correcting to each row from <c:autocompletelwc
can some please help me in this above problem
I am inserting multiple invoice and invoice items  at using post web service REST API

Main class
 
@RestResource(urlMapping='/InsertInvoiceandInvoiceitems/*')
global class Bulkinsert_InvoiceInvoiceitems
{  
   global class myWrapper
   {
     public List<Invoice__c> Invoicelst;
     public List<Invoice_Item__c> InvoiceLineslst;
      public string status;
      public string message;
   }
   
@HttpPost
   global static myWrapper doPost()
   {
      
    RestRequest req = RestContext.request;
    Blob body = req.requestBody;
    String requestString = body.toString();
     //system.debug(requestString);
      myWrapper response=new myWrapper(); //this is object of wrapper class
      
      JsonParserInv rw = (JsonParserInv)JSON.deserialize(requestString,JsonParserInv.class);
       List<Invoice__c> InvList=new List<Invoice__c>();
       List<Invoice_Item__c> InvItemsList=new List<Invoice_Item__c>();
       List<Invoice_Item__c> InvItemsList123=new List<Invoice_Item__c>();
       Map<Integer,Invoice_Item__c> mapinvitems = new Map<Integer,Invoice_Item__c>();
       Map<Integer,List<Invoice_Item__c>> mapInvIdToInvitems = new Map<Integer,List<Invoice_Item__c>>();
       
       integer i;
       integer j;
       for(i=0;i<rw.Invoicesdata.invoices.size();i++){
           Invoice__c inv =new Invoice__c();
           inv.Account_Code__c=rw.Invoicesdata.invoices[i].accountCode;
           inv.Invoice_Number__c=rw.Invoicesdata.invoices[i].customerPo;
           date mydate = date.parse(rw.Invoicesdata.invoices[i].invoiceDate); 
           InvList.add(inv);
           //system.debug(InvList);
           for(j=0;j<rw.Invoicesdata.invoices[i].invoiceLines.size();j++){
           Invoice_Item__c ils = new Invoice_Item__c();
            ils.Name= rw.Invoicesdata.invoices[i].customerPo ;
            ils.Product_Family_code__c=rw.Invoicesdata.invoices[i].invoiceLines[j].familly;
            ils.Product_Family__c=rw.Invoicesdata.invoices[i].invoiceLines[j].famillyName; 
         //   InvItemsList.add(ils);
            mapinvitems.put(j, ils);    
               system.debug(mapinvitems);   
           }
          mapInvIdToInvitems.put(i,mapinvitems.values());
           system.debug(mapInvIdToInvitems.keyset());             
       }   
 
      try
      {
          insert InvList;
          //Invoicelst.addall(InvList);
          
          
          for(Integer k = 0; k < InvList.size(); k++)
          {
             for(Invoice_Item__c objinvitems : mapInvIdToInvitems.get(k))
             {
                objinvitems.Invoice__c = InvList[k].Id;
                InvItemsList.add(objinvitems);
             }
          }
          
          insert InvItemsList;
          
          
         response.Invoicelst=InvList;
         response.InvoiceLineslst=InvItemsList;
         response.status='Success';
         response.Message='Total No of Invoice inserted :'+InvList.size()+ '===' +'Total No of Invoice items inserted :'+InvItemsList.size();
      }
       
      catch(exception ex)
      {
         response.Invoicelst=null;
         response.InvoiceLineslst=null;
         response.status='ERROR';
         response.Message='could not create record'+ ex.getMessage();
      }
      
      return response;
   }
   
}
json apex parser
 
public class JsonParserInv{
    public Invoicesdata Invoicesdata{get;set;}
	public class Invoicesdata{
		public list<invoices> invoices{get;set;}
	}
	public class invoices{
		public String invoiceDate{get;set;}
		public String customerPo{get;set;}
		public list<invoiceLines> invoiceLines{get;set;}
		public String accountCode{get;set;}
	}
	public class invoiceLines{
		public String familly{get;set;}
		public String famillyName{get;set;}
	}
}

sample json:
'{"Invoicesdata":{"invoices": [{"accountCode" : "ELECTRONIC","customerPo" : "AV1600117","invoiceDate" : "05/01/2016","invoiceLines" : [{"DAS" : "","familly" : "","famillyName" : ""}]}]}}';

test class:
 
@isTest
public class TestBulkinsert_InvoiceInvoiceitems { 
 static testmethod void Testinvitems(){
     List<invoice__c> lstinv=new List<invoice__c>();
          integer j;
     for(j=0;j<=10;j++){     
           Invoice__c inv =new Invoice__c();
           inv.Account_Code__c='test'+j;
           inv.Invoice_Number__c='testpo'+j;
           date mydate = date.parse('23/2/2020');
           inv.Date_of_Invoice__c= mydate;
           //insert inv;
           //system.debug(InvList);
           lstinv.add(inv);
     }
     List<Invoice_Item__c> lstinvitems=new List<Invoice_Item__c>();
     
     integer i;
     for(i=0;i<=10;i++){
           Invoice_Item__c ils = new Invoice_Item__c();
            ils.Invoice__c=lstinv[i].id;
            ils.Product_Family_code__c='68';
            ils.Product_Family__c='879'; 
            lstinvitems.add(ils);
     }    
     Bulkinsert_InvoiceInvoiceitems.myWrapper reqw= new Bulkinsert_InvoiceInvoiceitems.myWrapper();
     reqw.InvoiceLineslst=lstinvitems;
     reqw.Invoicelst=lstinv;
     reqw.message=null;
     reqw.status=null;
    Test.startTest();

         //As Per Best Practice it is important to instantiate the Rest Context
    RestRequest req = new RestRequest();
    RestResponse res = new RestResponse();
    req.requestURI = '/services/apexrest/InsertInvoiceandInvoiceitems'; //Request URL
    req.httpMethod = 'POST';
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
    Test.setMock(HttpCalloutMock.class, new Mock()); 
    Bulkinsert_InvoiceInvoiceitems.myWrapper res2 =new Bulkinsert_InvoiceInvoiceitems.myWrapper(); 
   JsonParserInv rw = (JsonParserInv)JSON.deserialize(JsonMsg,JsonParserInv.class);
     JsonParserInv.Invoicesdata invdata=new JsonParserInv.Invoicesdata();
     JsonParserInv.invoices invs=new JsonParserInv.invoices();
     JsonParserInv.invoiceLines inves=new JsonParserInv.invoiceLines();
        Bulkinsert_InvoiceInvoiceitems.doPost();
    Test.stopTest();

   // System.assertEquals('expected value', actual, 'Value is incorrect');
        
   }
}

Mock class:
 
@isTest
global class Mock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
       // System.assertEquals('http://example.com/example/test', req.getEndpoint());
      //  System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"Invoicesdata":{"invoices": [{"accountCode" : "DICOELECTRONIC","customerPo" : "AV1600117","invoiceDate" : "05/01/2016","invoiceLines" : [{"familly" : "tes","famillyName" : "testfamily"}]}]}}');
        res.setStatusCode(200);
        return res;
    }
}

i cant able to cross code coverage from this line in main class "Bulkinsert_InvoiceInvoiceitems"
JsonParserInv rw = (JsonParserInv)JSON.deserialize(requestString,JsonParserInv.class);

can someone can help me regarding this 
<aura:iteration items="{!v.QliList}" var="Qli" indexVar="sNo">      
               <tr>
                    <td><div class="slds-truncate">{!sNo+1}</div></td>
                    <td><div class="slds-truncate">{!Qli.Name}</div></td>
                    <td><div class="slds-truncate">{!Qli.Description__c}</div></td>
                   <td><div class="slds-truncate">{!Qli.Family__c}</div></td>
                   <td><div class="slds-truncate"><ui:inputText aura:id="dynamicResult" class="pnsuggestion" value="{!Qli.Part_number_Suggestion__c}"/></div></td>
                   <!--<td><div class="slds-truncate">{!Qli.PN_Suggestion__c}</div></td>-->
                    <td><div class="slds-truncate"></div>
                    <lightning:button type="button" onclick="{!c.UpdatePnsuggestion}"   name="CMM Tooling and Accessories" label="{!sNo}">CMM Tooling and Accessories</lightning:button>
 </td>
                </tr>
          </aura:iteration>

//JS

    UpdatePnsuggestion: function(component,event,helper){
       var va= event.getSource().get("v.name");
       var indexnumber= event.getSource().get("v.label");
      console.log(indexnumber);
        component.set("v.QliList.Part_number_Suggestion__c", va);  
    },  

I want to pass the button value to inputtext field {!Qli.Part_number_Suggestion__c}

In iteration n number of record when I click on a button it is copying the value to all records. But in my case, I would like to copy value only to the current row.
 
<apex:pageBlockTable value="{!WrapperOrder}" onclick="insert_numbers()" var="or" id="pbtable">           
             <apex:column headerValue="No." >
                  <apex:outputText value="{0}" style="text-align:center;">
                       <apex:inputField value="{!or.rorli.Row_Num__c}" id="getindex" Style="width:15px" />
                          <apex:param value="{!rowNumber+1}" />     
                          </apex:outputText>                    
             </apex:column>
             <apex:column headerValue="Nicomatic P/N" >
                 <apex:inputField value="{!or.rorli.Name}" id="pnname" required="true" styleClass="theqid"/>
                 </apex:column>
         
             <apex:column headerValue="Client P/N" >
                 <apex:inputField value="{!or.rorli.Client_Pn__c}" Style="width:110px" />
             </apex:column>
             <apex:column headerValue="Description" >
                 <apex:inputField value="{!or.rorli.Description__c}"/>
             </apex:column>
             <apex:column headerValue="Confirmed Shipping Date" >
                 <apex:inputField value="{!or.rorli.Confirmed_Shipping_Date__c}"/>
             </apex:column>

                         <apex:column headervalue="Batch Price and Quantity" >
                                 <table border="1px">
                   <tr>
                       <th>Price</th>
                       <th>Quantity</th>
                       <th>Action</th>
                   </tr>
                    <apex:repeat value="{!or.batc}" var="ba" >  
                    <tr>
                       <td>{!ba.Unit_Price__c}</td>
                       <td>{!ba.Asked_Qty__c}</td>
                       <td><input type="checkbox" onclick="" id="checx" class="checx"/></td>
                   </tr>  
                   </apex:repeat>
                   </table>         
                    </apex:column>
            <apex:column headerValue="Unit Price"  >
               <!-- <input type="text" id="two" value="{!or.rorli.Price__c}" Style="width:60px" name="two" />  -->
                 <apex:inputField id="rpri" value="{!or.rorli.Price__c}" Style="width:50px" styleClass="spri[rowNumber]" />
                
             </apex:column>
             <apex:column headerValue="Qty" id="col"  >
               <!--<input type="text" id="one" value="{!or.rorli.Quantity__c}" Style="width:60px" name="one" />  -->
                 <apex:inputField id="rqty" value="{!or.rorli.Quantity__c}" Style="width:25px" styleClass="sqty[rowNumber]"/>
             </apex:column>

  <script type="text/javascript">       
    checkboxes = document.getElementsByClassName("checx"); 
    for (var i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
    checkbox.onclick = function() {
            var currentRow = this.parentNode.parentNode;
            var secondColumn = currentRow.getElementsByTagName("td")[1];
            var FirstColumn = currentRow.getElementsByTagName("td")[0];           
            alert("My text is: " + secondColumn.textContent +" "+FirstColumn.textContent);
            $('.sqty').val(secondColumn.textContent);
            $('.spri').val(FirstColumn.textContent);

        };
    } 
        
       </script>

I want to specify the send value to a specific row  $('.sqty').val(secondColumn.textContent); $('.spri').val(FirstColumn.textContent);
After clicking Quantity and price form table i want to copy value to apex:inputfield of qty and price of corresponding row 
I want to check whether a response.getReturnValue() is valid JSON or not .if it is a valid JSON then it should parse otherwise it shows error  
if (state === "SUCCESS") {
                   console.log(response.getReturnValue());
                    var jsonData=JSON.parse(response.getReturnValue());
                    console.log(jsonData); 
                    if(!jsonData){
                    component.set("v.Servererror",'Null');
                    }else(jsonData['error']!=null){
                      component.set("v.Servererror",jsonData['error']);
                    }
             }

How to check whether it is a valid JSON or not
Parent Component:
 
<aura:iteration items="{!v.QuotelinitemList}" var="item" indexVar="index">
                <c:Child QliInstance="{!item}" rowIndex="{!index}" randNum="223"  aura:id="childcomp" qid="{!v.ParentId}" Language="{!v.Language}" oldqlino="{!v.oldqlino}"/>
            </aura:iteration>
Parent controller Js:
Save: function(component, event, helper) {
        var qid=component.get("v.ParentId");
        if (helper.validate(component, event)) {
            var action = component.get("c.SaveQlis");
            action.setParams({
                "QliList": component.get("v.QuotelinitemList"),
                "QuoteID" : qid
            });
            // set call back 
            action.setCallback(this, function(response){
                var state = response.getState();
                if (state === "SUCCESS") {
                    var qli=response.getReturnValue(); 
                        $A.createComponent(
                            "c:Child",{
                             "aura:id" : "childcomp"  
                            },function(newChild, status) {
                             if (component.isValid() && status === 'SUCCESS') {
                                    var key=0;
                                    for (key in qli){
                                    var qlisaved=qli[key].Id;
                                    var qliindexno=qli[key].QliRowNum__c;      
                                var childcomponent = component.find('childcomp');
                               childcomponent[key].mychildcompmethod(qliindexno,qlisaved); 
                                        key++;
                                }               
                          }    
                     });  
                }
            });
            $A.enqueueAction(action);
           component.set("v.Likedisable",true); 
        }

    },

Child component method :
 
<aura:attribute name="BatchList" type="Batch__c[]"/>
    <aura:method name="mychildcompmethod" action="{!c.saveBatchDetails}" access="public">
    <aura:attribute name="param1" type="integer"/>
    <aura:attribute name="param2" type="object"/>
    </aura:method>
            <aura:iteration items="{!v.BatchList}" var="item" indexVar="index">
<c:Grandchild  BatchInstance="{!item}" rowIndex="{!index}" qlinum="{!v.rowIndex}" />
            </aura:iteration>
Child Controller js :
 
saveBatchDetails: function(component,event,helper){
    console.log("calling updateRaces in ListRaceController");
    var qid=component.get("v.qid");
    var params = event.getParam('arguments');
    if (params) {
    var param1 = params.param1;
    var param2 = params.param2;
    }
    console.log(param1);
    console.log(param2);
            var par3=component.get("v.rowIndex")+1+component.get("v.oldqlino");
    console.log(par3);
   var action = component.get("c.SaveBatchDet");
    var par1=param1;
    var par2=component.get("v.BatchList");
        action.setParams({
            "Bt": component.get("v.BatchList"),
            "QliRowNum": par3,
            "Rowmap":{param1,par2},
            "QuoteID":qid
        });
        action.setCallback(this,function(resp){
        var state = resp.getState();
        if(state == "SUCCESS"){
            console.log( 'Add Batch Detail is saved');
            window.location.href = '/lightning/r/Quote__c/'+qid+'/view';
        }
        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("Unknown error");
            }


        }

    });

   $A.enqueueAction(action);   
}
Apex class :
 
@AuraEnabled
    public static list<Quote_Line_Item__c> SaveQlis(List<Quote_Line_Item__c> QliList,string QuoteID){

        Map<Integer, Quote_Line_Item__c> qouteLineItemMap = new Map<Integer, Quote_Line_Item__c>();
        integer i=1;
        for(Quote_Line_Item__c qli : QliList)
        {
          qouteLineItemMap.put(i, qli);
           i++; 
         }    

        transient List<Quote_Line_item__c> listtoinsert =new List<Quote_Line_item__c>();

        transient List<Integer> sortkey=new List<Integer>();
        sortkey.addAll(qouteLineItemMap.keySet());
        sortkey.sort();

        Integer rowCount=0;
        rowCount++;
        for(integer key : sortkey){
            if(qouteLineItemMap.containsKey(key) && qouteLineItemMap.get(key)!=null){
                qouteLineItemMap.get(key).QliRowNum__c = rowCount;
                qouteLineItemMap.get(key).Quote1__c=QuoteID;
                rowCount++;
            }
        }
        //Iterating the loop to store the list of QuoteLineItems which are going to be inserted into the databse
        for(integer qli:sortkey){
            if(qouteLineItemMap.get(qli).Name!='' && qouteLineItemMap.get(qli).name!=null){
            listtoinsert.add(qouteLineItemMap.get(qli));

            }
            // conditon to display the error when there is no batch for a particular QuoteLineItem
        }//End of for 

        // Inserting the list of QuoteLine Items
        try{
            system.debug(listtoinsert);
            upsert listtoinsert;
          //  system.debug(listtoinsert);
        } catch(DmlException de){
            return null;
        }
        System.debug('Number of Queries used in this apex code so far: ' + Limits.getQueries());
        return [SELECT QliRowNum__c,Id FROM Quote_Line_item__c where ID IN: listtoinsert];

    }



     @AuraEnabled
        public static list<batch__c> SaveBatchDet(integer QliRowNum,list<Batch__c> Bt,map<integer,list<batch__c>> Rowmap,string QuoteID){
            System.debug('beforedeleteNumber of Queries used in this apex code so far: ' + Limits.getQueries()); 

            //transient List<Integer> sortkey=new List<Integer>();
             Map<Integer,list<batch__c>> batchMap =  New Map<Integer,list<batch__c>>();
                batchMap.put(Integer.valueOf(QliRowNum),Bt);
             transient List<Batch__c> batchListToInsert =new List<Batch__c>();
             Map<integer,Quote_Line_Item__c> qouteLineItemMap = new Map<integer,Quote_Line_Item__c>();

            for(quote_line_item__c t: [SELECT QliRowNum__c, Id FROM quote_line_item__c WHERE quote1__c=:QuoteID])
            qouteLineItemMap.put(Integer.valueOf(t.QliRowNum__c), t);
            transient List<Integer> sortkey=new List<Integer>();
            sortkey.addAll(qouteLineItemMap.keySet());
          for(integer qli:sortkey){
              if(batchMap.get(qli)!=null)
                for(Batch__c bat: batchMap.get(qli)){
                    if(bat.Asked_Qty__c!=null && bat.Asked_Qty__c!=''){
                    bat.Quote_Line_Item__c=qouteLineItemMap.get(qli).id;
                    }
                    if(bat.Quote_Line_Item__c!=null)
                    batchListToInsert.add(bat);
                   // system.debug(batchListToInsert);
                }//End of for 
            }// End of for
            // Inserting the list of batches
            try{

              upsert batchListToInsert ;
                //system.debug(batchListToInsert);
            }catch(DmlException de){
                return null;
            }
            return null;
        }

I am getting 101 soql query error in "SaveBatchDet" apex class .
Form lightning parent component is calling mutiple times on child component action .
if i have 10 parents child is getting called 10 times .
Is there any way in "SaveBatchDet" apex to store all data and perform the action in a single insert .
Please try to help i working on this so many days
 
@AuraEnabled
    public static list<batch__c> SaveBatchDet(integer QliRowNum,list<Batch__c> Bt,map<integer,list<batch__c>> Rowmap,string QuoteID){
          system.debug(QliRowNum+'-------------'+Bt+'@@@@@@@@@@@@@@@@'+Rowmap+'###################'+QuoteID); 
         System.debug('1.Number of Queries used in this apex code so far: ' + Limits.getQueries());
         System.debug('2.Number of rows queried in this apex code so far: ' + Limits.getDmlRows());
        //transient List<Integer> sortkey=new List<Integer>();
         Map<Integer,list<batch__c>> batchMap =  New Map<Integer,list<batch__c>>();
            batchMap.put(Integer.valueOf(QliRowNum),Bt);
         transient List<Batch__c> batchListToInsert =new List<Batch__c>();
        
         Map<integer,quote_line_item__c> qouteLineItemMap = new Map<integer,quote_line_item__c>();
		for(quote_line_item__c t: [SELECT QliRowNum__c, Id FROM quote_line_item__c WHERE quote1__c=:QuoteID])
         qouteLineItemMap.put(Integer.valueOf(t.QliRowNum__c), t);
        
        transient List<Integer> sortkey=new List<Integer>();
        sortkey.addAll(qouteLineItemMap.keySet());
      for(integer qli:sortkey){
          if(batchMap.get(qli)!=null)
            for(Batch__c bat: batchMap.get(qli)){
                if(bat.Asked_Qty__c!=null && bat.Asked_Qty__c!=''){
                bat.Quote_Line_Item__c=qouteLineItemMap.get(qli).id;
                }
                if(bat.Quote_Line_Item__c!=null)
                batchListToInsert.add(bat);
               // system.debug(batchListToInsert);
            }//End of for 
        }// End of for
        // Inserting the list of batches
        try{
        
          upsert batchListToInsert ;
           System.debug('1.Number of Queries used in this apex code so far: ' + Limits.getQueries());
         System.debug('2.Number of rows queried in this apex code so far: ' + Limits.getDmlRows());
            //system.debug(batchListToInsert);
        }catch(DmlException de){
            return null;
        }
        return null;
    }

i am getting error in this query 
 
for(quote_line_item__c t: [SELECT QliRowNum__c, Id FROM quote_line_item__c WHERE quote1__c=:QuoteID])
is there is any workaround to solve this issue?

Could some help me is there is any wrong in my code?

 
 {!v.BatchInstance.Discount_Type__c}
         <td>
            <ui:inputselect class="slds-input" value="{!v.BatchInstance.Discount_Type__c}" aura:id="disctype" change="{!c.discountvalidation}">
             <option value=""> - </option> 
             <option value="ServicePremium"> ServicePremium </option> 
             <option value="Service Rapide"> Service Rapide </option> 
              <option value="MOD/MOQ">     MOD/MOQ </option> 
        
             </ui:inputselect>   
        </td>

I cant able to show  "{!v.BatchInstance.Discount_Type__c}" value in ui:inputselect 

Outside of ui:inputselect it is showing the value .this value is retrieving from the database  
 
<ui:inputcheckbox  value="{!v.BatchInstance.Discount__c}" aura:id="disc" change="{!c.discountvalidation}"/>

discountvalidation : function(component, event, helper){
 var disc = component.find("disc");
    var discvalue = disc.get("v.value");  
        if(discvalue=true){
            alert("true");
        }
        if(discvalue=false){
            alert("false");
        }

I cant able to see false alert by deselecting the checkbox 
 
<lightning:select  value="{!v.BatchInstance.LeadTime__c}" aura:Id="leadtimesel" onchange="{!c.validateotherleadtime}">
             <option value=""> - </option> 
             <option value="Within 48 hours"> Within 48 hours </option> 
             <option value="1 Week"> 1 Week </option> 
             <option value="2 Weeks"> 2 Weeks </option>
             <option value="3 Weeks"> 3 Weeks </option> 
             <option value="4 Weeks"> 4 Weeks </option> 
             <option value="5 Weeks"> 5 Weeks </option> 
             <option value="6 Weeks"> 6 Weeks </option> 
             <option value="7 Weeks"> 7 Weeks </option> 
             <option value="8 Weeks"> 8 Weeks </option> 
             <option value="More than 8 weeks"> More than 8 weeks </option> 
             <!--<option value="1 week if Qty<=999, 4 weeks if Qty>999"> 1 week if Qty<=999, 4 weeks if Qty>999 </option> 
             <option value="1 week if Qty<=249, 2 weeks if Qty>249"> 1 week if Qty<=249, 2 weeks if Qty>249 </option> -->
             <option value="In stock"> In stock </option> 
             <option value="Other"> Other </option> 
             </lightning:select>   
        </td>
         <td>
            <lightning:input  value="{!v.BatchInstance.Other_Lead_Time__c}" aura:id="otherleadtime" />
        </td>
 
validateotherleadtime : function(component, event, helper) {
    var leadesl = component.find("leadtimesel");
    var leadeslvalue = leadesl.get("v.value");  
    var otherleadtime = component.find("otherleadtime");
    var otherleadtimevalue = otherleadtime.get("v.value");  
    
      if(leadeslvalue==='Other' & !otherleadtimevalue) {
            otherleadtime.set("v.errors", [{message:"Other lead time is compulsory"}]);
        }else{
         //otherleadtime.set("v.errors", null);
        }
   }

I want to make other lead time value compulsory when they select lead time as "other" and I want to show this error, message on each and every step and action not at the end while clicking save button 
Parent Action JS :
 
// set call back 
action.setCallback(this, function(response) {
    var state = response.getState();
    if (state === "SUCCESS") {
        var qli=response.getReturnValue();
        var key=0;
        for (key in qli){
            var qliindexno=qli[key].Id;
            var qlisaved=qli[key].QliRowNum__c;                    
            var appEvent = $A.get("e.c:ClearValues");
            appEvent.setParams({ "param1" : qliindexno});
            console.log('NOuyd123');
            appEvent.fire(); 
            console.log('NOuyd');
            key++;
        }
    }
});


child component :
 
<aura:handler  event="c:ClearValues" action="{!c.saveBatchDetails}"/>

Child action :
 
saveBatchDetails: function(component,event,helper){
           console.log("calling updateRaces in ListRaceController");
           var param1 = event.getParam('param1');
           console.log(param1);

User-added image

If we remove
var param1 = event.getParam('param1');
           console.log(param1);
User-added image


Event.getparam is duplicating multiple time if we remove the event.getparam 
 
action.setParams({
                "Bt": component.get("v.BatchList"),
                "QliRowNum": 1,
                "RowIndex":[component.get("v.rowIndex"),component.get("v.BatchList")]
            });
            action.setCallback(this,function(resp){
lightning APEX: 
@AuraEnabled
    public static list<batch__c> SaveBatchDet(integer QliRowNum,list<Batch__c> Bt,map<string,list<batch__c>> RowIndex){

I want to pass  MAP value 

"RowIndex":[component.get("v.rowIndex"),component.get("v.BatchList")]

How can i do that ?
 
<input type="text" id="getet"/>
var nameField =component.find("getet");
        var itemname = nameField.get("v.value");

        alert(itemname);

I want to pass HTML input data  to the lighting controller 
Controller :
 
public class quotewebservices {
   public static String language {get;set;}
   Public static  string  NicoPinFrance{get;set;}
   public static List<AccountDetails> AccountDetailsList {get;set;}      

@AuraEnabled
    public static List<AccountDetails> france(string NicoPinFrance){
   // public  static List<AccountDetails> InfoWithoutAccNum() {
        String XMLString;
        AccountDetailsList = new List<AccountDetails>();
       XMLString='<RESULT><PARTNUMBER>D221C04DXX-0005-3310</PARTNUMBER><DESCRIPTION>Boîtier série\'s 0F 12 pts</DESCRIPTION><DESCRIPTIONUK>housing serie\'s OF 12pts</DESCRIPTIONUK><STOCK>43382</STOCK><CLIENTPNS></CLIENTPNS></RESULT>';
                String PartNicomat='';
                String PartDescription= '';
                String PartDescriptionUK='';
                String PartStock='';
                String PartClientPNREF='';
        //Getting the values from xml String
      system.debug(XMLString);
      if(XMLString!=null){
          Dom.Document doc = new Dom.Document();
            doc.load(XMLString);
            dom.XmlNode node=doc.getRootElement();
            //Condition to check the responce without error 
            if(node.getChildElements()[0].getName() != 'ERROR'){
                PartNicomat=node.getChildElement('PARTNUMBER',null).getText();
                PartDescription=  node.getChildElement('DESCRIPTION',null).getText();
                PartDescriptionUK=node.getChildElement('DESCRIPTIONUK',null).getText();
                PartStock= node.getChildElement('STOCK',null).getText();
                //Iterating the child elements
                 for(dom.XmlNode child:node.getChildElements()){
                    if(child.getName() =='CLIENTPNS'){
                    //iterating the grand child elements
                        for(dom.XmlNode gchild:child.getChildElements()){
                            if(gchild .getName() == 'CLIENTPN'){
                                //Iterating the grand grand child elements
                                for(dom.XmlNode ggchild:gchild.getChildElements()){
                                    if(ggchild .getName() == 'CLIENTPNREF'){
                                        PartClientPNREF=ggchild.getText();
                                    }
                                }//End of for loop
                            }//End of if
                        }//End of for loop
                    }//End of if
                }//End of for loop
             }//End of if condition
          
              if(PartDescription!=null){
            if(PartDescription.contains('\'')){
               PartDescription=PartDescription.replace('\'','\\\'');
            }
        }
        if(PartDescriptionUK!=null){
            if(PartDescriptionUK.contains('\'')){
                PartDescriptionUK=PartDescriptionUK.replace('\'','\\\'');
            }
        } 
          system.debug(PartNicomat+PartDescription);
           					AccountDetails acc = new AccountDetails(); 
                            acc.PartNicomat= PartNicomat ;
                            acc.PartDescription = PartDescription;
                            acc.PartDescriptionUK=PartDescriptionUK;
                            acc.PartStock=PartStock;
                            acc.PartClientPNREF=PartClientPNREF;
          AccountDetailsList.add(acc);
         }//End of if    
        system.debug(AccountDetailsList);
      return AccountDetailsList ;   
    }//End of method
 public class AccountDetails{
@AuraEnabled  public String PartNicomat{get;set;}
@AuraEnabled  public String PartDescription{get;set;}
@AuraEnabled  public String PartDescriptionUK{get;set;}
@AuraEnabled  public String PartStock{get;set;}
@AuraEnabled  public String PartClientPNREF{get;set;} 
    }    
}
component :
<aura:component controller="quotewebservices">
    <aura:attribute name="AccountDetails" type="object"/>
    <aura:attribute name="firstName" type="String" default="D221C04DXX-0005-3310"/>
    <aura:attribute name="partnumber" type="string" default=""/>
    <aura:attribute name="PartDescription" type="string" default=""/>
    <aura:attribute name="PartStock" type="string" default=""/>
 <lightning:input label="firstName" name="Noofqli" value="{!v.firstName}" />
    <ui:inputtext value="{!v.partnumber}" label="Part number"/>
    <ui:inputtext value="{!v.PartDescription}" label="Part Description"/>
    <ui:inputtext value="{!v.PartStock}" label="PartStock"/>
    <ui:button label="Call server" press="{!c.echo}"/>
    
</aura:component>
JS
 
({
    "echo" : function(cmp) {
       var firstName = cmp.get("v.firstName");
        var action = cmp.get("c.france");    
         
        action.setParams({ NicoPinFrance : firstName });

         action.setCallback(this, function(response) {
            var state = response.getState();
             
            if ( state === "SUCCESS") {
                cmp.set('v.AccountDetails', response.getReturnValue());
                var acc= cmp.get("v.AccountDetails");
                alert(acc.PartNicomat);
               // alert("From server: " + response.getReturnValue());
               // component.set("v.partnumber", PartNicomat);
               // component.set("v.PartDescription",PartDescription);
              //  component.set("v.PartStock",PartStock)
            }
            else if (state === "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");
                }
            }
        });

        $A.enqueueAction(action);
    }
})

I want to set wrapper values to the UI: input how can  do it
component.set("v.partnumber", PartNicomat);
component.set("v.PartDescription",PartDescription);
component.set("v.PartStock",PartStock)

Thanks in advance
<aura:component controller="autoCompleteController">

    <!-- <ltng:require scripts="{!join(',',
    $Resource.jquery224 + '/jquery-2.2.4.min.js',
    $Resource.JqueryA + '/jquery-ui-1.8.16.custom.min.js')}" 
      afterScriptsLoaded="{!c.doInit}" /> -->            
 <ltng:require scripts='/resource/jquery224.js' afterScriptsLoaded="{!c.doInit}"/>                  


  <aura:attribute name="objectname" description="The object name you want to look for." type="String" required="true" />
  <aura:attribute name="additionalfield" description="Any additional fields you'd like to search and include in the display." type="String" required="false"/>
  <aura:attribute name="autocomplete_textbox" description="The ID for the Autocomplete List Textbox." type="String" required="true"/>
  
</aura:component>

controller JS:
 
({
	doInit : function(component, event, helper) {
        var j$ = jQuery.noConflict();
        j$(document).ready(function() {
        var sObjects;
        var queryTerm;
 
        j$(esc('{v.autocomplete_textbox}')).autocomplete({
        
            minLength: 4,
            source: function(request, response) {
                        queryTerm = request.term;
                        autoCompleteController.findSObjects("{v.objectname}", request.term, "{v.additionalfield}", function(result, event){
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 sObjects = result;
                                 response(sObjects);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    j$(esc('{v.autocomplete_textbox}')).val( ui.item.NicoPinFrace__c );
                    return false;
                    },
            select: function( event, ui ) {
                        j$(esc('{v.autocomplete_textbox}')).val( ui.item.NicoPinFrace__c );
                        j$(esc('{v.autocomplete_textbox}_lkid')).val( ui.item.Id );
                        j$(esc('{v.autocomplete_textbox}_lkold')).val( ui.item.NicoPinFrace__c );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.NicoPinFrace__c + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return j$( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
    });
 
    function esc(myid) {
           return '#' + myid.replace(/(:|\.)/g,'\\\\$1');
     }
    }
})
apex class :
 
global class autoCompleteController {
    
    @RemoteAction
    @auraenabled
    global static SObject[] findSObjects(string obj, string qry, string addFields) {
        // more than one field can be passed in the addFields parameter
        // split it into an array for later use
        List<String> fieldList;
        if (addFields != null) fieldList = addFields.split(',');
       // check to see if the object passed is valid
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sot = gd.get(obj);
        if (sot == null) {
            // Object name not valid
            return null;
        }
        // create the filter text
        String filter = ' like \'%' + String.escapeSingleQuotes(qry) + '%\'';
        //begin building the dynamic soql query
        String soql = 'select id , Name ';
        // if an additional field was passed in add it to the soql
        if (fieldList != null) {
            for (String s : fieldList) {
                soql += ', ' + s;
            }
        }
        // add the object and filter by name to the soql
        soql += ' from ' + obj + ' where NicoPinFrace__c' + filter;
        // add the filter by additional fields to the soql
        if (fieldList != null) {
            for (String s : fieldList) {
                soql += ' or ' + s + filter;
            }
        }
        soql += ' order by NicoPinFrace__c limit 20';
        List<sObject> L = new List<sObject>();
        try {
            L = Database.query(soql);
        }
        catch (QueryException e) {
            return null;
        }
        return L;
   }
}
compoenent 
 
<aura:component >
<ui:inputtext  aura:id="memNam">
        <c:autoComplete2 autocomplete_textbox="{!$Component.memNam}" additionalfield="NicoPinFrace__c" objectname="NicoPinCodeFrance__c" />
</ui:inputtext> 
</aura:component>

I am converting my old visualforce component to lightning component :

visualforce component 
 
<apex:component controller="autoCompleteController">
  <!-- JQuery Files -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"/>
<apex:stylesheet value="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/ui-smoothness/jquery-ui.css"/>
 <!-- Attributes Required For Component -->
  <apex:attribute name="objectname" description="The object name you want to look for."     type="String" required="true"/>
  <apex:attribute name="additionalfield" description="Any additional fields you'd like to search and include in the display."     type="String" required="false"/>
  <apex:attribute name="autocomplete_textbox" description="The ID for the Autocomplete List Textbox."     type="String" required="true"/>
  <style>
    .ui-autocomplete-loading { background: white url({!$Resource.circleIndicator}) right center no-repeat; }
  </style>
  <script type="text/javascript">
    var j$ = jQuery.noConflict();
    j$(document).ready(function() {
 
        var sObjects;
        var queryTerm;
 
        j$(esc('{!autocomplete_textbox}')).autocomplete({
            minLength: 4,
            source: function(request, response) {
                        queryTerm = request.term;
                        autoCompleteController.findSObjects("{!objectname}", request.term, "{!additionalfield}", function(result, event){
                            if(event.type == 'exception') {
                                  alert(event.message);
                            } else {
                                 sObjects = result;
                                 response(sObjects);
                            }
                        });
                   },
            focus: function( event, ui ) {
                    j$(esc('{!autocomplete_textbox}')).val( ui.item.NicoPinFrace__c );
                    return false;
                    },
            select: function( event, ui ) {
                        j$(esc('{!autocomplete_textbox}')).val( ui.item.NicoPinFrace__c );
                        j$(esc('{!autocomplete_textbox}_lkid')).val( ui.item.Id );
                        j$(esc('{!autocomplete_textbox}_lkold')).val( ui.item.NicoPinFrace__c );
                        return false;
                    },
         })
         .data( "autocomplete" )._renderItem = function( ul, item ) {
            var entry = "<a>" + item.NicoPinFrace__c + "</a>";
            entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");
            return j$( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( entry )
                .appendTo( ul );
        };
    });
 
    function esc(myid) {
           return '#' + myid.replace(/(:|\.)/g,'\\\\$1');
    }
 
  </script>
</apex:component>

Could someone help on this?

Thanks in advance  


 

I want to insert Multiple parent and child (Account and contacts) in Salesforce lightning. One parent and child set, multiple children if required.User-added image
Parent component :
 
<!--Parent-->
<aura:component controller="AuraSampleController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
    <!--Init handler which is call doInit js function on component Load--> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <!--Event handler for Add and Delete Row Event which is execute from Child Component-->   
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.addRow}"/>

    <!--Aura Attribute for store Account Object List as Array-->   
    <aura:attribute name="AccountList" type="Account[]"/> 

    <!--Header Part-->       
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Accounts and contacts in Lightning</h1>
    </div>

    <!--Table Part-->          
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Name">Account Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Number">Account Number</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>           
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.AccountList}" var="item" indexVar="index">
                <c:Child AccountInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <!--Save Button which is call Save js function on click -->
    <button class="slds-button slds-button_brand"  onclick="{!c.Save}">Save</button>
</aura:component>

parent controller :
({  
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Account Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },

    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "Account Name" will not be blank on each row.
        if (helper.validate(component, event)) {
            // call the apex class method for save the Account List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.SaveAccounts");
            action.setParams({
                "accList": component.get("v.AccountList")
            });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset the 'AccountList' Attribute 
                    // and call the common helper method for create a default Object Data to Account List 
                    component.set("v.AccountList", []);
                    helper.createObjectData(component, event);
                    alert('Account records saved successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },

    // function for create new object Row in Contact List 
    addRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },

    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.AccountList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.AccountList", AllRowsList);
    },
})

Parent Helper :
 
({
    createObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var RowItemList1 = component.get("v.AccountList");
        RowItemList1.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.AccountList", RowItemList1);
    },
    //helper function for check if Account Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allAccountRows = component.get("v.AccountList");
        for (var indexVar = 0; indexVar < allAccountRows.length; indexVar++) {
            if (allAccountRows[indexVar].Name == '') {
                isValid = false;
                alert('Account Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Child Component :
 
<!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
<aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
<aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 

<!-- Table Row -->  
<tr class="slds-text-title_caps">
    <td> 
        {!v.rowIndex + 1}
    </td>
    <td>
        <ui:inputText class="slds-input" value="{!v.AccountInstance.Name}"/>
    </td>
    <td>
        <ui:inputText class="slds-input" value="{!v.AccountInstance.AccountNumber}"/>
    </td>
    <td>
        <ui:inputPhone class="slds-input" value="{!v.AccountInstance.Phone}"/>
    </td>
    <td>
        <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
        <aura:if isTrue="{!v.rowIndex == 0}">
            <a onclick="{!c.addRow}">
                <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                <span class="slds-assistive-text">Add</span>
            </a>    
            <aura:set attribute="else">
                <a onclick="{!c.deleteRow}">
                    <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                    <span class="slds-assistive-text">Delete</span>
                </a>
            </aura:set> 
        </aura:if>
    </td>
</tr>
    <br/>




    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
    <thead>
        <tr class="slds-text-title_caps">
             <th scope="col">
                <div class="slds-truncate" title="No">S.NO</div>
            </th>
             <th scope="col">
                <div class="slds-truncate" title="First Name">Contact Name</div>
            </th>
               <th scope="col">
                <div class="slds-truncate" title="Action">Action</div>
            </th>
            </tr>         
    </thead>   
    <tbody>
        <!--Iterate the child Component for display Table rows 
           with pass the List Item Index for track the Every child Component 
           and pass each List Account Instance -->        
        <aura:iteration items="{!v.ContactList}" var="item" indexVar="index">
            <c:Contact ContactInstance="{!item}"  rowIndex="{!index}"/>
        </aura:iteration>    
    </tbody>
</table>

child js :
 
({
        // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [contact Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData1(component, event);
    },

    addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },

    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    },

      // function for create new object Row in Contact List 
    addingRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData1(component, event);
    },

    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (ContactList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.ContactList");
        AllRowsList.splice(index, 1);
        //set the ContactList after remove selected row element  
        component.set("v.ContactList", AllRowsList);
    }
})

child helper :
 
({
    createObjectData1: function(component, event) {
        //get the ContactList from component and add(push) New Object to List  
        var RowItemList = component.get("v.ContactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': ''
        });
        // set the updated list to attribute (ContactList) again    
        component.set("v.ContactList", RowItemList);
    },
    //helper function for check if Contact Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.ContactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].FirstName == '') {
                isValid = false;
                alert('Contact Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Contact Component :
 
<!--Child-->
<aura:component >    
    <!--Attribute for store single Contact object instance-->
    <aura:attribute name="ContactInstance" type="Contact"/>
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="rowIndex" type="String"/>

    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 

    <!-- Table Row -->  
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
            <aura:if isTrue="{!v.rowIndex == 0}">
                <a onclick="{!c.addRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                <aura:set attribute="else">
                    <a onclick="{!c.deleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
                </aura:set> 
            </aura:if>
        </td> 
    </tr>

</aura:component>

Contact Controller :
 
({
addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },

    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    }

 })

When I click on iteration add button.The iteration is happening for parent and child.By using this code you can see two add button in both parent and child . when i clik on child add.It is adding parent as well.I want to add child when i click on child button.I want to parent and child set when i click on parent button.
 
I want to insert Multiple parent and child (Account and contacts)  in Salesforce lightning.
One parent and child set, multiple children if required.
Child component - account Iteration
 
<!--Child-->
<aura:component >    
    <!--Attribute for store single Account object instance-->
    <aura:attribute name="AccountInstance" type="Account"/>
        
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="rowIndex" type="String"/>
     
    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 
     
    <!-- Table Row -->  
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.AccountInstance.Name}"/>
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.AccountInstance.AccountNumber}"/>
        </td>
        <td>
            <ui:inputPhone class="slds-input" value="{!v.AccountInstance.Phone}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
                <a onclick="{!c.addRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                    <a onclick="{!c.deleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
        </td> 
    </tr>
</aura:component>
Childcontroller :
 
({
    addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },
     
    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    }
})
child component 2 - contact iteration:
 
<aura:component >    
    <!--Attribute for store single Account object instance-->
    <aura:attribute name="ContactInstance" type="Contact"/>
        
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="BrowIndex" type="String"/>
     
    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 
     
    <!-- Table Row -->  
        <tr class="slds-text-title_caps">
        <td> 
            {!v.BrowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.LastName}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
                <a onclick="{!c.BaddRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                    <a onclick="{!c.BdeleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
        </td> 
    </tr>
</aura:component>

comtroller:
 
({
        BaddRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },
     
    BdeleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.BrowIndex") }).fire();
    }
})

Parent component :
<!--Parent-->
<aura:component controller="addDeleteController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
    <!--Init handler which is call doInit js function on component Load--> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
     
    <!--Event handler for Add and Delete Row Event which is execute from Child Component-->   
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.addRow}"/>
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.BremoveDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.BaddRow}"/>
     
    <!--Aura Attribute for store Account Object List as Array-->   
    <aura:attribute name="AccountList" type="Account[]"/> 
    <aura:attribute name="ContactList" type="contact[]"/> 
     
    <!--Header Part-->       
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Accounts in Lightning</h1>
    </div>
     
    <!--Table Part-->          
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Name">Account Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Number">Account Number</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.AccountList}" var="item" indexVar="index">
                <c:childcomponent AccountInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <table>
            <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Contact First Name">Contact First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Contact Last Name">Contact Last Name</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.ContactList}" var="item" indexVar="index">
                   <c:childcomponent2 ContactInstance="{!item}" BrowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <!--Save Button which is call Save js function on click -->
    <button class="slds-button slds-button_brand"  onclick="{!c.Save}">Save</button>
</aura:component>

parent controller :
 
({
     
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Account Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },
     
    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "Account Name" will not be blank on each row.
        if (helper.validate(component, event)) {
            // call the apex class method for save the Account List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.SaveAccounts");
            action.setParams( {"accList": component.get("v.AccountList") });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset the 'AccountList' Attribute 
                    // and call the common helper method for create a default Object Data to Account List 
                    component.set("v.AccountList", []);
                    helper.createObjectData(component, event);
                    alert('Account records saved successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },
     
    // function for create new object Row in Contact List 
    addRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },
    BaddRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.BcreateObjectData(component, event);
    },
     
    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.AccountList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.AccountList", AllRowsList);
    },
        BremoveDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.ContactList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.ContactList", AllRowsList);
    },
})

parent helper :
 
({
    createObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var RowItemList = component.get("v.AccountList");
        RowItemList.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        var BRowItemList = component.get("v.ContactList");
        BRowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.AccountList", RowItemList);
        component.set("v.ContactList", BRowItemList);
    },
        BcreateObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var BRowItemList = component.get("v.ContactList");
        BRowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.ContactList", BRowItemList);
    },
    //helper function for check if Account Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allAccountRows = component.get("v.AccountList");
        for (var indexVar = 0; indexVar < allAccountRows.length; indexVar++) {
            if (allAccountRows[indexVar].Name == '') {
                isValid = false;
                alert('Account Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})
One parent and child sets,multiple childs optional
 






 
We have a custom object Quote in that there is a lightning button called "Quote preview LE".where when we click on quote preview button it will open PDF. It is perfectly working on salesforce classic and lightning desktop and it is not working on the salesforce1 mobile app.

Generally, Lightning components should work on salesforce1app.I dont this is strange

This is our ID : 00D90000000bovq
Grant login access on your Org : yes


Component :
<aura:component implements="force:lightningQuickAction,force:hasRecordId" controller="Quote_Preview_LE">
    <style>
      .forceChatterLightComponent .bodyWrapper{height:0%;width:0%;padding:0;box-sizing:border-box}
      .slds-modal__close{height:0%;width:0;padding:0;display:none;}
     </style>
     <aura:attribute name="ProfileId" type="String"/>
     <aura:handler name="init" action="{!c.CheckPreview}" value="{!this}" />
    <aura:attribute name="quo" type="Quote__c" default="{'sobjectType': 'Quote__c'}" />
</aura:component>
controller :
({
    CheckPreview : function(component, event, helper){
            var qid=component.get("v.recordId");   
            //alert(qid);
            var action = component.get("c.getquoteid");
            action.setParams({ "recordId" : qid });          
            action.setCallback(this, function(a) {
            parent.location.href =parent.location.href; 
            window.open("/apex/QuotePreview?id="+qid,"_blank");    
        });
        $A.get("e.force:closeQuickAction").fire()
            $A.enqueueAction(action);
    }
})
quote preview  is a pdf page. It is opening in classic and lightning desktop.

I tried with the formulae field which is not working as well with a hyperlink URL

 
salesforce classic onclick javascript button code :
 
{!REQUIRESCRIPT("/soap/ajax/34.0/connection.js")} {!REQUIRESCRIPT("/soap/ajax/34.0/apex.js")} 
var connection = sforce.connection; 
var qid="{!Quote__c.Id}"; 
var isedit="{!Quote__c.isEdited__c}"; 
var isPreviewed="{!Quote__c.isPreviewd__c}"; 
var isGenerated="{!Quote__c.Generated__c}"; 
var pot="{!Quote__c.potential__c}"; 
var x=pot.replace(/\,/g,''); 

var quot= new sforce.SObject("Quote__c"); 
quot.id=qid; 
if(isGenerated==true && isPreviewed==false){ 
alert('Please preview the quote then generate '); 
} 
else if(isedit==true && isPreviewed==false){ 
alert('Please preview the quote then generate '); 
}else{ 
parent.location.href = parent.location.href; 
window.open("/apex/QuotePDF?id={!Quote__c.Id}","_blank"); 
if(x>50000){ 
if (('{!$User.ProfileId}'=='00e90000000emPJ') || ('{!$User.ProfileId}'=='00e90000001k992' )){ 
alert('Please print the quote for manager signature'); 
}} 
}
visual page button code :
 
<apex:page standardController="Quote__c">
 <apex:includeScript value="../../soap/ajax/34.0/connection.js"/>
  <apex:includeScript value="../../soap/ajax/34.0/apex.js"/>
<script>
sforce.connection.sessionId='{!GETSESSIONID()}';

var qid="{!Quote__c.Id}"; 
var isedit="{!Quote__c.isEdited__c}"; 
var isPreviewed="{!Quote__c.isPreviewd__c}"; 
var isGenerated="{!Quote__c.Generated__c}"; 
var pot="{!Quote__c.potential__c}"; 
var x=pot.replace(/\,/g,''); 

var quot= new sforce.SObject("Quote__c"); 
quot.id=qid; 
if(isGenerated==true && isPreviewed==false){ 
alert('Please preview the quote then generate '); 
} 
else if(isedit==true && isPreviewed==false){ 
alert('Please preview the quote then generate '); 
}else{ 
parent.location.href = parent.location.href; 
window.open("/apex/QuotePDF?id={!Quote__c.Id}","_blank"); 
if(x>50000){ 
if (('{!$User.ProfileId}'=='00e90000000emPJ') || ('{!$User.ProfileId}'=='00e90000001k992' )){ 
alert('Please print the quote for manager signature'); 
}} 
}
</script>
</apex:page>

I can able to show this button in lightening in salesforce .
But I cant see any alert messages ,when i click on the button .it is blank pop up opening.

 
As of i am using auto number field to generate new number .But when some validation rule error or flow error occur .The number skips some numbers in the middle. 

Suppose in my number auto number says : 205 

On the next insert record if validation rule or flow error occur .It will be changing auto 205 to 208.
se
I dont know why it is not generating in good way,Only record inserts it should generate number and why it skips number due to errors.
 
trigger feeditemnofication on FeedItem (after update,after insert) {
   for (feeditem F : Trigger.new)
    {       
        if(Trigger.isInsert)
        {

                feeditem EE = [Select body,parentid from feeditem where Id = :F.Id];  
                opportunity op=[select id,ownerid from opportunity where id=:EE.parentid] ;
                User U= [select id,Email,Name from user where id =:op.ownerid ];
                 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                String[] toAddresses = new String[] {U.email};                  
                mail.setToAddresses(toAddresses);                  
                mail.setSubject('Record Feed Notification to record  owner' );                
                mail.setPlainTextBody('Hello,' + '\n\n' +'Please consider the following feed'+' '+'\n\n'+'Subject :'+F.body );
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }

       }
}

In this parentid will of any thing like accound id ,opportunity id,quote id,userid--- i need to send email to the record owner when feed is posted .how i can write the code as global way (or) we need to write it seperately (if account id,if oppid,if quoteid).it woud be great it would have some sample code.
Error while deploying
Trigger while deploying i am getting the error :

trigger orderreceived on Quote__c (after update,after insert) {
Profile pr = [select id from Profile where name='USA User'];
list<task> ta=new list<task>();
Set<id> QuoteId = new Set<id>();
    for(Quote__c q:Trigger.new){
    if(UserInfo.getProfileId()==pr.id){
     if (q.Order_Received__c!= Null && q.Order_Received__c == true )
        QuoteId.add(q.Id);
    }
    }
list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (Integer i = 0; i < tasklist.size(); i++) {
tasklist[i].status='completed';
}
update tasklist;
}


i had used many ways like

way 1:

list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (task t: tasklist){
t.status='completed';
tasklist.add(t);
}
update tasklist;
}

way2:
list<task> ta=new list<task>();
list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (task t: tasklist){
t.status='completed';
ta.add(t);
}
update ta;
}

I am getting error as while deploying as s

TestQuotelineitem_France_Edit.testMethod1() Class 413  Failure Message: "System.LimitException: Too many SOQL queries: 101", Failure Stack Trace: "Class.Quotelineitem_France_Edit.InfoWithoutAccNum: line 413, column 1 Class.Quotelineitem_France_Edit.france: line 390, column 1 Class.TestQuotelineitem_France_Edit.testMethod1: line 77, column 1"
TestQuotelineitem_IBC.testMethod1() Class 6  Failure Message: "System.LimitException: Too many SOQL queries: 101", Failure Stack Trace: "Class.asyncApex.processAccounts: line 6, column 1 Trigger.quotepotential: line 12, column 1"
Trigger while deploying i am getting the error :

trigger orderreceived on Quote__c (after update,after insert) {
Profile pr = [select id from Profile where name='USA User'];
list<task> ta=new list<task>();
Set<id> QuoteId = new Set<id>();
    for(Quote__c q:Trigger.new){
    if(UserInfo.getProfileId()==pr.id){
     if (q.Order_Received__c!= Null && q.Order_Received__c == true )
        QuoteId.add(q.Id);
    }
    }
list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (Integer i = 0; i < tasklist.size(); i++) {
tasklist[i].status='completed';
}
update tasklist;
}


i had used many ways like

way 1:

list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (task t: tasklist){
t.status='completed';
tasklist.add(t);
}
update tasklist;
}

way2:
list<task> ta=new list<task>();
list<task> tasklist=[SELECT Id,whatId,whoid FROM Task where whatid=:Quoteid ];
for (task t: tasklist){
t.status='completed';
ta.add(t);
}
update ta;
}
My requirement is to create a dashboard bar graph X-axis as createddate(MONTHLY) and the y-AXIS (RECORD COUNT)

In the first image i had Groupby N EP/DPI: and write formula as ROWCOUNT/ROWCOUNTUser-added image



IN the second Image i had kept the GROUP BY CREATEDDATE/MONTH ?

How can can i write the formula so that i can get the formula as get count 2

not as 3 .how many N EPDPI as there that i need the that count

DASHBOARD: DEC-2013(2 records) x y axis

This is my criteria Hope.it is so confusing Reply me if you don't understandUser-added image
i want to resize the pageblocktable 

here is the demo table what i need 

http://www.ita.es/jquery/jquery.kiketable.colsizable.htm

i can able to stretch the rows how can i do it 

this is my visulforce code :

<apex:pageBlockTable value="{!quo}" var="q"   width="10000px">      
<apex:column value="{!q.Quote_Line_Item__r.Quote1__r.Quote_Number_New__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.From1__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.Name}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.Quote_Validity__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.RFQ_Date__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.createdDate__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.Account_Code__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Quote1__r.Account_Name__c}" width="300"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Name}"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Client_P_N__c}"/>
                 <apex:column value="{!q.Quote_Line_Item__r.N_EP_DPI__c}"/>
                 <apex:column value="{!q.Quote_Line_Item__r.Description__c}"/>
                 <apex:column value="{!q.Asked_Qty__c}"/>
                 <apex:column value="{!q.MOD_Maxi__c}"/>
                 <apex:column value="{!q.batch_value__c}"/>
                 <apex:column value="{!q.Unit_Price__c}"/>
                 <apex:column value="{!q.Max_Quantity__c}"/>
                 <apex:column >
                 <apex:commandbutton value="Create PDF" onclick="return window.open('/apex/QuotePDF?id={!q.Quote_Line_Item__r.Quote1__c}')" />
                 </apex:column>
                 <apex:column >
                 <apex:commandbutton value="open Quote" onclick="return window.open('https://cs6.salesforce.com/{!q.Quote_Line_Item__r.Quote1__c}')" />
                 </apex:column>
        </apex:pageBlockTable>
i have same requirement what your are discussing about

<apex:commandButton value="Search Again" onclick="return window.open('/apex/customreport');window.top.close();" />

it is opening one new window and the old window is also there .

when the button is clicked it has to close the current window and apen the new window which i wrote above .answer would be great helpful
@AuraEnabled
    public static list<batch__c> SaveBatchDet(integer QliRowNum,list<Batch__c> Bt,map<integer,list<batch__c>> Rowmap,string QuoteID){
          system.debug(QliRowNum+'-------------'+Bt+'@@@@@@@@@@@@@@@@'+Rowmap+'###################'+QuoteID); 
         System.debug('1.Number of Queries used in this apex code so far: ' + Limits.getQueries());
         System.debug('2.Number of rows queried in this apex code so far: ' + Limits.getDmlRows());
        //transient List<Integer> sortkey=new List<Integer>();
         Map<Integer,list<batch__c>> batchMap =  New Map<Integer,list<batch__c>>();
            batchMap.put(Integer.valueOf(QliRowNum),Bt);
         transient List<Batch__c> batchListToInsert =new List<Batch__c>();
        
         Map<integer,quote_line_item__c> qouteLineItemMap = new Map<integer,quote_line_item__c>();
		for(quote_line_item__c t: [SELECT QliRowNum__c, Id FROM quote_line_item__c WHERE quote1__c=:QuoteID])
         qouteLineItemMap.put(Integer.valueOf(t.QliRowNum__c), t);
        
        transient List<Integer> sortkey=new List<Integer>();
        sortkey.addAll(qouteLineItemMap.keySet());
      for(integer qli:sortkey){
          if(batchMap.get(qli)!=null)
            for(Batch__c bat: batchMap.get(qli)){
                if(bat.Asked_Qty__c!=null && bat.Asked_Qty__c!=''){
                bat.Quote_Line_Item__c=qouteLineItemMap.get(qli).id;
                }
                if(bat.Quote_Line_Item__c!=null)
                batchListToInsert.add(bat);
               // system.debug(batchListToInsert);
            }//End of for 
        }// End of for
        // Inserting the list of batches
        try{
        
          upsert batchListToInsert ;
           System.debug('1.Number of Queries used in this apex code so far: ' + Limits.getQueries());
         System.debug('2.Number of rows queried in this apex code so far: ' + Limits.getDmlRows());
            //system.debug(batchListToInsert);
        }catch(DmlException de){
            return null;
        }
        return null;
    }

i am getting error in this query 
 
for(quote_line_item__c t: [SELECT QliRowNum__c, Id FROM quote_line_item__c WHERE quote1__c=:QuoteID])
is there is any workaround to solve this issue?

Could some help me is there is any wrong in my code?

 

I want to insert Multiple parent and child (Account and contacts) in Salesforce lightning. One parent and child set, multiple children if required.User-added image
Parent component :
 
<!--Parent-->
<aura:component controller="AuraSampleController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
    <!--Init handler which is call doInit js function on component Load--> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <!--Event handler for Add and Delete Row Event which is execute from Child Component-->   
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.addRow}"/>

    <!--Aura Attribute for store Account Object List as Array-->   
    <aura:attribute name="AccountList" type="Account[]"/> 

    <!--Header Part-->       
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Accounts and contacts in Lightning</h1>
    </div>

    <!--Table Part-->          
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Name">Account Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Number">Account Number</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>           
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.AccountList}" var="item" indexVar="index">
                <c:Child AccountInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <!--Save Button which is call Save js function on click -->
    <button class="slds-button slds-button_brand"  onclick="{!c.Save}">Save</button>
</aura:component>

parent controller :
({  
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Account Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },

    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "Account Name" will not be blank on each row.
        if (helper.validate(component, event)) {
            // call the apex class method for save the Account List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.SaveAccounts");
            action.setParams({
                "accList": component.get("v.AccountList")
            });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset the 'AccountList' Attribute 
                    // and call the common helper method for create a default Object Data to Account List 
                    component.set("v.AccountList", []);
                    helper.createObjectData(component, event);
                    alert('Account records saved successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },

    // function for create new object Row in Contact List 
    addRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },

    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.AccountList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.AccountList", AllRowsList);
    },
})

Parent Helper :
 
({
    createObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var RowItemList1 = component.get("v.AccountList");
        RowItemList1.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.AccountList", RowItemList1);
    },
    //helper function for check if Account Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allAccountRows = component.get("v.AccountList");
        for (var indexVar = 0; indexVar < allAccountRows.length; indexVar++) {
            if (allAccountRows[indexVar].Name == '') {
                isValid = false;
                alert('Account Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Child Component :
 
<!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
<aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
<aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 

<!-- Table Row -->  
<tr class="slds-text-title_caps">
    <td> 
        {!v.rowIndex + 1}
    </td>
    <td>
        <ui:inputText class="slds-input" value="{!v.AccountInstance.Name}"/>
    </td>
    <td>
        <ui:inputText class="slds-input" value="{!v.AccountInstance.AccountNumber}"/>
    </td>
    <td>
        <ui:inputPhone class="slds-input" value="{!v.AccountInstance.Phone}"/>
    </td>
    <td>
        <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
        <aura:if isTrue="{!v.rowIndex == 0}">
            <a onclick="{!c.addRow}">
                <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                <span class="slds-assistive-text">Add</span>
            </a>    
            <aura:set attribute="else">
                <a onclick="{!c.deleteRow}">
                    <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                    <span class="slds-assistive-text">Delete</span>
                </a>
            </aura:set> 
        </aura:if>
    </td>
</tr>
    <br/>




    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
    <thead>
        <tr class="slds-text-title_caps">
             <th scope="col">
                <div class="slds-truncate" title="No">S.NO</div>
            </th>
             <th scope="col">
                <div class="slds-truncate" title="First Name">Contact Name</div>
            </th>
               <th scope="col">
                <div class="slds-truncate" title="Action">Action</div>
            </th>
            </tr>         
    </thead>   
    <tbody>
        <!--Iterate the child Component for display Table rows 
           with pass the List Item Index for track the Every child Component 
           and pass each List Account Instance -->        
        <aura:iteration items="{!v.ContactList}" var="item" indexVar="index">
            <c:Contact ContactInstance="{!item}"  rowIndex="{!index}"/>
        </aura:iteration>    
    </tbody>
</table>

child js :
 
({
        // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [contact Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData1(component, event);
    },

    addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },

    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    },

      // function for create new object Row in Contact List 
    addingRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData1(component, event);
    },

    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (ContactList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.ContactList");
        AllRowsList.splice(index, 1);
        //set the ContactList after remove selected row element  
        component.set("v.ContactList", AllRowsList);
    }
})

child helper :
 
({
    createObjectData1: function(component, event) {
        //get the ContactList from component and add(push) New Object to List  
        var RowItemList = component.get("v.ContactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': ''
        });
        // set the updated list to attribute (ContactList) again    
        component.set("v.ContactList", RowItemList);
    },
    //helper function for check if Contact Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.ContactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].FirstName == '') {
                isValid = false;
                alert('Contact Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Contact Component :
 
<!--Child-->
<aura:component >    
    <!--Attribute for store single Contact object instance-->
    <aura:attribute name="ContactInstance" type="Contact"/>
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="rowIndex" type="String"/>

    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 

    <!-- Table Row -->  
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
            <aura:if isTrue="{!v.rowIndex == 0}">
                <a onclick="{!c.addRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                <aura:set attribute="else">
                    <a onclick="{!c.deleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
                </aura:set> 
            </aura:if>
        </td> 
    </tr>

</aura:component>

Contact Controller :
 
({
addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },

    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    }

 })

When I click on iteration add button.The iteration is happening for parent and child.By using this code you can see two add button in both parent and child . when i clik on child add.It is adding parent as well.I want to add child when i click on child button.I want to parent and child set when i click on parent button.
 
I want to insert Multiple parent and child (Account and contacts)  in Salesforce lightning.
One parent and child set, multiple children if required.
Child component - account Iteration
 
<!--Child-->
<aura:component >    
    <!--Attribute for store single Account object instance-->
    <aura:attribute name="AccountInstance" type="Account"/>
        
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="rowIndex" type="String"/>
     
    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 
     
    <!-- Table Row -->  
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.AccountInstance.Name}"/>
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.AccountInstance.AccountNumber}"/>
        </td>
        <td>
            <ui:inputPhone class="slds-input" value="{!v.AccountInstance.Phone}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
                <a onclick="{!c.addRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                    <a onclick="{!c.deleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
        </td> 
    </tr>
</aura:component>
Childcontroller :
 
({
    addRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },
     
    deleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    }
})
child component 2 - contact iteration:
 
<aura:component >    
    <!--Attribute for store single Account object instance-->
    <aura:attribute name="ContactInstance" type="Contact"/>
        
    <!--Attribute for store Index of Particular Instance -->
    <aura:attribute name="BrowIndex" type="String"/>
     
    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  -->
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddRowEvent" type="c:AddRowEvent"/> 
     
    <!-- Table Row -->  
        <tr class="slds-text-title_caps">
        <td> 
            {!v.BrowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.LastName}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons, if rowIndex is 0 then show add row Icon else show delete Icon-->
                <a onclick="{!c.BaddRow}">
                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="Add"/>
                    <span class="slds-assistive-text">Add</span>
                </a>    
                    <a onclick="{!c.BdeleteRow}">
                        <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="Delete"/>
                        <span class="slds-assistive-text">Delete</span>
                    </a>
        </td> 
    </tr>
</aura:component>

comtroller:
 
({
        BaddRow : function(component, event, helper){
        //Execute the AddRowEvent Lightning Event 
        component.getEvent("AddRowEvent").fire();     
    },
     
    BdeleteRow : function(component, event, helper){
        //Execute the DeleteRowEvent Lightning Event and pass the deleted Row Index to Event attribute
        component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.BrowIndex") }).fire();
    }
})

Parent component :
<!--Parent-->
<aura:component controller="addDeleteController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
    <!--Init handler which is call doInit js function on component Load--> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
     
    <!--Event handler for Add and Delete Row Event which is execute from Child Component-->   
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.addRow}"/>
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.BremoveDeletedRow}"/>
    <aura:handler name="AddRowEvent" event="c:AddRowEvent" action="{!c.BaddRow}"/>
     
    <!--Aura Attribute for store Account Object List as Array-->   
    <aura:attribute name="AccountList" type="Account[]"/> 
    <aura:attribute name="ContactList" type="contact[]"/> 
     
    <!--Header Part-->       
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Accounts in Lightning</h1>
    </div>
     
    <!--Table Part-->          
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Name">Account Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Account Number">Account Number</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.AccountList}" var="item" indexVar="index">
                <c:childcomponent AccountInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <table>
            <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">#</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Contact First Name">Contact First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Contact Last Name">Contact Last Name</div>
                </th>
                 <th scope="col">
                    <div class="slds-truncate" title="Action">Action</div>
                </th>
            </tr>
        </thead>   
        <tbody>
            <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Account Instance -->        
            <aura:iteration items="{!v.ContactList}" var="item" indexVar="index">
                   <c:childcomponent2 ContactInstance="{!item}" BrowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <!--Save Button which is call Save js function on click -->
    <button class="slds-button slds-button_brand"  onclick="{!c.Save}">Save</button>
</aura:component>

parent controller :
 
({
     
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Account Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },
     
    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "Account Name" will not be blank on each row.
        if (helper.validate(component, event)) {
            // call the apex class method for save the Account List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.SaveAccounts");
            action.setParams( {"accList": component.get("v.AccountList") });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset the 'AccountList' Attribute 
                    // and call the common helper method for create a default Object Data to Account List 
                    component.set("v.AccountList", []);
                    helper.createObjectData(component, event);
                    alert('Account records saved successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },
     
    // function for create new object Row in Contact List 
    addRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },
    BaddRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.BcreateObjectData(component, event);
    },
     
    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.AccountList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.AccountList", AllRowsList);
    },
        BremoveDeletedRow: function(component, event, helper) {
        //get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        //get the all List (AccountList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.ContactList");
        AllRowsList.splice(index, 1);
        //set the AccountList after remove selected row element  
        component.set("v.ContactList", AllRowsList);
    },
})

parent helper :
 
({
    createObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var RowItemList = component.get("v.AccountList");
        RowItemList.push({
            'sobjectType': 'Account',
            'Name': '',
            'AccountNumber': '',
            'Phone': ''
        });
        var BRowItemList = component.get("v.ContactList");
        BRowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.AccountList", RowItemList);
        component.set("v.ContactList", BRowItemList);
    },
        BcreateObjectData: function(component, event) {
        //get the AccountList from component and add(push) New Object to List  
        var BRowItemList = component.get("v.ContactList");
        BRowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': ''
        });
        // set the updated list to attribute (AccountList) again    
        component.set("v.ContactList", BRowItemList);
    },
    //helper function for check if Account Name is not null/blank on save  
    validate: function(component, event) {
        var isValid = true;
        var allAccountRows = component.get("v.AccountList");
        for (var indexVar = 0; indexVar < allAccountRows.length; indexVar++) {
            if (allAccountRows[indexVar].Name == '') {
                isValid = false;
                alert('Account Name Cannot be blank on row number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})
One parent and child sets,multiple childs optional
 






 
trigger ba on Task (after update, after insert) {
    
    GetMaxActivityDate ad= new GetMaxActivityDate();
    
    
    
    Set<ID> ids = Trigger.newMap.keySet();
    
    List<Task> tk = [select id, whoId,OwnerId from Task where id = :ids limit 1000];
    System.debug('b tasks:'+ tk+ ' size:'+tk.size());
    List<ID> idzz = new List<ID>{};
        
        for(Task a: tk)
    {
        idzz.add(a.whoId);
    }
        
    
    List<Lead> ldz = [select name,id, Sales_Last_Activity_Date__c, Sales_First_Activity_Date__c, OwnerId, IsConverted from Lead where id = :idzz limit 1000];
    
    System.debug('b ids:'+ idzz+'. leads:' + ldz + ' size:' + ldz.size());
    
    List<Lead> updateld = new List<Lead>{};
    
    
    for(Lead a : ldz)
    {
        
        
    
    
    
    
    
                    String ldd = a.id;
        
        if(ldd!=null)
        {
           
        String lds = ldd.subString(0,3);
        
        System.debug('lds: '+ lds);
        
        if(lds.equals('00Q'))
        {
            
             List<aggregateResult> dates = new List <aggregateResult>();
        

        
        
        
       // Lead ld = [select name,id, Sales_Last_Activity_Date__c, Sales_First_Activity_Date__c, IsConverted from Lead where id = :a.WhoId limit 1];
        
        
        
        if(a!=null)
        {
            System.debug('b ' + lds);
            
			Set<ID> taskset = new Set<ID>();
			List<ID>result = new List<ID>();            
            taskset.addAll(idzz);
            result.addAll(taskset);
            System.debug('taskset:'+ taskset.size()+' result:'+result.size());
            
            
            for(ID b:result)
            {
            
            if(b == a.Id)
                {
                     dates = ad.getMaxActivity(b);
                    System.debug('b triggered:  max:'+ (Date)dates[0].get('myMax') + ' min: '+ (Date)dates[0].get('myMin') + 'last activity date:'+ a.Sales_Last_Activity_Date__c + ' first activity date ' +  a.Sales_First_Activity_Date__c+  ' isconverted:'+ a.IsConverted );
                        System.debug('b triggered: lead:'+ a);
                    if(a.IsConverted == false && (dates[0].get('myMax')!=null) && dates[0].get('myMin')!=null && (a.Sales_Last_Activity_Date__c != (Date)dates[0].get('myMax')||a.Sales_First_Activity_Date__c != (Date)dates[0].get('myMin')))
                    {
                        System.debug('Activity_date updated');
                        
                        a.Sales_Last_Activity_Date__c = (Date)dates[0].get('myMax');
                        a.Sales_First_Activity_Date__c = (Date)dates[0].get('myMin');
                        
                        updateld.add(a);
                    }
                    
                    
                }
                
            }
            
        }
        }

        }
    }
    
    update updateld;
    
    
    
    
    
    for(Task a: Trigger.New)
    {

      
        
        
        
    }

}

  public  List<aggregateResult> getMaxActivity(ID who)
    {
        List<aggregateResult> maxDates = [Select Max(Sales_Activity_Date__c) myMax, Min(Sales_Activity_Date__c) myMin from Task 
         where whoid = :who and status = 'Completed'];
            System.debug('Max is:  ' + maxDates[0].get('myMax') + 'min '+maxDates[0].get('myMin'));  
     
        return maxDates;
    }
I was getting this governor limit error in the past, and I rewrote most of the trigger to hopefully fix that, yet I still occasionally see this error. And from personally inserting a bunch of data, i can't seem to reproduce so its having a hard time debug. 

I'm thinking its due to getMaxActivity though because techinically its a select in a for loop? I'm not sure how else logically I can address this though.

thanks!
 
visuaforce page:
<apex:page sidebar="false" controller="UploadOpportunityScheduleLineItem123">
    <apex:form >
        <apex:sectionHeader title="Upload data from CSV file"/>
          <apex:pagemessages />  
            <center>
                <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
                <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
                <br/> <br/>
            </center>  
   </apex:form>   
</apex:page>
apex:
public with sharing class UploadOpportunityScheduleLineItem123{

    // Global variables
    public string nameFile{get;set;}


    Public Id parentId{get;set;}

    public Blob contentFile{get;set;}


    List<account> lstScheduleToUpdate = new List<account>();

    public account objSchedule{get;set;}
    //String array for taking csv data by line.
    String[] filelines = new String[]{};


    //set for storing all id's from csv.
    set<String> opptoupload{get;set;}



       //Main constructor
    public UploadOpportunityScheduleLineItem123()
    {
        //Initalizing required objects.
        objSchedule = new account();
        opptoupload = new set<String>();

    }
    //Method to read file content and check extension and file format.
    public Pagereference ReadFile()
    {

        parentId=Apexpages.currentPage().getParameters().get('ParentId');
        //If without selecting csv file you clicked on upload it will give error message.
      if(nameFile == null)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'You should select csv file to upload');
            ApexPages.addMessage(errormsg);
            return null;
        }
        //Taking file extension.
        String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        { 
            nameFile =blobToString( contentFile,'ISO-8859-1');
            //Spliting by new line

            filelines = nameFile.split('\n');
            //Spliting values by (,) for checking coloumn size

                for (Integer i=1;i<filelines.size();i++){               
                String[] inputconvalues = new String[]{};
                inputconvalues = filelines[i].split(',');
                account b = new account();
                b.name= inputconvalues[0];
                b.billingcountry = inputconvalues[1];
                b.billingcity = inputconvalues[2];
                lstScheduleToUpdate.add(b);                
                }
                //Checking if list is not empty then updating.
                if(lstScheduleToUpdate.Size()>0)
                {
                    insert lstScheduleToUpdate;
                }
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.info,'Batches File uploaded successfully');
                ApexPages.addMessage(errormsg);
            return null;
        }
        //If file is not csv type then it will give error message.
        else
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File type should be csv type');
            ApexPages.addMessage(errormsg);
            return null;
        }
    }
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }    
}

test class :
 
@IsTest(SeeAllData=true)

    private class testexceltoaccount
    {
          static testmethod void testLoadData() {
                   StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload1'];
             UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
             testUpload.contentFile= testdoc.Body;
             testUpload.ReadFile();
              }

    }


Cant able to cross this section of code in code coverage :
String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        {


I tried many possible to cross code coverage but still it is at that point .Please help me in this regard.
Thanks in advance
<td><apex:inputField value="{!child.batchObj.Asked_Qty__c}"/></td>
                                                   
<td><apex:inputfield value="{!child.batchObj.Quantity__c}"  required="{!child.batchObj.Asked_Qty__c=0}" style="width:110px"/></td>


When inputfield  "Asked_Qty__c" was empty .then "Quantity__c" was not required .

When inputfield  "Asked_Qty__c" was not empty .then "Quantity__c" was  required 

I want to do this asked quantity was entered by salesforce user ?

Based on input it should take required or not require  ?

How can i do this Thanks in Advance ?
 

<td>
<apex:inputfield value="{!qli.Batches_No__c}" style="width:25px;">
<apex:actionSupport event="onchange" rerender="pb,op" />
</apex:inputfield>
<apex:outputPanel id="op" >                                     
<apex:outputField value="{!qli.Batches_No__c}" />
</apex:outputPanel>
</td> 
<td>
<apex:commandlink Value="Add Batch" action="{!addBatch}" rerender="pb" styleclass="btn" style="text-decoration:None;padding-top:5px;" >
<apex:param assignTo="{!qliRowNum}" value="{!rowNum}" name="qliRowNum" /> 
<apex:param assignto="{!Batchesnumber1}" value="{!qli.Batches_No__c}" name="Batchesnumber1"/>  
</apex:commandlink>

It takes some time to load after changing the value  .I want immediate action after giving input .when i click the button it has to send the param values.
List<Batch__c> listBatchToadd=new List<Batch__c>();
          For(integer j=0;j<2;j++){
            batch__c b=new batch__c();
            listBatchToadd.add(b);
         }

        For(integer i=0;i<count;i++){
               qouteLineItemMap.put(i+1,new Quote_line_Item__c(Quote1__c=parentId));
               //  batchMap.put(i+1,new list<batch__c>();
                  batchMap.put(i+1,new list<batch__c>(listBatchToadd));
                }
System.ListException: Before Insert or Upsert list must not have two identically equal elements

I am getting this error here 
new list<batch__c>(listBatchToadd)

How to get rid of this error ?
 
public Quotelineitem_IBC(ApexPages.StandardController controller){
        flag=true;
        qouteLineItemMap=new map<Integer,Quote_line_Item__c>();
        batchMap=new Map<integer,List<Batch__c>>();
        //Capturing parent Quote id from URL
        parentId=Apexpages.currentPage().getParameters().get('ParentId');
        //Adding new QuoteLineItem without batches to map  which will be displayed after loading the page
        count=2;
        count1=2;
        List<Batch__c> listBatchToadd=new List<Batch__c>();
        For(integer i=0;i<count;i++){
        qouteLineItemMap.put(i+1,new Quote_line_Item__c(Quote1__c=parentId));
        }
        For(integer j=0;j<count1;j++){
         batch__c b=new batch__c();
        listBatchToadd.add(b);
        batchMap.put(j+1,listBatchToadd);
        }
        quoteLineItemMapsize=qouteLineItemMap.size();
    }//End of constructor

I am trying to insert two parents with two childs attached each .

This is my save method :
 
public pageReference save1(){

        //Local varibles and instance 
        List<Quote_Line_item__c> listtoinsert =new List<Quote_Line_item__c>();
        List<Batch__c> batchListToInsert =new List<Batch__c>();
        List<Integer> sortkey=new List<Integer>();
        sortkey.addAll(qouteLineItemMap.keySet());



        for(integer qli:sortkey){
            listtoinsert.add(qouteLineItemMap.get(qli));
        }//End of for 
        // Inserting the list of QuoteLine Items
        try{
            upsert listtoinsert;
        } catch(DmlException de){
             return null;
        }
        //Iterating the loop to store the list of Batches which are going to be inserted into the databse
        for(integer qli:sortkey){
            for(Batch__c bat: batchMap.get(qli)){
            if(bat.Asked_Qty__c!=Null){
                bat.Quote_Line_Item__c=qouteLineItemMap.get(qli).id;
                }
                batchListToInsert.add(bat);
            }//End of for 
        }// End of for
        try{
            upsert batchListToInsert;
        } catch(DmlException de){ 
             return null;
        }
    }//End of method


I am getting the error like this

System.ListException: Before Insert or Upsert list must not have two identically equal elements 

It is throwing the error in this 
upsert batchListToInsert;

Please provide me best solution for this :

Thanks in Advance

 
<apex:pageBlockTable value="{!Blist}" var="a">
      <apex:column headerValue="Nicomatic P/N"><apex:inputField value="{!a.Name}" id="Name" style="width:110px"  StyleClass="AutoPin" /><br/>
        <apex:commandlink Value="Fetch details"  rerender="wtable" >
                       <apex:param assignTo="{!nicomaticpn}" value="{!a.Name}" Name="parentname777"/>
                       </apex:commandlink>
      </apex:column>
Public string nicomaticpn{get ; set;}
public quoteController(){
         blist=new Map<Quote_line_item__c,list<batch__c>>();
         Quote_line_item__c acc= new Quote_line_item__c();
         acc.name=nicopn;
         acc.name=geterp(acc.Name).PartNico;
         acc.Client_P_N__c=geterp(acc.Name).PartClientPNREF;
         acc.description__c=geterp(acc.Name).PartDescription;
         acc.stock__c=geterp(acc.Name).Partstock;    
        blist.add(acc);
      }

       public ERPResult geterp(string nicopn){
          ERPResult result = new ERPResult ();
    result.PartClientPNREF = PartClientPNREF;
    result.PartDescription = PartDescription;
    result.Partstock = Partstock;
    return result;  
    };

  Hi i am passing input field value and i am getting the details from the ERP in method ERP .i want to get the pass the input field value from visaulforce to controller constructor  to get the process done .how i can do it ?

Thanks
controller:
public class quoteController{
       Public set<Quote_line_item__c> acclist{get ; set;}
       Public string parentname{get ; set;}
       Public string childname{get ; set;}
     Public Map<Quote_line_item__c,list<batch__c>> blist{ get; set;}
     public list<batch__c> ctlist{get; set;}
     integer count;
     Integer bcount;
    
        public quoteController(){
              count=1; 
              bcount=1; 
         acclist=new set<Quote_line_item__c>();      
         blist=new Map<Quote_line_item__c,list<batch__c>>();
         Quote_line_item__c acc= new Quote_line_item__c(Master_Id__c='Qli'+count,Name='teja');
         system.debug(acc.Master_Id__c);
         ctlist=new list<batch__c>();
        // batch__c ct=new batch__c(Dummy_field__c='BTH'+bcount,Quote_line_item__r=new Quote_line_item__c(Master_Id__c='Qli'+count));         
           batch__c ct=new batch__c(Dummy_field__c='BTH'+bcount);     
         system.debug(ct.Dummy_field__c);
         ctlist.add(ct);
         blist.put(acc,ctlist); 
         acclist.add(acc);
         
    }

       Public void addparent(){
         count=count+1;
         bcount=bcount+1;
         Quote_line_item__c acc= new Quote_line_item__c(Master_Id__c='Qli'+count);
         ctlist=new list<batch__c>();
         batch__c ct=new batch__c(Dummy_field__c='BTH'+bcount,Quote_line_item__r=new Quote_line_item__c(Master_Id__c='Qli'+count));
         ctlist.add(ct);
         blist.put(acc,ctlist);
         acclist.add(acc);
       }
       Public Void addchild(){
       count=count+1;
       bcount=bcount+1;
       Quote_line_item__c acc= new Quote_line_item__c(Master_Id__c=parentname);
       list<batch__c> ctlist=blist.get(acc);
       batch__c ct=new batch__c(Dummy_field__c='BTH'+bcount,Quote_line_item__r=new Quote_line_item__c(Master_Id__c=parentname));
       ctlist.add(ct);
       blist.put(acc,ctlist);
       } 
       Public void deletechild(){
       list<batch__c> b=new list<batch__c>();
       batch__c ct=new batch__c(Dummy_field__c=childname,Quote_line_item__r=new Quote_line_item__c(Master_Id__c=parentname));
       b.add(ct);
       b.clear();
      }
      Public Void deleteparent(){
      Quote_line_item__c acc= new Quote_line_item__c(Master_Id__c=parentname);
      blist.remove(acc);
     }
    Public pagereference save(){
Map<Integer,List<batch__c>> mapIndexWithBatch = new Map<Integer,List<Batch__c>>();

// Insert quote line items and prepare map of index and batch
List<Quote_line_item__c> listInsertQuoteLineItem = new List<Quote_line_item__c>();
Integer intCount = 0;
for (Quote_line_item__c objQuoteLineItem:blist.KeySet()) {
    listInsertQuoteLineItem.Add(objQuoteLineItem);
    mapIndexWithBatch.put(intCount,blist.Get(objQuoteLineItem));
    intCount++;
}
Insert listInsertQuoteLineItem;

// Prepare list of batch and assign quote line item id based on index
// and insert list of batch
List<Batch__c> listInsertBatch = new List<Batch__c>();
for (Integer intCurrentIndex:mapIndexWithBatch.KeySet()) {
    for (Batch__c objBatch:mapIndexWithBatch.Get(intCurrentIndex)) {
        objBatch.Quote_line_item__c = listInsertQuoteLineItem[intCurrentIndex].Id;
        listInsertBatch.Add(objBatch);
    }
}
Insert listInsertBatch;
  
      return null;
      }
  }

Visualforce Page:
<apex:page Controller="quoteController" showHeader="false">
<apex:form >
   <apex:pageBlock title="Bulk Quotelineitem Create" id="wtable">
      <apex:pageBlockTable value="{!Blist}" var="a" >
      <apex:column >

         </apex:column>
         <apex:column headerValue="Parent">
            <apex:inputField value="{!a.Name}"/>
         </apex:column>
         <apex:column headerValue="Name">
            <apex:outputField value="{!a.Master_Id__c}"/>
         </apex:column>
         <apex:column >
         <apex:commandButton value="Delete Parent" action="{!deleteparent}" rerender="wtable">
         <apex:param assignTo="{!parentname}" value="{!a.name}" Name="parentname777"/>
         </apex:commandButton>
         </apex:column>
         <apex:column breakBefore="true" colspan="2" >
          <apex:pageblocktable value="{!blist[a]}" var="c" >
        <apex:column headerValue="Contact Name">
           <apex:inputField value="{!c.Name}"/>
         </apex:column>
         <apex:column headerValue="Dummy Field">
          <apex:inputField value="{!c.Dummy_field__c}"/>
         </apex:column>
         <apex:column >
          <apex:commandlink Value="Add child" action="{!addchild}" rerender="wtable">
         <apex:param assignTo="{!parentname}" value="{!a.Master_Id__c}" Name="parentname777"/>
         </apex:commandlink>
         </apex:column>
         <apex:column >
         <apex:commandlink Value="Delete Child" action="{!deletechild}" onclick="remove(this)"  rerender="wtable">
         <apex:param assignTo="{!parentname}" value="{!a.Master_Id__c}" Name="parentname777"/>
         <apex:param assignTo="{!childname}" value="{!c.Dummy_field__c}" Name="parentname777"/>
         </apex:commandlink>
         </apex:column>
         </apex:pageblocktable>
         </apex:column>  
    </apex:pageBlockTable>
   </apex:pageblock>
   <apex:commandButton Value="Add parent"   action="{!addparent}" rerender="wtable"/>
   <apex:commandButton Value="save"   action="{!save}" rerender="wtable"/>
 </apex:form>
</apex:page>

Map key a0LN0000002vFjWMAU not found in map
Error is in expression '{!blist[a]}' in component <apex:pageBlockTable> in page newlineitempage

I am getting like this error .Help me to solve this error 

Thanks in Advance


 
Public Map<Quote_line_item__c,list<batch__c>> blist{ get; set;}
public list<batch__c> ctlist{get; set;}
 Quote_line_item__c acc= new Quote_line_item__c(Master_Id__c='Qli'+count);
         ctlist=new list<batch__c>();
         batch__c ct=new batch__c(Dummy_field__c='BTH'+bcount,Quote_line_item__r=new Quote_line_item__c(Master_Id__c='Qli'+count));       
         ctlist.add(ct);
         blist.put(acc,ctlist);



Master_id__c is a link field between Quote_line_item__c and batch
For Every action I am using this map to put 

At last i want to insert those values in Map blist how can i do that help me ?
 
for(quote_line_item__c q:blist.keyset()){
       For(batch__c b:  ){
     }
     }

How to compete thsi save logic .Help me
want to auto click the link when a field update happens picklist value is "sent to customer".

I have a link from website that when i click on link it will change status on website.

what i want is ,Want to auto click that link when a slaesforce field upadte happenes pick list value is"sent to customer".

auto click should run on back ground it should not reload page.

Help me suggesting some ideas .say me this is possible or not
want to auto click the link when a field update happens picklist value is "sent to customer".

I have a link from website that when i click on link it will change status on website.

what i want is ,Want to auto click that link when a slaesforce field upadte happenes pick list value is"sent to customer".

auto click should run on back ground it should not reload page.

Help me suggesting some ideas .say me this is possible or not
Hi all ,
          I have a requirement that i need to to display all Contacts and Leads of our Organization on Google maps using Single Visualforce page to track All Contacts and Leads from Current Location, Here i displayed all Leads from current location but i need to display All Contacts also for the same Page if any one knows pls help

Here is my code

Class:
--------
global with sharing class LeadsNearbyMe {

public Lead leads{get; set;}

@RemoteAction
   global static List<Lead> getNearby(String lat, String lon) {

        if(lat == null || lon == null || lat.equals('') || lon.equals('')) {
            lat = '51.096214';
            lon = '3.683153';
        }

        String queryString =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Lead ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';
        return(database.Query(queryString));
    }
}

Page:
--------

<apex:page sidebar="false" showheader="false" controller="LeadsNearbyMe">
 
  <apex:includeScript value="{!$Resource.googleMapsAPI}" />
      <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCROH4OR9fzDhmprWPL1wGWfPT4uGUeMWg&sensor=false">
        </script>
        
    <!-- Setup the map to take up the whole window -->
    <style>
        html, body { height: 100%; }
        .page-map, .ui-content, #map-canvas { width: 100%; height:100%; padding: 0; }
        #map-canvas { height: min-height: 100%; }
    </style>
    
    <script>
        function initialize() {
            var lat, lon;
          
             if (navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(function(position){
                     lat = position.coords.latitude;
                     lon = position.coords.longitude;                    
                     
                     // Use Visualforce JavaScript Remoting to query for nearby conts      
                     Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.LeadsNearbyMe.getNearby}', lat, lon,
                         function(result, event){
                             if (event.status) {
                                 console.log(result);
                                 createMap(lat, lon, result);           
                             } else if (event.type === 'exception') {
                                 //exception case code          
                             } else {
                                            
                             }
                          },
                          {escape: true}
                      );
                  });
              } else {
                  // Set default values for map if the device doesn't have geolocation capabilities
                    /** Eindhoven **/
                    lat = 51.096214;
                    lon = 3.683153;
                    
                    var result = [];
                    createMap(lat, lon, result);
              }
          
         }
    
         function createMap(lat, lon, leads){
            var currentPosition = new google.maps.LatLng(lat,lon);
            var mapDiv = document.getElementById('map-canvas');
            var map = new google.maps.Map(mapDiv, {
                center: currentPosition,
                zoom: 13,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            
            // Set a marker for the current location
            var positionMarker = new google.maps.Marker({
                map: map,
                position: currentPosition,
                title: 'You are here',
            });
            
            // Keep track of the map boundary that holds all markers
            var mapBoundary = new google.maps.LatLngBounds();
            mapBoundary.extend(currentPosition);
            
            // Set markers on the map from the @RemoteAction results
            var cont;
            for(var i=0; i<leads.length;i++){
                cont = leads[i];
                console.log(leads[i]);
                setupMarker();
            }
       map.fitBounds(mapBoundary);

           function setupMarker(){
                var contNavUrl;
           
                try{
                    if(sforce.one){
                        contNavUrl =
                            'javascript:sforce.one.navigateToSObject(\'' + cont.Id + '\')';
                    }
                } catch(err) {
                    console.log(err);
                    contNavUrl = '\\' + cont.Id;
                }
                
                var contDetails =
                    
                    cont.Name + ',' +
                    cont.Street + ',' +
                    cont.City + ',' +
                    cont.PostalCode;
           var marker = new google.maps.Marker({
                   map: map,
                   icon : "{!URLFOR($Resource.GoogleMarkers, 'GoogleMark/4-l.png')}",
                   title:contDetails,
                   position: new google.maps.LatLng(
                                   cont.Location__Latitude__s,
                                   cont.Location__Longitude__s)
               });
               mapBoundary.extend(marker.getPosition());
           }
                  
           }
 
        google.maps.event.addDomListener(window, 'load', initialize);
        
    </script>
<body style="font-family: Arial; border: 0 none;">
 
        <div id="map-canvas"></div>
    </body>
 
</apex:page>


Screen shot:
------------------

User-added image


Thanks & Regards,
  • January 07, 2015
  • Like
  • 2