• Vigneshwaran Loganathan
  • NEWBIE
  • 435 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 5
    Likes Received
  • 0
    Likes Given
  • 124
    Questions
  • 58
    Replies
I am trying to show number of components in same section by using LWC. I can able to acheive this using "v.body" in lightning.. But I am not sure if I can acheive the same in LWC.
User-added image

From above picture, If I click on any row, it will open next-page on the same section.. I need a similar one with LWC.. I read somewhere I can use slot for this, but not able to complete.

Can anyone help?
I have a Component where I show list of Accounts using "lightning:verticalNavigation".. Now upon clicking one Account from this list, I would like to Open all its associated Contacts in same section.. How can I do that? 

User-added image
<aura:handler name="init" value="{!this}" action="{!c.doInit1}" />
 <aura:attribute name="items" type="Object"/>
 <aura:attribute name="items2" type="String" />

 <div class="slds-m-around_xx-small">  
        <lightning:layout>
            <lightning:layoutItem>
                <lightning:verticalNavigation selectedItem="{!v.selectedaccId}"
                                              onselect="{!c.onSelect}">
                    <lightning:verticalNavigationSection label="Select Account">
                        <aura:iteration items="{!v.items}" var="clnt" indexVar="index">
                            <lightning:verticalNavigationItemIcon label="{!clnt.Name}" 
                                                              name="{!clnt.Id}"
                                                              iconName="utility:open_folder"/>
                        </aura:iteration>
                    </lightning:verticalNavigationSection>
                </lightning:verticalNavigation>
            </lightning:layoutItem>          
        </lightning:layout>
</div>
 
doInit1: function (cmp, event, helper) {
        var action = cmp.get("c.getTreeData1");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.items', response.getReturnValue());
            }
            
        });
        $A.enqueueAction(action);
    },


Thanks

Vignesh

Hi All,  I have a requirement to show object's records in nested-accordian view.. It goes Like Customer(Parent) > Customer Product(Child for Customer) > Suites (Child for Customer Product)

Initially I used Accordian, but I was not able to go third-level.. So, I used lightning:tree for this purpose.. But, with this, I cannot get Id of the record.. Can anyone help with this? 

CMP: 
<aura:component controller="TreeController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="items" type="Object"/>
    <lightning:tree items="{! v.items }" onselect="{!c.handleSelect}"/>
</aura:component>

JS
({
    doInit: function (cmp, event, helper) {
        var action = cmp.get("c.getTreeData");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.items', JSON.parse(response.getReturnValue()));
            }
            
        });
        $A.enqueueAction(action);
    },
    
    handleSelect: function (cmp, event, helper) {  
        
        var getId = event.getParam('name');
        console.log('>>> getName' + getId);
	},
    
 })




User-added image

Vignesh
I need to add a Date field in "Approver Settings" section from "My Settings" page. I created this field "Delegate Till" - and added in User layout.
But this just adds field "Additional Information" section - Is there way to include under Approver Settings? If not, what workaround can I suggest?User-added image
Hi All, The link https://rajvakati.com/2018/11/13/navigate-to-component-using-lightningnavigation/ where Source Component passes parameters to Target and the parameters are visible in URL.. 

I am following the exact steps but its not passing parameters to mt Target Component, neither can I see any Parameters in URL.. Is there anything I am doing wrong? 

I have added the component in Account Details Page.. 

Source.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <lightning:navigation aura:id="navService"/>
    <aura:attribute name="pageReference" type="Object"/>
    <aura:attribute name="url" type="String"/>
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    <lightning:button label="Open Lightning Component" onclick="{!c.handleClick}"/>
    
</aura:component>
SourceController.JS
({
    init : function(cmp, event, helper) {
        var navService = cmp.find("navService");
        var pageReference = {
            
            "type": "standard__component",
            "attributes": {
                "componentName": "c__Target"    
            },    
            "state": {
                "firstName": "Test"  ,
                "lastName": "user"    
            }
        };
        cmp.set("v.pageReference", pageReference);
        var defaultUrl = "#";
        navService.generateUrl(pageReference)
        .then($A.getCallback(function(url) {
            cmp.set("v.url", url ? url : defaultUrl);
        }), $A.getCallback(function(error) {
            cmp.set("v.url", defaultUrl);
        }));
    },
    handleClick: function(cmp, event, helper) {
        var navService = cmp.find("navService");
        // Uses the pageReference definition in the init handler
        var pageReference = cmp.get("v.pageReference");
        event.preventDefault();
        navService.navigate(pageReference);
    }
})

Target.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:isUrlAddressable" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />

    <aura:attribute name="firstName" type="String" />
    <aura:attribute name="lastName" type="String" />
    <div>
        Full Name : {!v.firstName} + {!v.lastName}
    </div>
</aura:component>
TargetController.JS
({
    init: function(cmp, event, helper) {
        var pageReference = cmp.get("v.pageReference");
        cmp.set("v.firstName", pageReference.state.firstName);
        cmp.set("v.lastName", pageReference.state.lastName);
    }
})


Below is the URL which when I clicked from Account Page - without Parameters

User-added image

Thanks

Vignesh

I am facing "Error in $A.getCallback() [quickcon is not defined]" and not able to find whats the issue, can anyone help? 

Component
<aura:component implements="force:appHostable,force:hassObjectName,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" 
                controller="RatingVsAccount">
   
   <aura:attribute name="cons" type="Contact" />
    <aura:registerEvent name="quickcontact" type="c:QuickContactEvent"></aura:registerEvent>
                   
    
    <aura:attribute name="newContact" type="Contact" default="{'sobjectType': 'Contact',
                                                              'FirstName':'',
                                                              'LastName':'',
                                                              'Email':'',
                                                              'Phone':''
                                                              }"/>
    <div class="slds-col-grid">
         <lightning:input aura:id="fieldId"
                             required="true"
                             label="Last Name"
                             name="filename"
                          	 type="text"
                        	 message-when-value-missing="This field is mandatory"	
                             value="{!v.newContact.LastName}"/>
       
        <lightning:button label="save" onclick="{!c.savecontact}"/>
    </div>
</aura:component>

Controller
({
	savecontact : function(component, event, helper) {
		
       
   
        var action = component.get("c.save");
        
        
            var con = component.get("v.newContact");
            action.setParams({
                con : con,
                Accid : component.get('v.AccountId'),
            });
        
		action.setCallback(this, function(a) {
					   var state = a.getState();
						if (state === "SUCCESS") {
							var name = a.getReturnValue();
						   var CompEvent = component.getEvent('quickcontact');
											   CompEvent.setParams({ quickcon, name});
											   
											   CompEvent.fire();  
							}
						});
		$A.enqueueAction(action)    
        },
	
})

Apex method
@AuraEnabled
    public static Contact save(contact con, string Accid)
    {
        
        con.AccountId = Accid;
        
        insert con;
        system.debug('>>> con' + con);
        return con;
        
    }
Event
<aura:event type="COMPONENT" description="Event template" >
   <aura:attribute name="quickcon" type="Contact"></aura:attribute> 
</aura:event>

Many Thanks for your help
 
Hi All, 

I have a form-page with some fields.. Upon entering values, I can click on a button which takes me to Page 2.. I am using different Page and Controller here.. Earlier I used to send parameters from URL and it worked fine.. 
Now, I have added a new Multi-Picklist field to Page 1 - This field has around 20 values.. In case, If I select all values and append in URL, will it work fine? Or do we have any alternatives to achieve this? 

 
public PageReference getCreateNewAccountPage()
{

// URL Parameter codes here

//territoryNameStr string in below URL contains all Multi-values 

PageReference cnaPr = new PageReference('/apex/'+ GAS_CREATE_NEW_ACCOUNT_PAGE_URL + 
                            '?aType=' + selectedAccountType + passOnParams + 
                            '&defaultCountry=' + defaultCountry +  
                            '&territoryname='+territoryNameStr + '&retUrl=' + GAS_TAB_URL +  
                            '&aggSpendHCP='+aggSpendHCP);
}
Thanks
Vignesh 
Hi All, I am facing the above error while doing a module from Trailhead, can anyone help? what does the error mean?

AccountMap
<aura:component>
    <aura:attribute name="map" type="Object"/>
    <aura:handler event="c:AccountsLoaded" action="{!c.accountsLoaded}"/>
    <ltng:require styles="/resource/leaflet/leaflet.css"
        scripts="/resource/leaflet/leaflet.js"
        afterScriptsLoaded="{!c.jsLoaded}" />
    <div id="map"></div>
</aura:component>


AccountMapController
accountsLoaded: function(component, event, helper) {
        // Add markers
        var map = component.get('v.map');
        var accounts = event.getParam('accounts');
        for (var i=0; i<accounts.length; i++) {
            var account = accounts[i];
           
            var latLng = [account.Location__Latitude__s, account.Location__Longitude__s];
            L.marker(latLng, {account: account}).addTo(map);
        }

AccountsLoaded.evt
<aura:event type="APPLICATION">
    <aura:attribute name="accounts" Type="Account[]"/>
</aura:event>
Thanks for the help
Vignesh
 
Hi, I need to write a valdation rule for below scenario, 
Two Objects -- Eg, Accounts and Contacts. Contacts has a picklist called "Type" (values - 'Business' , 'Professional')..
I have a vf page where i can enter Account details, (multiple)Contacts and save all at one go.. Now the requirement is, if I save more than one contact, Type should be same - means, it should be either Bussiness or Professional for all contacts.. 
Is it possible to achieve this using ONLY vaidation rule (i cant write trigger for some reasons).?
 
I am importing large csv using VF page. Before importing I need to Validate the data. So, I have created a validate method which reads the file and stores in a list(and do validations further). Since the file has nearly >5k records it hits CPU Time limit exception. So, i thought of passing the parsedValues to batch class and get sObject values. Below is the method i have in class,


I need to pass ParsedVal to batch class and return results to Normal class to proceed checking further methods.
Class : SPLImortGildExt
Public list<sObject> csv2sObject(list<List<string>> parsedval)
    { 
      splitObject = selectedObj.split(',');  
       SPL_BatchCsv2sObject sb = new SPL_BatchCsv2sObject(parsedval);
        Database.executeBatch(sb,200);

      return sObj; // Need to get value from Batch apex
   }
 
Batch Apex :

global void execute(Database.BatchableContext context, SObject[] records)
          list<sobject> sObj = new list<sobject>();
       
          Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(splitObject[0]).getDescribe().getSObjectType();
                       
          for(list<string> head : parsedVal)
          {
            for(string col : head)
            {
             if(headerMap.containsKey(col.Trim()))
              headers.add(headerMap.get(col.Trim()));
             else
              headers.add(col);
             }
            break;
          }
            
          integer rowNum = 0; 
          
          for(list<string> row : parsedval)
          {
            if(rowNum == 0)
            {
              rowNum++; 
              continue;
            }
            
            else
            {
              sObject thisObj = objectDef.NewsObject();
                           
              integer col = 0;
              
              for(string colx : row)
              {
               
                string headerName = headers[col].trim();
                
                
                Try
                {
                       if((colx.contains('/')  || colx.contains('-'))
                      {
                      
                       datex =  (colx.contains('/')) ? colx.split('/') : colx.split('-');
                       
                         thisObj.put(headerName , Tempdate);                       
                      }
                      
                      else
                      {
                          if(headerName=='active_vod__c') 
                          {
                              thisObj.put(headerName , boolean.valueof(colx));
                          }
                          
                         
                      }

                    }
                                                 
                     col++;
                  }  // closing column for loop
                
              
              sObj.add(thisObj);  // Need to pass this values to previous class 
                
              
              rowNum++;
              } //close else
            } // close for         
        }
  
    }
Is there a way to acheive this.? 

Thanks.!
Hello, 

I have a VisualForce page to Export as Csv. In this I have some columns which renders based on a Boolean value. I have added a similar code below,
<td><apex:outPutlabel value="Prioritisation ANF"  rendered="TRUE"/>  </td>
<td><apex:outPutlabel value="Classification CF"  rendered="FALSE"/>  </td>
<td><apex:outPutlabel value="Prioritisation CF"  rendered="FALSE"/>  </td>
<td><apex:outPutlabel value="Classification HBV"  rendered="TRUE"/>  </td>


When it exports, it shows Blank columns as in below screenshot. For each (Render=false) it creates a blank space. it looks fine in VisualForce page though. 

  User-added image 

Any idea to overcome this.? 

Thanks 
Vignesh

Hello, 

I have to bulk insert in two objects which are parent and child. I have mapped parent's external id to child records.

I'm calling batch apex from normal class which inserts both. But Child records cant able to find parent External ID as it runs in parallel instead of one after one. 

Error : System.DmlException: Upsert failed. First exception on row 0; first error: INVALID_FIELD, Foreign key external ID
public static void saveFile()
     {         
              Try
                {                                                
                        if(FinalTarList.size()>0)  // Parent
                         {
                         SPL_BatchImportGild splTar = new SPL_BatchImportGild(FinalTarList); // should execute first
                         Database.executeBatch(splTar,200);
                         success = true;
                         }
                        
                        if(FinalcycdetCopy.size() > 0)
                            {
                             SPL_BatchImportGild splTarDet = new SPL_BatchImportGild(FinalcycdetCopy); // should execute after parent Insertion. 
                             Database.executeBatch(splTarDet,200); 
                            }                            
                 }
                       
          }

Is there a way to achieve this.? please suggest me if there are alternatives. 

Thanks 
Vignesh

Hello, 

I am importing large sets of Data using Batch Apex from visualForce page. I have collected the list value from Class and calling batch apex just to do DML. 

Below is my code, 

Calling from class : 
SPL_BatchImportGild splTar = new SPL_BatchImportGild(FinalTarList);
Database.executeBatch(splTar);

Batch:

global class SPL_BatchImportGild implements Database.Batchable<SObject> , Database.Stateful 
{
global SObject[] queue; // = new list<Cycle_Plan_Target_vod__c>();
    
    global SPL_BatchImportGild(SObject[] recs)
    {
        queue=recs;
    }
    
    public static SObject[] start(Database.BatchableContext context) {
    {
        // need to pass the Queue value to execute. But showing error message 'Variable does not exist: queue'.
    }
    
    global static void execute(Database.BatchableContext context, SObject[] records) {
        insert records;
    }
    gloBal void finish(Database.BatchableContext context) 
    {
        
    }

What could be the reason for this.? 

Thanks 

Vignesh

Hi All, 

I have a requirement to import data from excel sheet. the Sheet will have data similar to the below one, 

User-added image

As you see, I need to map two (or more) Contacts to the same account in a row. For Eg, 2nd column has 2 contacts. So, I need to create 2 list records for 1 row and at the end list should have 6 rows (2 contacts for each accounts).  

If I iterate the row using 'for' loop, I can able to map only One contact not two. So, I end up adding only 3 rows. Is there a way we can achieve this.? 

Thanks,
Vignesh
 
Hello,

I have a VisualForce page from which I'm loading some Data , Validating and Saving it to SF. While processing this i need to show Loading icon. I've tried this with the help of some forums but no luck. 
 
<apex:pageBlockSection id="pbs">
         <apex:pageBlockSectionItem >
            <apex:outputLabel value="Select Object"/>
         </apex:pageBlockSectionItem>  
       
         <apex:pageBlockSectionItem >
             <apex:selectList size="1" value="{!Objselected}" >
                <apex:selectOptions value="{!ObjList}"/>
             </apex:selectList>
         </apex:pageBlockSectionItem> 
         
         <apex:pageBlockSectionItem >
             <apex:outputLabel value="Select File"/>
         </apex:pageBlockSectionItem>
         
         <apex:pageBlockSectionItem >
               <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />          
         </apex:pageBlockSectionItem>
                           
          <apex:pageBlockSectionItem ></apex:pageBlockSectionItem> 
          
         
          
          <apex:pageBlockSectionItem id="pbsi">
             <apex:actionRegion id="area51" renderRegionOnly="false">
             <apex:commandButton action="{!ReadFile}" value="Validate File" id="theButton" disabled="{!vbutton}" status="spinnerStatus" rerender="pbsi"  /> 
             <apex:commandButton action="{!SaveFile}" value="Save" id="sButton"  disabled="{!sbutton}" status="spinnerStatus" rerender="form" /> 
            </apex:actionRegion>    
              
          </apex:pageBlockSectionItem> 
</apex:pageBlockSection>

When I use rerender, parameters are not passed to controller. Is there a way to overcome this.? 

Thanks
Vignesh
Hi Everyone, 

I'm facing "Illegal assignment from Cycle_Plan_vod__c to Id". Below is my code, 

I'm getting the values for colx from excel and should assign it to Cycle_plan_vod__c (Lookup in Cycle plan target) field. When i assign External id, I'm facing the error. I cant assign cyp.id as it returns null..!

Schema.sObjectType objectDefTar = Schema.getGlobalDescribe().get('Cycle_plan_Target_vod__c').getDescribe().getSObjectType();
sObject thisObjTar = objectDefTar.NewsObject();

if(cycPlanTargetFields.contains(headerNameTar) && headerNametar=='Cycle_Plan_vod__c')
                      {
                           system.debug('*****here' + headerNameTar);
                          Cycle_plan_vod__c cyp = new Cycle_plan_vod__c(External_ID_vod__c = colx);
                          
                          thisObjTar.put(headerNameTar , cyp);                        
                      }
I have a batch class in which I am deleting some records in Finish method. but its showing query error. can anyone help.? 

Not sure why the error is coming though i have set a limit to 9500 records. i can add more filters but need to know why this is not working.
global void finish(Database.BatchableContext bc) {
        // Delete TMs where the TOT has since been deleted, cancelled, rescheduled
        //delete [SELECT Id FROM Time_Management_AZ_EU__c WHERE TOT_For_Removal__c = TRUE];
        
        List <Time_Management_AZ_EU__c> Timemanage = new List<Time_Management_AZ_EU__c>(); 
        Timemanage = [SELECT Id, Name FROM Time_Management_AZ_EU__c WHERE TOT_For_Removal__c = TRUE LIMIT 9500] ;
         if(Timemanage.Size() > 0)
        Delete Timemanage;
       }


Thanks 
Vignesh

Hello, 

I Have apex class which checks if profile id != null and do some acions in user. Below is the code, 
 
public void registerUser()
{
   if(//condition)
        {
             if()
             {
                //some actions
             }
             else
             {
             Database.DMLOptions dmo = new Database.DMLOptions();
             dmo.EmailHeader.triggerUserEmail = true;
             
             Profile p = [select id from profile where name = 'YMCA Community User'];
             
             if(p.id != null)
             {
             try
             { 
                newUser = new User();
                newUser.Username = mEmail;
                newUser.firstName  = acnt[0].FirstName;
                newUser.LastName = acnt[0].LastName;
                //and all user field assigning fields..

                newUser.setOptions(dmo);
                List<Account> a = [SELECT Id from Account where Email__c = :mEmail];
                String accountId = a[0].Id;
                Site.createPortalUser(newUser,accountId,passwd);

             }
             catch(Exception Ex)
             {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error,ex.getmessage()));
                //return null;
             }
        }

I need to Execute the Try part, but below test class is not working..  
 
static testMethod void testselfregcon2(){
    
       
        Profile p= [Select id from profile where Name ='YMCA Community User']; 
        system.debug('>>profT'+p);
                
        user objuser=new user(Username='testuser@email.com', ContactId=objcon.Id,LastName ='uuser', Email='test1231231@abc.com', Alias='usr', CommunityNickname='test', TimeZoneSidKey='America/Los_Angeles', LocaleSidKey='en_US', EmailEncodingKey='UTF-8', ProfileId = p.id, LanguageLocaleKey='en_US');
        insert objuser;
       
        system.runAs(objuser)
        {
        CommunitiesSelfRegCustomController1 objcls= new CommunitiesSelfRegCustomController1();
        objcls.registerUser();
        }
    }
Guess, Profile Id is not passing to class because of which else part is not working. can anyone help on this.? 

Thanks
Vignesh
Hi Guys, 

I have written a simple REST class to connect two SF orgs (lets say A and B), 

in A, i have created remote site 'Login.salesforce.com' and wrote below class, 
 
@RestResource(urlMapping='/createNewAccountUsingRestAPI/*')
global with sharing class RESTCreateNewAccount{

    @HttpPost
    global static string createAccountRecord(String name) {
     string succError;
     account acc = new account();
     acc.name = name;       
     insert acc;
     acc.accountsource = 'Other';
     update acc;
     succError = 'New account has been created. Account Record id is:'+acc.id;
     return succError;
    }
  
    @httpput
    global static string updateAccountRecord(String name) {
       string returnmessage = 'Account are updated successfully';
       List<account> accupdateList = [select name,id,AccountSource from account where name =: name];
       for(account acc : accupdateList){
           acc.AccountSource = 'Web' ;
           returnmessage = returnmessage +acc.id;
       }
       try{
         update accupdateList;
       }
       catch(exception ex){
         returnmessage = ex.getmessage();
       }
       return returnmessage ;
    }           
}

in Org B, i have written Below class,
 
public class RestAPIcalloutExample{

   Public void loginToOtherOrgAndCreaetNewAccount(){
        /*Login to Other Salesforce Org to grab session id - begin*/
        HTTP h1 = new HTTP();
        HttpRequest request = new HttpRequest();       
        request.setEndpoint('https://login.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        request.setTimeout(60000);
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + 'vigneshwaranl@hotmail.com'+ '</username><password>' +'makil1234'+ '</password></login></Body></Envelope>');
        String SERVER_URL;
        String SESSION_ID;
        HTTPResponse loginResponse = h1.send(request);     
        Dom.Document doc = loginResponse.getBodyDocument();
        Dom.XMLNode receivedXml= doc.getRootElement();
        SESSION_ID = receivedXml.getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/').getChildElement('loginResponse', 'urn:partner.soap.sforce.com').getChildElement('result','urn:partner.soap.sforce.com').getChildElement('sessionId','urn:partner.soap.sforce.com') .getText();      
        system.debug('***session id'+SESSION_ID); 
        /*Login to Other salesforce Org to grab session id - finish*/
      
        /* Send https request to the custom REST API defined in other org that has urlmapping as 'createNewAccountUsingRestAPI' -begin*/
        HTTP h2 = new HTTP();
        HttpRequest request2CreateAccount = new HttpRequest();
        request2CreateAccount.setMethod('POST');
        request2CreateAccount.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request2CreateAccount.setHeader('Accept', 'application/json');
        request2CreateAccount.setHeader('SOAPAction', '""');
        request2CreateAccount.setbody('{"name":"Cloudforce4u Technologies Ltd"}');
            request2CreateAccount.setEndpoint('https://ap1.salesforce.com/services/apexrest/createNewAccountUsingRestAPI');
        request2CreateAccount.setHeader('Authorization', 'OAuth '+SESSION_ID);             
        HTTPResponse resppnceFromOtherSFOrg = h2.send(request2CreateAccount);
        /* Send https request to the custom REST API defined in other org that hass urlmapping as updateaccountrec - finish*/
        system.debug('**-Output-**'+resppnceFromOtherSFOrg.getbody());
   } 
 }

i tried to run this from Dev Console from Org B, its showing 'de-reference a null object' Error.. What is the mistake here.? 

Thanks, 
Vignesh
Hi, 

I am trying to add calender to My Dev Org with the help of one link. 

But Im facing issue on Pageload funtion,
public class CalendarExample_Controller {



    public Boolean includeMyEvents {get;set;}

    public list<calEvent> events {get;set;}

    

    //The calendar plugin is expecting dates is a certain format. We can use this string to get it formated correctly

    String dtFormat = 'EEE, d MMM yyyy HH:mm:ss z';

    

    //constructor

    public CalendarExample_Controller() {

        //Default showing my events to on

        includeMyEvents = true;

    }

    

    public PageReference pageLoad() {

        events = new list<calEvent>();

        //Get Contact's Birthdays

        for(Contact cont : [select Id, Birthdate, FirstName, LastName from Contact where Birthdate != null]){

            //here we need to replace the birth year with the current year so that it will show up on this years calendar

            DateTime startDT = datetime.newInstance(Date.Today().Year(),cont.Birthdate.Month(), cont.Birthdate.Day());

            calEvent bday = new calEvent();

            

            bday.title = cont.FirstName + ' ' + cont.LastName + '\'s Birthday!';

            bday.allDay = true;

            bday.startString = startDT.format(dtFormat);

            //Because this is an all day event that only spans one day, we can leave the send date null

            bday.endString = '';

            bday.url = '/' + cont.Id;

            bday.className = 'event-birthday';
            system.debug('>>>bday'+bday);
            events.add(bday);

        }

        

        //Get Campaigns

          for(Campaign camp : [select Id, Name, StartDate, EndDate from Campaign where IsActive = true])
        {

         DateTime startDT = camp.StartDate;
    system.debug('>>>startDT'+startDT);
            DateTime endDT = camp.EndDate;

            calEvent campEvent = new calEvent();            

            campEvent.title = camp.Name;

            campEvent.allDay = true;

           campEvent.startString = startDT.format(dtFormat);

          campEvent.endString = endDT.format(dtFormat);

            campEvent.url = '/' + camp.Id;

            campEvent.className = 'event-campaign';
    //system.debug('>>>11'+endDT.format(dtFormat));
            events.add(campEvent);

        }  
        
        return null;

    }

    

    public PageReference toggleMyEvents() {

        if(includeMyEvents){

            includeMyEvents = false;

        }

        else{

            includeMyEvents = true;

        }

        pageload();

        return null;

    }



    

    //Class to hold calendar event data

    public class calEvent{

        public String title {get;set;}

        public Boolean allDay {get;set;}

        public String startString {get;private set;}

        public String endString {get;private set;}

        public String url {get;set;}

        public String className {get;set;}

    }

}

Its showing "Attempt to de-reference a null object" on campEvent.endString . But from Debud Log i can see records. 

What could be the reason for this? 

Thanks 
Vignesh
Hi frnz, I need a logic for below situation in TRIGGER.

** VA is a parent object which has Cancellation as Child that has three records with 'start date' and 'end date' fields.
We need to calculate total days between Start date and End date in three records, then store it in VA.

** Now if those three records have any Overlapping days, we should not count that. For Example.......

Record1 - start date = jul 01 2015, end date = Jul 31 2015  = 31 days
Record2 - start date = Jul 10 2015, end date = Jul 20 2015  = 0 Dates were overlapped by the others
Record3 - start date = Jun 21 2014, end date = Jul 05 2015 = 10 days (Jun 21 - Jun 30, july 01 - july 05 overlapped by the others)
Record4 - start date = Jun 01 2014, end date = Jun 05 2014 = 5 days
total of 46 days

How to achieve this?
Thanks. :))
 
Hi,

I'm facing below error in Callout. Can anyone help?


System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
public static void CallforListContactsRequest(string accno)
    {  
       
        contactrequest cntreq1 = new contactrequest();
        contactrequest cntreq = new contactrequest();
        cntreq1.Customername = 'TelAssistant';
        cntreq1.Username = 'Salesforce';
        cntreq1.Password = '&7mXvDGwvU';
        cntreq1.ThirdpartyAccountID= accno;
        //cntreq1.ClientId='517ec5430f4e161a400dc07a';
        String jsonBody = json.serialize(cntreq1);
        system.debug(jsonBody);
        system.debug('this is called from CallforListContactsRequest');
        HttpResponse res;
        HttpRequest req = new HttpRequest();
        req.setEndPoint('https://telassistant.hostedsuite.com/api/json/reply/ListClientsRequest'); 
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');
        req.setBody(jsonBody);
        Http http_req = new Http();
      try 
        {
            res = http_req.send(req);  //********ERROR  AT THIS LINE  
            system.debug('bodycontact'+res);
           // if(res.getbody()!='[]')
             //{    
                string httpresp = res.getBody();
                String reqresponse = res.getBody();
                list<contactrequestresp> deserializedString= (list<contactrequestresp>)JSON.deserialize(reqresponse,list<contactrequestresp>.class);
                system.debug('deserializedString contact request'+deserializedString);
                for( contactrequestresp d1 : deserializedString )
                  {
                     clientidx = d1.id;
                     system.debug('** client name **' + d1.id );
                     system.debug('** client name **' + d1.clientname );
                     system.debug('**3rdpartyno **' + d1.ThirdPartyAccountId );
                     system.debug('**Client id **' + d1.ClientId );
                 }//}  
          /***   else
             {
                Daily_Billing_Error_Log__c e8 = new Daily_Billing_Error_Log__c();
                e8.Accountno3__c = accno;
                e8.processdate__c = system.today();
                e8.errormsg__c = ' contact request response error '; 
                insert e8;
             }***/          
        }  
        catch(System.CalloutException e) 
        {
            Daily_Billing_Error_Log__c e9 = new Daily_Billing_Error_Log__c();
            e9.Accountno3__c = accxx;
            e9.processdate__c = system.today();
            e9.errormsg__c = ' call out error - contact request '; 
            insert e9;
           
        }
        
     }
Thanks
On Clicking 'GO' button in 'SampleVF' page, Link will be sent to Mail of Applicant(s).

when he clicks that link he will be redirected to SampleVF2 visualforce page.

After Entering Details Into the Visualforce page he/she will click the 'submit' button.

Then Entered details are stored in HelloWorld Objects fields and also that page 'SampleVF2'  should be converted as PDF and saved in same HelloWorld Object as attachment.

Thanks.
 
I need to display a column value with the proper format. Let me explain my situation,

Am entering hint values in a Rich Text field and trying to display it in a pageblock table column.Am using show toggle function to that particular column based on the user click event on the other column.

Am entring the values as line by line.

Line 1
Line 2
Line 3
When am seeing the rich text field value with the created record it is displaying properly with line by line.

But if I assign this field value to page block table column it is coming as a paragraph instead of line by line.

Line1 Line2 Line3
Also am using a div tag inside of apex column to show/hide the rich text field value based on the user clicks.If user clicks first column the second column will be shown/hidden.

So what I need do to display this rich text field value line by line...Is there any way to make it work...

Any help would be appreciated.
I have to create a Visualforce page and attach that LINK in Email Template to send for my Higher Official ( say XXX ). 
Now when Mr.XXX clicks on the link which I sent, He should have access to EDIT that page. But Salesforce generally not allows that,is that right? 
If I am wrong, give me a solution. 

Thanks in advance :)
Hi All,  I have a requirement to show object's records in nested-accordian view.. It goes Like Customer(Parent) > Customer Product(Child for Customer) > Suites (Child for Customer Product)

Initially I used Accordian, but I was not able to go third-level.. So, I used lightning:tree for this purpose.. But, with this, I cannot get Id of the record.. Can anyone help with this? 

CMP: 
<aura:component controller="TreeController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="items" type="Object"/>
    <lightning:tree items="{! v.items }" onselect="{!c.handleSelect}"/>
</aura:component>

JS
({
    doInit: function (cmp, event, helper) {
        var action = cmp.get("c.getTreeData");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.items', JSON.parse(response.getReturnValue()));
            }
            
        });
        $A.enqueueAction(action);
    },
    
    handleSelect: function (cmp, event, helper) {  
        
        var getId = event.getParam('name');
        console.log('>>> getName' + getId);
	},
    
 })




User-added image

Vignesh
Hi All, The link https://rajvakati.com/2018/11/13/navigate-to-component-using-lightningnavigation/ where Source Component passes parameters to Target and the parameters are visible in URL.. 

I am following the exact steps but its not passing parameters to mt Target Component, neither can I see any Parameters in URL.. Is there anything I am doing wrong? 

I have added the component in Account Details Page.. 

Source.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <lightning:navigation aura:id="navService"/>
    <aura:attribute name="pageReference" type="Object"/>
    <aura:attribute name="url" type="String"/>
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    <lightning:button label="Open Lightning Component" onclick="{!c.handleClick}"/>
    
</aura:component>
SourceController.JS
({
    init : function(cmp, event, helper) {
        var navService = cmp.find("navService");
        var pageReference = {
            
            "type": "standard__component",
            "attributes": {
                "componentName": "c__Target"    
            },    
            "state": {
                "firstName": "Test"  ,
                "lastName": "user"    
            }
        };
        cmp.set("v.pageReference", pageReference);
        var defaultUrl = "#";
        navService.generateUrl(pageReference)
        .then($A.getCallback(function(url) {
            cmp.set("v.url", url ? url : defaultUrl);
        }), $A.getCallback(function(error) {
            cmp.set("v.url", defaultUrl);
        }));
    },
    handleClick: function(cmp, event, helper) {
        var navService = cmp.find("navService");
        // Uses the pageReference definition in the init handler
        var pageReference = cmp.get("v.pageReference");
        event.preventDefault();
        navService.navigate(pageReference);
    }
})

Target.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:isUrlAddressable" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />

    <aura:attribute name="firstName" type="String" />
    <aura:attribute name="lastName" type="String" />
    <div>
        Full Name : {!v.firstName} + {!v.lastName}
    </div>
</aura:component>
TargetController.JS
({
    init: function(cmp, event, helper) {
        var pageReference = cmp.get("v.pageReference");
        cmp.set("v.firstName", pageReference.state.firstName);
        cmp.set("v.lastName", pageReference.state.lastName);
    }
})


Below is the URL which when I clicked from Account Page - without Parameters

User-added image

Thanks

Vignesh

I am facing "Error in $A.getCallback() [quickcon is not defined]" and not able to find whats the issue, can anyone help? 

Component
<aura:component implements="force:appHostable,force:hassObjectName,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" 
                controller="RatingVsAccount">
   
   <aura:attribute name="cons" type="Contact" />
    <aura:registerEvent name="quickcontact" type="c:QuickContactEvent"></aura:registerEvent>
                   
    
    <aura:attribute name="newContact" type="Contact" default="{'sobjectType': 'Contact',
                                                              'FirstName':'',
                                                              'LastName':'',
                                                              'Email':'',
                                                              'Phone':''
                                                              }"/>
    <div class="slds-col-grid">
         <lightning:input aura:id="fieldId"
                             required="true"
                             label="Last Name"
                             name="filename"
                          	 type="text"
                        	 message-when-value-missing="This field is mandatory"	
                             value="{!v.newContact.LastName}"/>
       
        <lightning:button label="save" onclick="{!c.savecontact}"/>
    </div>
</aura:component>

Controller
({
	savecontact : function(component, event, helper) {
		
       
   
        var action = component.get("c.save");
        
        
            var con = component.get("v.newContact");
            action.setParams({
                con : con,
                Accid : component.get('v.AccountId'),
            });
        
		action.setCallback(this, function(a) {
					   var state = a.getState();
						if (state === "SUCCESS") {
							var name = a.getReturnValue();
						   var CompEvent = component.getEvent('quickcontact');
											   CompEvent.setParams({ quickcon, name});
											   
											   CompEvent.fire();  
							}
						});
		$A.enqueueAction(action)    
        },
	
})

Apex method
@AuraEnabled
    public static Contact save(contact con, string Accid)
    {
        
        con.AccountId = Accid;
        
        insert con;
        system.debug('>>> con' + con);
        return con;
        
    }
Event
<aura:event type="COMPONENT" description="Event template" >
   <aura:attribute name="quickcon" type="Contact"></aura:attribute> 
</aura:event>

Many Thanks for your help
 
Hi, I need to write a valdation rule for below scenario, 
Two Objects -- Eg, Accounts and Contacts. Contacts has a picklist called "Type" (values - 'Business' , 'Professional')..
I have a vf page where i can enter Account details, (multiple)Contacts and save all at one go.. Now the requirement is, if I save more than one contact, Type should be same - means, it should be either Bussiness or Professional for all contacts.. 
Is it possible to achieve this using ONLY vaidation rule (i cant write trigger for some reasons).?
 
Hello, 

I have to bulk insert in two objects which are parent and child. I have mapped parent's external id to child records.

I'm calling batch apex from normal class which inserts both. But Child records cant able to find parent External ID as it runs in parallel instead of one after one. 

Error : System.DmlException: Upsert failed. First exception on row 0; first error: INVALID_FIELD, Foreign key external ID
public static void saveFile()
     {         
              Try
                {                                                
                        if(FinalTarList.size()>0)  // Parent
                         {
                         SPL_BatchImportGild splTar = new SPL_BatchImportGild(FinalTarList); // should execute first
                         Database.executeBatch(splTar,200);
                         success = true;
                         }
                        
                        if(FinalcycdetCopy.size() > 0)
                            {
                             SPL_BatchImportGild splTarDet = new SPL_BatchImportGild(FinalcycdetCopy); // should execute after parent Insertion. 
                             Database.executeBatch(splTarDet,200); 
                            }                            
                 }
                       
          }

Is there a way to achieve this.? please suggest me if there are alternatives. 

Thanks 
Vignesh

Hello, 

I am importing large sets of Data using Batch Apex from visualForce page. I have collected the list value from Class and calling batch apex just to do DML. 

Below is my code, 

Calling from class : 
SPL_BatchImportGild splTar = new SPL_BatchImportGild(FinalTarList);
Database.executeBatch(splTar);

Batch:

global class SPL_BatchImportGild implements Database.Batchable<SObject> , Database.Stateful 
{
global SObject[] queue; // = new list<Cycle_Plan_Target_vod__c>();
    
    global SPL_BatchImportGild(SObject[] recs)
    {
        queue=recs;
    }
    
    public static SObject[] start(Database.BatchableContext context) {
    {
        // need to pass the Queue value to execute. But showing error message 'Variable does not exist: queue'.
    }
    
    global static void execute(Database.BatchableContext context, SObject[] records) {
        insert records;
    }
    gloBal void finish(Database.BatchableContext context) 
    {
        
    }

What could be the reason for this.? 

Thanks 

Vignesh

Hello,

I have a VisualForce page from which I'm loading some Data , Validating and Saving it to SF. While processing this i need to show Loading icon. I've tried this with the help of some forums but no luck. 
 
<apex:pageBlockSection id="pbs">
         <apex:pageBlockSectionItem >
            <apex:outputLabel value="Select Object"/>
         </apex:pageBlockSectionItem>  
       
         <apex:pageBlockSectionItem >
             <apex:selectList size="1" value="{!Objselected}" >
                <apex:selectOptions value="{!ObjList}"/>
             </apex:selectList>
         </apex:pageBlockSectionItem> 
         
         <apex:pageBlockSectionItem >
             <apex:outputLabel value="Select File"/>
         </apex:pageBlockSectionItem>
         
         <apex:pageBlockSectionItem >
               <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />          
         </apex:pageBlockSectionItem>
                           
          <apex:pageBlockSectionItem ></apex:pageBlockSectionItem> 
          
         
          
          <apex:pageBlockSectionItem id="pbsi">
             <apex:actionRegion id="area51" renderRegionOnly="false">
             <apex:commandButton action="{!ReadFile}" value="Validate File" id="theButton" disabled="{!vbutton}" status="spinnerStatus" rerender="pbsi"  /> 
             <apex:commandButton action="{!SaveFile}" value="Save" id="sButton"  disabled="{!sbutton}" status="spinnerStatus" rerender="form" /> 
            </apex:actionRegion>    
              
          </apex:pageBlockSectionItem> 
</apex:pageBlockSection>

When I use rerender, parameters are not passed to controller. Is there a way to overcome this.? 

Thanks
Vignesh
Hi,

I have a Two picklist fields A and B. both are picklist fields. I created a field dependency where "A" is a controlling and "B" is dependent.

I am adding more than 400-500 values in "A" which is not possible because of limitation of 300 values in SF. Is there any alternative ways? Help plz.

will SF increase the count if I Raise a CASE?

Thanks in Advance
Hi,

I have written a test class for getting History Records for the Purticular field. but it shows 'Null'. I have tried from some links but all will give the same result. Am i wrong somewhere?
 
public class batchDateplacedbackoncallTest
{
    public static Testmethod void mytest()
    {      
        VA_Matching__c vaMatchRec = new  VA_Matching__c(Client__c = accobj.id,status__c='Available',
                                                         VA__c = vaRec.id,
                                                         Date_added_to_On_Call_List__c=Date.parse('1/1/2015')
                                                         );
    insert vaMatchRec;
    vaMatchRec.status__c='Placed- Part time';
    update vaMatchRec;
    vaMatchRec.status__c='Available';
    update vaMatchRec; 

    List<VA_Matching__History> histList=new List<VA_Matching__History>();
     VA_Matching__History hist=new VA_Matching__History(Field='Status__c');
     histList.add(hist);
        
      List<String> results=example.processRows(histList);
     System.assertEquals(1, results.size());
     System.assertEquals('Name|null|null', results[0]);  
 }
}

 public List<VA_Matching__History> queryDatabase(id vaId)
    {
        return [select Id, OldValue, NewValue, Field, CreatedBy.Name 
                from VA_Matching__History
                where ParentId=:vaId order by createddate desc limit 1];
    }
   
     public List<String> ProcessRows(List<VA_Matching__History> historyList)
    {
        List<String> results=new List<String>();
        for (VA_Matching__History hist : historyList)
        {
            String field=hist.field;
            Object oldValue=hist.oldValue;
            Object newValue=hist.newValue;

            results.add(field + '|' + oldValue + '|' + newValue);
        }

        return results;
    }

Thank you so much.
 
Hi,

I am trying to get all the selected records from data table using Onchange function, but got the error, where am i making mistake?

VF:
<apex:dataTable value="{!wrapPriceList}" var="pdWrap" columnswidth="50px,50px" cellpadding="4" border="1" align="center" id="reRenderPbId">
                 <apex:column >
                           <apex:facet name="header">
                             <apex:inputCheckbox >
                                <apex:actionSupport event="onclick" action="{!getselected1}" onsubmit="selectAllCheckboxes(this,'inputId')" rerender="inputId"/>
                             </apex:inputCheckbox> 
                           </apex:facet>
                        <apex:inputCheckbox value="{!pdWrap.selected}" id="inputId">
                            <apex:actionSupport event="onclick" action="{!GetSelected1}" rerender="false"/>
                       </apex:inputCheckbox>          
                 </apex:column>   
                  <apex:column headerValue="Operating Model"><apex:outputtext value="{!pdWrap.pds.Name}" /></apex:column> 
    </apex:dataTable>

Controller :
public class QuoteController{
public List<Price_details__c> prc;
public List<Price_details__c> selectedprd=new List<Price_details__c>();
public list<price_details__c> getselected1;
public Boolean rendcart{get;set;}
public price_details__c price{get;set;}
public Price_details__c SearchCriteria{get;set;}
public List<wrapPrice> wrapPriceList{get;set;}
public List<Price_details__c> wrapPriceList2{get;set;}
public opportunity opp{get;set;}
public String cid = ApexPages.currentPage().getParameters().get('id');
public QuoteController(ApexPages.StandardController controller) 
         { 
           SearchCriteria = new Price_details__c();
           prc= new list<Price_details__c>();
           region = false;
           typef = false;          
         } 

public void filterapp()
{
       godis=true;
       wrapPriceList = new List<wrapPrice>();   
      if(SearchCriteria.Operating_Model__c!=null && Quantity!=null && SearchCriteria.Region__c!=null && typeSelected==null)
      {
          for(Price_Details__c pd: [SELECT Id,Operating_Model__c,Buying_Price__c,Type__c,MSRP__c, Name FROM Price_details__c WHERE Operating_Model__c =: SearchCriteria.Operating_Model__c and QuantityStart__c<=:Quantity 
            and QuantityEnd__c>=:Quantity and region__c=:SearchCriteria.region__c ])
            {
            wrapPriceList.add(new wrapPrice(pd));
            }
      }  
     }    
    system.debug('>>>wrapPriceList'+wrapPriceList);  
 }
 
 
 public pagereference getSelected1() 
{
    system.debug('>>>wraps'+wrapPriceList); // here i got all records 
    for(wrapPrice wrapx:wrapPriceList)
    if(wrapx !=null && wrapx.selected==true )
    {
      system.debug('>>>wraps'+wrapx); // here i got the purticular selected record
      wrapPriceList2.add(wrapx.pds);  // Error at this line 
    }
    return null;  
}
public class wrapPrice {
        public Price_Details__c pds {get; set;}
        public Boolean selected {get; set;}
 
        public wrapPrice(Price_Details__c pd) {
            pds = pd;
            selected = false;
        }
}
}

Thanks in advance.
I need clarification on below things which are confusion lot,

1) How many Queries we can do in Trigger? (??)
2) How many Queries we can do in a Apex Class? (150??)
3) How many DMLs we can do in Trigger for an instance? (??)
4) How many DML we can do in class for an instance? (50k??)
5) how many records will be retrieved in a single query in Apex class?
6) how many records will be retrieved in a single query in Trigger?

** In trigger we can do 100soql per cycle. (What does it mean?)

if there is a query like 
SELECT id,name from Account where status='Active'; // consider if there are 7000 active records
will it retrieve all the 7000 records on next to query line?

I have seen somewhere that we can do 20 DML in Trigger for an Instance, another site its 150.. what is true?

Correct me if some questions are wrong, it really confusing a lot :))

Thanks folks.
Hi frnz, I need a logic for below situation in TRIGGER.

** VA is a parent object which has Cancellation as Child that has three records with 'start date' and 'end date' fields.
We need to calculate total days between Start date and End date in three records, then store it in VA.

** Now if those three records have any Overlapping days, we should not count that. For Example.......

Record1 - start date = jul 01 2015, end date = Jul 31 2015  = 31 days
Record2 - start date = Jul 10 2015, end date = Jul 20 2015  = 0 Dates were overlapped by the others
Record3 - start date = Jun 21 2014, end date = Jul 05 2015 = 10 days (Jun 21 - Jun 30, july 01 - july 05 overlapped by the others)
Record4 - start date = Jun 01 2014, end date = Jun 05 2014 = 5 days
total of 46 days

How to achieve this?
Thanks. :))
 
Hi guyz,

I have written a Test class for Batch clas with the help of google. but I could able to cover only 14%. In debug log My Execute method was not covered. Any help?

My Class :
global class batchVATenureUpdate implements Database.Batchable<AggregateResult>
{
    global Iterable<AggregateResult> start(Database.BatchableContext info)
    {
        return new AggregateVAtenureIterable();       
    }
    
    global void execute(Database.BatchableContext info,  List<AggregateResult> accva )
    {
        List<Our_VA__c> ourvalist = new List<Our_VA__c>();
        map<string,Decimal> mapva = new map<string,Decimal>();
        integer i;
        
        for(AggregateResult av : accva)
        {     
            mapva.put(string.valueof(av.get('VA__c')),(Decimal)av.get('daycount'));         
        }
        map<Id,Our_VA__c> ourva = new map<Id,Our_VA__c>();  
        List<Our_VA__c> ourva1 = new List<Our_VA__c>();
        ourva1 = [select id,VA_Tenure_Active_Clients__c,VA_Tenure_Cancellation__c,Account_Number__c,BonusCount__c,Name,ClientCount__c,LoanCount__c,test__c from Our_VA__c];// where id IN:vaids];
       
        for(Our_VA__c a : ourva1)
        {            
            ourva.put(a.id,a);
            string idva = string.valueof(a.id);
            if(mapva.containskey(idva) == true)
            {
                a.VA_Tenure_Active_Clients__c = mapva.get(idva);
                ourvalist.add(a);
            }
        } 
        update ourvalist;              
    }   
    global void finish(Database.BatchableContext BC)
    {
    }
}

Test class :
@isTest

public class TestvaTenureactiveclients1
{

 public static testmethod void batchVATenureUpdate()
    {
         
     our_va__c v1 = new our_va__c();
     v1.name = 'v1';
     insert v1;
     
     Account_VA__c accva = new Account_VA__c();
     accva.Account__c = a1.id;
     accva.VA__c = v1.id;
     accva.Status__c = 'Active';
     accva.Type__c = 'Full Time';
     accva.VA_start_Date__c = Null;
     insert accva;
     
     Test.StartTest();
     list<account_va__c> accvax=new list<account_va__c>();
     accvax.add(accva);
     upsert accvax;
     
     list<our_va__c> ourvax=new list<our_va__c>();
     ourvax.add(v1);
     upsert ourvax;    
     
     batchVATenureUpdate objBatch = new batchVATenureUpdate();
     Database.executeBatch(objBatch);
     Test.StopTest();
    }
}

Thanks,
@future(callout=true)
       public static void ListCallAllowanceBalanceRequest()
      {  
		accx=[Select id,Name,Billing_Date__c,AccountNumber__c,Client_ID__c,Start_Date__c,End_Date__c,Bill_Hold__c,Bill_Talk__c,Bill_Transfer__c,Bill_Ring__c,Call_Rounding__c from Account WHERE To_Be_Run_Today__c = 'True'];
        for(Account accy:accx)
        {
        wrap.StartDate=accy.Start_Date__c; 
        wrap.EndDate=accy.End_Date__c; 
        wrap.ClientId=accy.Client_ID__c;
        wrap.BillHold = Boolean.ValueOf(accy.Bill_Hold__c);
        system.debug('****billhold****'+wrap.BillHold);
        wrap.BillTalk = Boolean.ValueOf(accy.Bill_Talk__c);
        wrap.BillTransfer= Boolean.ValueOf(accy.Bill_Transfer__c);
        wrap.BillRing = Boolean.ValueOf(accy.Bill_Ring__c);
        wrap.RoundCalls = accy.Call_Rounding__c;
        wrap.CustomerName= autx.Customer_Name__c;
        wrap.UserName = autx.User_Name__c;
        wrap.Password = autx.Password__c;
        String jsonBody = json.serialize(wrap);
        system.debug(jsonBody);
        HttpResponse res;
        HttpRequest req = new HttpRequest();
        req.setEndPoint('https://telassistant.hostedsuite.com/api/json/reply/ListCallAllowanceBalanceRequest'); 
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');
        req.setBody(jsonBody);
        Http http_req = new Http();
        res = http_req.send(req);
        System.Debug(res.toString());
         try 
        {
            res = http_req.send(req);
            System.debug('>>>>>res'+res.getBody());
            string httpresp = res.getBody();
         deserialize1 qw= new deserialize1();
         qw=(deserialize1)JSON.deserialize(httpresp,deserialize1.class);
         system.debug('***userid***' + qw.NumCalls);
         listacc1.Num_calls__c =qw.NumCalls;
         kk.add(listacc1);
         system.debug('NumCalls'+listacc1.Num_calls__c);
        }
        catch(System.CalloutException e) 
        {
            System.debug('Callout error: '+ e);
            System.debug(res.toString());
        }
           update kk;
      }
     }

public class deserialize1
       {
             public boolean Authenticated {get; set;}
             public string UserType {get; set;}
             public string body  {get; set;}  
             public string Name {get; set;}  
             public string CompanyName {get; set;}
             public string userId {get; set;}  
             public string ClientId {get; set;}  
             public string PhotoUrl {get; set;} 
             public Integer NumCalls{get; set;} 
       }


Hi,
I have written a call out function like above. It shows the following Error in debug log

Any help? What does it mean?

Thanks frnz.
Hi,
I have written Javascript to check all records using Checkbox, Plz see the snapUser-added image

Its working well but after a while it goes like below snap,

User-added image

My VF
<apex:page standardController="Payment__c" extensions="paymentController" id="page1">
<script>
function checkAll(cb,cbid)
{
    var inputElem = document.getElementsByTagName("input");                    
    for(var i=0; i<inputElem.length; i++)
    {            
        if(inputElem[i].id.indexOf(cbid)!=-1){                                       
        inputElem[i].checked = cb.checked;
        }
    }
}
function checkAll1(cb,cbid)
{
    var inputElem = document.getElementsByTagName("input");                    
    for(var i=0; i<inputElem.length; i++)
    {            
        if(inputElem[i].id.indexOf(cbid)!=-1){                                       
        inputElem[i].checked = cb.checked;
        }
    }
}
<apex:pageblockSection title="Payslip Selection" columns="1" rendered="{!paysec}" id="pb1s2">
            <apex:dataTable value="{!payslip}" var="pay" columnswidth="50px,50px" cellpadding="4" border="1" align="center" id="datatable">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!Getselected}" onsubmit="checkAll(this,'checkedone')" rerender="checkedone"/>
                        </apex:inputCheckbox>                  
                    </apex:facet>  
                    <apex:inputCheckbox value="{!pay.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="Selected_PBS1"/>
                    </apex:inputCheckbox>
                </apex:column> 
                <apex:column headervalue="Payslip Name" value="{!pay.payslp.Name}" />
                <apex:column headervalue="VA Name" value="{!pay.payslp.Name__c}" />
                <apex:column headervalue="Bank Account" value="{!pay.payslp.Account_Number__c}"/>
                <apex:column headervalue="Bank Account" value="{!pay.payslp.Account_Number__c}"/>                
                <apex:column headervalue="Total Pay in Dollar" value="{!pay.payslp.Total_Pay_for_this_period__c}"/> 
                <apex:column headervalue="Total Pay in Peso" value="{!pay.payslp.Total_Pay_in_Peso__c}"/>                                        
            </apex:dataTable>
 </apex:pageblockSection>
Hope you can help,

Thanks.
 
public with sharing class legalactionsubmission
{   
    public legal_action__c legact{get;set;}
    public String currentid= ApexPages.currentPage().getParameters().get('id');
    public boolean savedis{get;set;}
    public string idcurr;
    
    public legalactionsubmission(ApexPages.StandardController controller)
    {
        savedis=false;
        legact=new legal_action__c();
        legact=(legal_action__c)controller.getrecord();
        system.debug('>>>legact'+legact);
        this.idcurr=ApexPages.currentpage().getparameters().get('id');
        if(currentid!=null && currentid!='')
        {
          //Legal_Action__c a = new Legal_Action__c();
          legact=[select id,submit_done__c,entry_by__c from legal_action__c where id=:currentid];
          if(legact.submit_done__c==true)
          {
           savedis=true;
           String msg = 'Thank you for Submitting.';
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,msg));
          }
        }  
    }
    
    public pagereference save()
    {
     savedis=true;
     legal_action__c leg= new legal_action__c();
     //legal_action__c legact= new legal_action__c();
     system.debug('>>>legact'+legact);
     leg=[select id,Name_of_Client__c,submit_done__c,Name_of_VA__c,entry_by__c,reviewed_by__C,Summary_of_Situation__c,Attachment_summary__c from legal_action__c where id=:currentid];
     if(leg.submit_done__c==false)
     {
       leg.Name_of_Client__c=legact.Name_of_Client__c; // Error Line 
       leg.submit_done__c=true;
       leg.Name_of_VA__c=legact.Name_of_VA__c;
       leg.entry_by__c=legact.entry_by__c;
       leg.reviewed_by__C=legact.reviewed_by__C;
       leg.Summary_of_Situation__c=legact.Summary_of_Situation__c;
       leg.Attachment_summary__c=legact.Attachment_summary__c;
       update leg;
       system.debug('>>>>entryby'+leg.entry_by__c);
     }
     
        pagereference ref;
        ref = new pagereference('/apex/legal_action_final_reviewe?id='+legact.id);
        ref.setredirect(true);
        return ref;
    }
}
Hi,
Can anyone help me for this, I know where it goes wrong..  I have queried correctly but still its showing the error.. Any mistakes here?
 
Hi,

I got a task like, I need to sort a field from the table.. written the Dynamic query for it and faced the issue that i mentioned,

Error is in For Loop
 
public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
    }
    public String sortField {
    get  { if (sortField == null) {sortField = 'Name'; } return sortField;  }
    set;
    }
  
 // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    getpayslip();}

public List<payslipwrapper> getpayslip()
    {
        Payslip__c myVariable = new Payslip__c(Payment_Status__c ='Paid');
        string status = myVariable.Payment_Status__c;
        string payrolldate = payment2.payroll_cycle_date__c;
        string year = payment2.payroll_cycle_year__c;
        soql='select id,Name,Name__c,PaymentStatus__c,Account_Number__c,Billing_Specialist__c,PayRoll_Cycle__c,Year__c,Total_Pay_for_this_period__c,Total_Pay_in_Peso__c,Payment_Status__c from Payslip__c where PaymentStatus__c !=';       
        for(payslip__c pay : Database.query(soql + status + ' and PayRoll_Cycle__c=:'+ payrolldate + ' and Year__c=:'+ year +' order by ' + sortField + ' ' + sortDir + ' Limit 999')) // Error At this  Line 
		 payslipList.add(new payslipwrapper(pay)); 
        if(payslipList.size()== 0)
        {
            // some codes
        }   
        return payslipList;
    }
 

 

Hi all,

I am trying to update all records through scheduling job daily. Records are not updating and throwing this error mesaage "A workflow or approval field update caused an error when saving this record. Contact your administrator to resolve it". Why i am getting this error message? how to resolve this error?

 

 

Thanks,

Vinod.