• Nayana K
  • ALL STAR
  • 6303 Points
  • Member since 2014
  • Software Engineer III
  • Walmart


  • Chatter
    Feed
  • 167
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 4
    Questions
  • 885
    Replies
Hi. I return custom object to js by callback, then take it in aura component like ​​​​​.
<aura:attribute name="customObj" type="customObj__c[]"/>
Also i have list of custom fields in this object (endless) 
<aura:attribute name="listObjKeys" type="String" default='["Field1__c","Field2__c","Field3__c","Field1__c","Date__c"]'/>
How i can iterate through my object to display values by field. I try this, but with no result 
<aura:iteration items="{!v.customObj}" var="co">
  <aura:iteration items="{!v.listObjKeys}" var="keys">
    <tr>{!keys}</tr>
  </aura:iteration>
</aura:iteration>
I have created a flow and a lightning component which run on new.
The flow creates a record and I want at the end of the flow to be redicted inside the record which was  just created.
In the flow I store the new record's id as {!recordId}

The controller is:
 
({
    init : function (component) {
        // Find the component whose aura:id is "flowId"
        var flow = component.find("flowId");
        // In that component, start your flow. Reference the flow's Unique Name.
        flow.startFlow("Internal_Requests");
        
    },
handleStatusChange : function (component, event) {
    
    if(event.getParam("status") === "FINISHED") {
       var navEvt = $A.get("e.force:navigateToSObject");
            navEvt.setParams({
                "recordId": "??????????",
                "slideDevName": "related"
            });
            navEvt.fire();
         }
      },
})


What do i set at the record Id though to be redicted in the new record?

All the threads I have found, provide specific Id which of course does not apply to our needs.

Hello Everyone,

I don't know why the bloc after if is not executed even the formula is true

<aura:if isTrue="{!reclamation.Type__c == !v.category}">

when I do display the value of {!reclamation.Type__c} and {!v.category} the two values are similar

NB: the first value is coming from the object and the second value is coming from the picklist, and when I remplace the {!v.category} by a fixe value exemple 'Manque' the if condition works and the bloc after if is executed

*******
component:
<aura:component
  implements="flexipage:availableForRecordHome,force:hasRecordId"
  controller="ReclamationListController"
  access="global"
>
  <!-- Handler to call function when page is loaded initially -->
  <aura:handler name="init" action="{!c.getReclamationsList}" value="{!this}" />
  <!-- List of contacts stored in attribute -->

  <aura:attribute name="reclamationList" type="List" />
  <aura:attribute name="type" default="true" type="Boolean" />
  <aura:attribute name="category" default="Excédent" type="String" />

  <!-- Lightning card to show contacts -->
  <lightning:card title="Reclamations">
    <!-- **************************** -->

    <lightning:select
      aura:id="selectItem"
      name="selectItem"
      label="selectItem"
      onchange="{! c.updateSelect }"
    >
      <option value="">choose one...</option>
      <option value="Excédent">Excédent</option>
      <option value="Retard">Retard</option>
      <option value="Manque">Manque</option>
      <option value="Autres">Autres</option>
    </lightning:select>

    <!-- **************************** -->
   

    <!-- Body of lightning card starts here -->
    <div class="slds-p-around_small">
      <div class="slds-grid slds-wrap">
        <aura:iteration items="{!v.reclamationList}" var="reclamation">
          <aura:if isTrue="{!reclamation.Type__c == !v.category}">
            <div
              class="slds-col slds-size_1-of-3 slds-p-around_small slds-box slds-theme_shade slds-theme_alert-texture"
            >
              <a href="javascript:void(0);"> </a>

              <lightning:card
                title="{!reclamation.Name}"
                footer="{!reclamation.Type__c}"
                iconName="standard:contact"
              >
                <span class="slds-avatar">
                  <aura:if isTrue="{!reclamation.Type__c == 'Excédent'}">
                    <img
                      alt="Logo"
                      src="{!$Resource.Plus}"
                      title="User avatar"
                    />
                    <aura:set attribute="else">
                      <img
                        alt="Logo"
                        src="{!$Resource.Minus}"
                        title="User avatar"
                      />
                    </aura:set>
                  </aura:if>
                </span>

                <aura:set attribute="actions">
                  <lightning:button
                    name="{!reclamation.Id}"
                    label=" Details"
                    variant="Neutral"
                    onclick="{!c.doRedirect}"
                  />
                </aura:set>

                <p class="slds-p-horizontal_small ? ' dix '">
                  {!reclamation.Description__c}
                </p>
                <tr
                  class="{!reclamation.Type__c == 'Excédent' ? ' exe ' : 
              reclamation.Type__c == 'Manque' ? ' mqe ' : 
              reclamation.Type__c == 'Retard' ? ' rtd ' :         
              reclamation.Type__c == 'Autres' ? ' oth ' : ''}"
                >
                  <td data-label="Date:"> {!reclamation.Date__c} </td>
                </tr>
              </lightning:card>
            </div>
          </aura:if>
        </aura:iteration>
      </div>
    </div>
    <!-- Lightning card actions -->
    <aura:set attribute="actions">
      <!-- New button added -->
      <lightning:button label="New" onclick="{!c.newReclamation}" />
    </aura:set>
  </lightning:card>
</aura:component>
*******************************
Controller:

({
  // Function called on initial page loading to get contact list from server
  getReclamationsList: function(component, event, helper) {
    // Helper function - fetchRecalamations called for interaction with server
    helper.fetchReclamations(component, event, helper);
  },

  updateSelect: function(component, event, helper) {
    //return the selected value

    var cat = component.find("selectItem").get("v.value");
    alert(cat);
    component.set("v.category", cat);
  },

  doRedirect: function(component, event, helper) {
    var eventSource = event.getSource();
    var id = eventSource.get("v.name");

    var navEvt = $A.get("e.force:navigateToSObject");
    navEvt.setParams({
      recordId: id,
      slideDevName: "detail"
    });
    navEvt.fire();
  },

  // Function used to create a new Reclamation
  newReclamation: function(component, event, helper) {
    // Global event force:createRecord is used
    var createReclamation = $A.get("e.force:createRecord");
    // Parameters like apiName and defaultValues are set
    createReclamation.setParams({
      entityApiName: "Reclamation__c",
      defaultFieldValues: {
        Contact__c: component.get("v.recordId")
      }
    });
    // Event fired and new contact dialog open
    createReclamation.fire();
  }
});

thanks for your Help
Hi all,
I am struggling to figure out how to display an avatar image  depenting to custom object field value, we have reclamation custom object with lookup relation with contact and I need to display all relamations related to a contact in lightning component under contact and for each reclamation I need to display a static ressource avatar image depending to the value stored on type__c, see bellow all config:

********************
Component

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" controller="ReclamationListController" access="global" >
    <!-- Handler to call function when page is loaded initially -->
    <aura:handler name="init" action="{!c.getReclamationsList}" value="{!this}" />
    <!-- List of contacts stored in attribute -->
    
    <aura:attribute name="reclamationList" type="List" />
    <aura:attribute name="type" default="true" type="Boolean"  />
    
    <!-- Lightning card to show contacts -->
        <lightning:card title="Reclamations">
    
    <!-- **************************** -->
    <!-- Body of lightning card starts here -->
    <div class="slds-p-around_small">
        <div class="slds-grid slds-wrap">
            <aura:iteration items="{!v.reclamationList}" var="reclamation">
                
                <span class="slds-avatar">
                <aura:if isTrue="{!reclamation.Type__c} = Retard">                                                                                                      
                  <img alt="Logo" src="{!$Resource.plus}" title="User avatar" />
                      <aura:set attribute="else">
                           <img alt="Logo" src="{!$Resource.Minus}" title="User avatar" />
                        </aura:set>

                    </aura:if>                    
               </span>       
                
                <div class="slds-col slds-size_1-of-3 slds-p-around_small slds-box slds-theme_shade slds-theme_alert-texture">
                    <a href="javascript:void(0);">                   
                       
</a>            
                   
                    <lightning:card title="{!reclamation.Name}" footer="{!reclamation.Type__c}" 
                                    iconName="standard:contact" >
                        <aura:set attribute="actions">
                            <lightning:button name="{!reclamation.Id}" label=" Details" variant="brand"
                                              onclick="{!c.doRedirect}"/>
                        </aura:set>
                        <p class="slds-p-horizontal_small">
                            {!reclamation.Description__c} <br/> {!reclamation.Date__c}
                        </p>
                                          
                    </lightning:card>
                    
                </div>                                       
                
            </aura:iteration>
        </div>
    </div>       
        <!-- Lightning card actions -->
        <aura:set attribute="actions">
            <!-- New button added -->
            <lightning:button label="New" onclick="{!c.newReclamation}" />
        </aura:set>
    </lightning:card>
</aura:component>
/**********************

controller

({
    // Function called on initial page loading to get contact list from server
        getReclamationsList : function(component, event, helper) {
        // Helper function - fetchRecalamations called for interaction with server
                helper.fetchReclamations(component, event, helper);
                     
        },


    // Function used to create a new Reclamation
    newReclamation: function(component, event, helper) {
        // Global event force:createRecord is used
        var createReclamation = $A.get("e.force:createRecord");
        // Parameters like apiName and defaultValues are set
        createReclamation.setParams({
            "entityApiName": "Reclamation__c",
            "defaultFieldValues": {
                "Contact__c": component.get("v.recordId")
            }
        });
        // Event fired and new contact dialog open
        createReclamation.fire();
    }
})


////**************************

Helper

({
    // Function to fetch data from server called in initial loading of page
        fetchReclamations : function(component, event, helper) {
        // Assign server method to action variable
        var action = component.get("c.getReclamationList");
        // Getting the contact id from page
        var contactId = component.get("v.recordId");
 
        // Setting parameters for server method
        // 
        // 
           
        action.setParams({
            contactIds: contactId

        });

        // Callback function to get the response
        action.setCallback(this, function(response) {
            // Getting the response state
            var state = response.getState();
            // Check if response state is success
            if(state === 'SUCCESS') {
                // Getting the list of contacts from response and storing in js variable
                var reclamationList = response.getReturnValue();
                // Set the list attribute in component with the value returned by function
                component.set("v.reclamationList",reclamationList);
            }
            else {
                // Show an alert if the state is incomplete or error
                alert('Error in getting data');
            }
        });
        // Adding the action variable to the global action queue
        $A.enqueueAction(action);
        }    
})

Thanks for your help
 
Hi Everyone.

I am trying to dynamically create a nested Map based on an AggregateResult. The results are grouped by Product, Template and Transaction Type. Therefor I am trying to create a Map like this: Map<String, Map<String, Map<String, Decimal>>>

The first String, Map Combination is Product ID and a Map for all different associated Templates. The second Map contains all associated Templates for that particular Product and a Map with all Transaction Types associated to that particular Template. The Decimal is the actual amount of the transaction. 

I am fairly new to Apex and programming in general so I am still trying to learn a lot. This is what I came up with but based on the research I did over the weekend, it is wrong. I am just not able to translate what I found out to my use-case.
 
//HelperMap
        Map<String, Map<String, Map<String, Decimal>>> cmap = New Map<String, Map<String, Map<String, Decimal>>>();

        //Query
        AggregateResult[] groupedResults = ...
        
        For(AggregateResult ar : groupedResults){

            If(!cmap.containsKey(ar.get('brand'))){
                Map<String, Map<String, Decimal>> templateMap = New Map<String, Map<String, Decimal>>();
                cmap.put(ar.get('brand'), templateMap);
            }

            If(!templateMap.containsKey(ar.get('template'))){
                Map<String, Decimal> insideMap = New Map<String, Decimal>();
                templateMap.put('template', insideMap);
            }

            insideMap.put(ar.get('type'), ar.get('amount'));
            templateMap.put('template', insideMap);
            cmap.put(ar.get('brand'), templateMap);

        }

I censored the query because it contains company information. The 'brand', 'template' and 'type' are aliases. 
I have been configuring ligthning component and its gone well so far. However I am struggling to find out why the new component doesnt display information, we have reclamation custom objet with lookup relation with contact and I need to display all relamations related to a contact in ligthning component under contact, see bellow all config:

ReclamationListController.apxc
public class ReclamationListController {
        
    @AuraEnabled
    public static List<Reclamation__c> getReclamationList(List<Id> contactIds) {
                List<Reclamation__c> reclamationList = [SELECT Id, Name, Type__c, Description__c, Contact__c FROM Reclamation__c WHERE Contact__c in :contactIds];
        return reclamationList;
    }
}
**************************************************
ReclamationList.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" controller="ReclamationListController" access="global" >
    <!-- Handler to call function when page is loaded initially -->
    <aura:handler name="init" action="{!c.getReclamationsList}" value="{!this}" />
    <aura:attribute name="reclamationList" type="List" />
        <lightning:card title="Reclamations">
        <p class="slds-p-horizontal_small">       
            <aura:iteration items="{!v.reclamationList}" var="reclamation"> 
                <lightning:recordViewForm recordId="{!reclamation.Id}" objectApiName="Reclamation__c">
                    <div class="slds-box slds-theme_default">
                        <lightning:outputField fieldName="Name" />
                        <lightning:outputField fieldName="Type__c" />
                        <lightning:outputField fieldName="Description__c" />
                    </div>             
                </lightning:recordViewForm>
                <br />
            </aura:iteration>
        </p>

        <aura:set attribute="actions">
            <lightning:button label="New" onclick="{!c.newReclamation}" />
        </aura:set>
    </lightning:card>
</aura:component>
**************************************************************
ReclamationsListController.js

({

        getReclamationsList : function(component, event, helper) {

                helper.fetchReclamations(component, event, helper);
        },

    newReclamation: function(component, event, helper) {
        var createReclamation = $A.get("e.force:createRecord");
        createReclamation.setParams({
            "entityApiName": "Reclamation__c",
            "defaultFieldValues": {
                "Contact__c": component.get("v.recordId")
            }
        });
        createReclamation.fire();
    }
})

*****************************************
ReclamationsListHelper.js

({
        fetchReclamations : function(component, event, helper) {
        var action = component.get("c.getReclamationList");
        var contactId = component.get("v.recordId");
        action.setParams({
            contactIds: contactId

        });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS') {

                var reclamationList = response.getReturnValue();

                component.set("v.contactList",reclamationList);
            }
            else {
                alert('Error in getting data');
            }
        });
        $A.enqueueAction(action);
        }    
})


*********

Thank you for your halp
Hi,

I'm trying to make progress with Create a Namespace per the module "Package an Exchange App" of trailhead "AppExchange App Development" which should help me succeed with the Challenge exericise later;
User-added image

however, I'm not able to get to the Change Developer Settings section of the supposed Packages page that I'm not able to get to because Step 1 resulted in no "Packages" option for me to click. 

I see only "Installed Packages", "Package Manager", and "Package Usage".  Tried clicking closest option "Installed Packages" and doesn't look like it's the right option.  

Any help is appreciated.

Thanks, 
Tien.

PS Even tried with new Dev Org and same issue:
User-added image
Hi guys,

Why are VF pages not available to be displayed in Dashboard in Lightning?
Hi! 
I want to use/create an autocomplete textbox using Lightning Web Components. Particularly, I want an autocomplete textbox for looking up a PriceBookEntry2 so that I can add a product to an opportunity, on the same page as Opportunity. 
I see options for autocomplete textbox for Visual Force, for Aura Lightning. However, I can't find anything for Lightning Web Components. 

I do see Lightning-Input (https://developer.salesforce.com/docs/component-library/bundle/lightning-input/example), but I don't know how to make it an autocomplete type.

What's the best way to go about it?

The final result needs to be an opportunity form, where a person can add/edit/delete products on the same page. 
Hi everyone, i am new with Apex and i have a question.
I want to update the Contact object field location_boat__c and that the location__c fields of the Boat object be updated also be updated My test is incompleted. i want test my trigger UpdateLocationand i dont know how do it
the object Boat field name Contac__c have relationship lookup with the Contact (Object standard)
My test is wrong but i can not how resolve this problem
trigger UpdateLocation on Contact (after update) { if (trigger.isAfter
&& Trigger.isUpdate) {
     List<Boat__c> boats = new List<Boat__c>();
     for (Contact c : [
                 SELECT location_boat__c, (SELECT Id FROM Boats__r)
                 FROM Contact
                 WHERE Id = :trigger.new
             ]) {
         for (Boat__c b : c.Boats__r) {
             b.location__c = c.location_boat__c;
             boats.add(b);
         }
     }
     update(boats); }}
 
@isTest
public class PruebaBotes {
@isTest static void TestActualizar() {

            Boat__c b1  = new Boat__c(Name='bote uno' ,Price__c=20, Type__c='Velero', location__c='Argentina');
            Boat__c b2  = new Boat__c(Name='bote dos' ,Price__c=50, Type__c='Yate', location__c='Brasil');
            Boat__c b3  = new Boat__c(Name='bote tres' ,Price__c=125, Type__c='Catamaran', location__c='España');
            Boat__c b4  = new Boat__c(Name='bote cuatro' ,Price__c=700, Type__c='Velero', location__c='India');

            insert b1;
            insert b2;
            insert b3;
            insert b4;   

            Contact a1 = new Contact(Lastname='Pepe',  location_boat__c = 'Brasil');
            Contact a2 = new Contact(Lastname='Jose',  location_boat__c = 'Argentina');
            Contact a3 = new Contact(Lastname='Maria', location_boat__c = 'India');
            Contact a4 = new Contact(Lastname='Ana',   location_boat__c = 'Argentina');

            insert a1;
            insert a2;
            insert a3;
            insert a4;    

            Contact updateLocation;
            updateLocation = [SELECT location_boat__c FROM Contact WHERE location_boat__c = 'Argentina' LIMIT 1];
            updateLocation.location_boat__c = 'India';
            update updateLocation;

Test.startTest();
    Contact afterUpdate = [SELECT  location_boat__c FROM Contact WHERE 
    Id=:updateLocation.Id];
    System.assertEquals('India', afterUpdate.location_boat__c);

    Test.stopTest();


    }
    }

 
Hi All,
My requirement is update previous contact as non primary if new contact is primary..
Can you please help me what to write in below trigger. Thanks in advance.
 
Trigger updatePrimaryCheckbox2 on Contact(after insert, after update) {
   Map < Id, Contact > accConMap = new Map < Id, Contact > ();
   List < Contact > conList = new List < Contact > ();
   if (Trigger.isInsert || Trigger.isUpdate) {
    for (Contact cont: Trigger.New) {
     if (cont.AccountId != null && cont.IsPrimaryContact__c == true) {
      accConMap.put(cont.AccountId, cont);
     }
    }
   }
   for (Contact con: [select id, AccountId, IsPrimaryContact__c, Description from contact
     where accountid IN: accConMap.keyset()
    ]) {
    if (con != null && accConMap.containsKey(con.AccountId)) {
    // here logic
    // logic
     conList.add(con);
    }
   }
   update conList;
  }

 
Hello Ohana,
I use Lightning Out to integrate my LWCs on external sites.

My LWC displays contact records and works perfectly on my Salesforce app homepage.
User-added image

On an external site, my LWC is displayed but not the records.
User-added image
The code of the LWC and my application is available at this address:https://github.com/Nashle/lightningout/
The live is available at this address:https://nashle.github.io/lightningout/

Do I need to create an application connected with OAuth to allow GestUsers to access the application's data? And if so, how should it be configured to allow my LWC to display the data when it is hosted on a remote site?

Can you help me please ?
Dear Team ,

M working on REST API and i write following code . But m receiving error plz have a look on code and snapshot :
 
APEX Code:

public with sharing class AccountRest {
    
 
    
    public list<account> acc{get{
    
    	//Define http Request 
    	//append your Query to the base url
    	HttpRequest req = new HttpRequest();
        req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v47.0/query/?q=SELECT Id,Name,AccountNumber,Type FROM Account limit 10');
        req.setMethod('GET');
        
        //Get SessionId
        string autho = 'Bearer '+userInfo.getSessionId();
        req.setHeader('Authorization', autho);
        
        //Get Response
        Http http = new Http();
        HTTPresponse res= http.send(req);
        string response = res.getBody();
        
        //Deserialize obtained json response
        string str = '['+ response.substring(response.indexOf('records":[')+10,response.indexof(']}')) +']';
        acc = (list<Account>)JSON.deserialize(str,list<Account>.class);
        
        return acc;    
    }set;}
    
}

VF :

<apex:page controller="AccountRest">

   
	<apex:sectionHeader title="Accounts" subtitle="List View"/>
	<apex:pageBlock>
	
		<apex:pageBlockTable value="{!acc}" var="key">
		
			<apex:column>
				<apex:facet name="header">Account Name</apex:facet>
				<apex:outputLink value="/{!key.Id}">{!key.Name}</apex:outputLink>
			</apex:column>
			<apex:column value="{!key.AccountNumber}"/>
			<apex:column value="{!key.Type}"/>	
		
		</apex:pageBlockTable>
	
	</apex:pageBlock>

</apex:page>

User-added image
Hi, I have an existing formula that was working but no longer does because it is receiving an error that the forumla is too long. Can someone please help me with this forumal using CASE. 

IF(
AND(ISPICKVAL(Percent_Complete__c, "5%-9% Reviewed"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "10%-19% Initiated"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "20%-34%: Stage 1"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "35%-49%: Stage 2"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "50%-64%: Stage 3"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "65%-74%: Stage 4"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "75%-94%: Stage 5"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "95%-99%: Stage 6"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 0)), "On Target",
IF(AND(ISPICKVAL(Percent_Complete__c, "5%-9% Reviewed"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "10%-19% Initiated"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "20%-34%: Stage 1"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "35%-49%: Stage 2"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "50%-64%: Stage 3"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "65%-74%: Stage 4"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "75%-94%: Stage 5"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "95%-99%: Stage 6"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c = 1)), "On Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "5%-9% Reviewed"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "10%-19% Initiated"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "20%-34%: Stage 1"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "35%-49%: Stage 2"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "50%-64%: Stage 3"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "65%-74%: Stage 4"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "75%-94%: Stage 5"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Percent_Complete__c, "95%-99%: Stage 6"), ISPICKVAL (Status__c, "In Progress"),(Days_Late__c > 1)), "Red Alert",
IF(AND(ISPICKVAL(Status__c, "Not Started"),(Days_Late__c >= 1)), "Red Alert",

"")))))))))))))))))))))))))

Your help is greatly appreciated. I have to urgently change this formula.
The ultimate goal is to be able to iterate over an array in a Lightning web component to show internal reviews about our vendors. There would be at least three levels: Super Category, Category, Review (maybe even four: Super Category, Category, Vendor, Review), so that the root lists are not repeated in the display. For example:

Super Category 1
-Category A
--Review 00
--Review 01
-Category B
--Review 02

Super Category 2
-Category C
--Review 03

Super Category is Parent over Category, which is parent over Review. Review also has references to Super Category. 

ultimately the array might look like this:
superCategories = [
        {
            Name: 'Additions',
            Categories: [
                {
                    Name: 'Bathroom Additions',
                    Reviews: [
                        {
                            Vendor: 'Jay at Pritches Closets',
                            Rating: 5,
                            Comment: 'this is the comment',
                            Phone: '8005551234'
                        }
                    ]
                },
                {
                    Name: 'Kitchen Additions',
                    Reviews: [
                        {
                            Vendor: 'Phil Dunphy',
                            Rating: 4,
                            Comment: 'this is the comment',
                            Phone: '8005551234'
                        }
                    ]
                }
            ]
        }
    ];

What is the best way to accomplish this? In the Controller or the .js of the component? And how?
I am using Email Services and I'm trying to extract field values (First Name, Last Name, Email, Phone, etc.) from the body of the email. Both the sender address and the subject do not contain the information I need.


In my class, I was able to isolate the the text of the email by using the following: 
String emailText = email.plainTextBody;


But I am struggling using String methods to isolate and get the field values from the text. 


Here's an example of the text I have to work with from the body of the email:

"
Requested by: John Doe
johndoe@example.com
Phone: 5555555555
Address of site: 123 Main St, Anywhere CA 12345
Electric Spend: 100 per month
Utility Company: PacifiCorp
Additional information: System Size (Kw): 7.76
Roof Type: Shingles
Roof Pitch: Slight
Shading: Shaded (can improve)
Credit Score: Over 680 Estimate
"
 

Any help is greatly appreciated! Thank you!
I am new to lightning . I am getting the below error

"This page has an error. You might just need to refresh it.
Error in $A.getCallback() [Component is not defined]
Callback failed: apex://getAccountList/ACTION$getAllAccounts
Failing descriptor: {c:AccList}"

My Code:
****************Apex class****************
public class getAccountList {
    @AuraEnabled
    public static List<Account> getAllAccounts(){
        return[select Id,Name,Type,Phone from Account ];
    }
     @AuraEnabled
    public static List<Account> getFilterAccounts(){
        return[select Id,Name,Type,Phone from Account where Type='Prospect'];
    }
}
************COMPONENT************************
<aura:component controller="getAccountList" >
    <aura:attribute name="AccList" type="List" />
    <aura:attribute name="PaginationList" type="Account[]" />
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:attribute name="Pagesize" type="Integer" default="10" />
    <aura:attribute name="Totalsize" type="Integer" />
    <tr><ui:inputSelect aura:id="records" >
        <ui:inputSelectOption text="10" value="10"/>
        <ui:inputSelectOption text="20" value="20"/>
        <ui:inputSelectOption text="30" value="30"/>
    </ui:inputSelect></tr>
    <table>
        <thead>
            <th>Id</th>
            <th>Name</th>
            <th>Phone</th>
            <th>Type</th>
        </thead>
     <tbody>
            <aura:iteration items="{! v.AccList}" var="Acc" >
                <tr>
                    <td>{! Acc.Id}</td>
                    <td>{! Acc.Name}</td>
                    <td>{! Acc.Phone}</td>
                    <td>{! Acc.Type}</td>
                    <td><c:Menu testRecord="{! Acc.Id}"/></td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>
********************Controller*******************
({
    doInit : function(component, event, helper){
        helper.callServerMethod(component,"c.getAllAccounts","v.AccList");    
       
    }

})
*******************Helper*****************************
({
    callServerMethod : function(component,methodName,attributeName) {
    var Pagesize = component.get("v.Pagesize");
    var methodRef = component.get(methodName);
        methodRef.setCallback(this,function(response){
            if(response.getState()=="SUCCESS"){
                component.set(attributeName,response.getReturnValue());
            }else{
                alert("Problem in method call");
            }
            Component.set("v.Totalsize",component.get(methodName).length);
            var PaginationList = [];
            for(var i=0;i<Pagesize;i++)
            {
                PaginationList.push(response.getReturnValue()[i]);
            }
            component.set("v.PaginationList",PaginationList);
        });
        $A.enqueueAction(methodRef);
    }    
})
I've got a string like so "The_quick_brown_fox_jumps_over_the_lazy_dog"

I want to add a space every 10 characters to it only if those 10 characters don't alreay have a space

so I'm hoping for a result like this
"The_quick_ brown_fox_ jumps_over _the_lazy_ dog"

But if the String was this
"The quick brown fox jumps over the lazy dog"
then it should remain the same.
  • September 10, 2019
  • Like
  • 0
I am trying to create a lightning componet for my Warranty Claim Case layout. On the case layout, I want to show a card of each record from a related object(Warranty_Claim_Line_Item__c) with a preview of the files attached to each of those records. I have the component setup to show the cards but the images are repeating for each record. I just need some advise on how to get only the images associated to each Warranty_Claim_Line_Item__c on the corresponding card. Below is my code. 
 
<aura:component implements="flexipage:availableForRecordHome,force:appHostable,lightning:actionOverride,force:hasRecordId" controller="warrantyLineItemRecordsCtrl">
   <aura:attribute name="lineItems" type="Warranty_Claim_Line_Item__c[]"/>
    <aura:attribute name="recordId" type="Id"/>  
    <aura:attribute name="filesIds" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.loadLineItems}"/>
    <aura:iteration items="{!v.lineItems}" var="l" indexVar="key">
        <lightning:card title="{!l.Name}">
            <aura:set attribute="actions">
                <lightning:button label="Edit" onclick="{!c.edit}" name="{!l.Id}"/>
            </aura:set>
            
            <div class="slds-grid slds-p-left_medium">
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Tire Description</h4>
                        <p><strong>Product Description</strong>:</p><p> {!l.Product__r.Name}</p>
                        <p><strong>Product Weight</strong>:<br/> {!l.Product_Weight__c} LBS</p>
                        <p><strong>Application Use</strong>: {!l.Application__c}</p>
                        <p><strong>Serial Number</strong>: {!l.Serial__c}</p>
                        <p><strong>Manufacturer Date</strong>: {!l.Manufacturer_Date__c}</p>
                        <p><strong>Removed Serial</strong>:</p>
                        <div class="row">
                        </div>
                    </div>
                    <div class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Purchasing Information</h4>
                        <p><strong>How You Got Your Tire</strong>: {!l.Original_Purchase__c}</p>
                        <p><strong>Purchase Date</strong>: {!l.Purchase_Date__c}</p>
                        <p><strong>Purchased New/Used</strong>:{!l.Purchased_New_or_Used__c}</p>
                        <p><strong>Selling Dealer</strong>: {!l.Selling_Partner_Account_Name__c}</p>
                        
                        <h4 class="slds-text-heading_small">Original Equipment Information</h4>
                        <p><strong>Make</strong>: {!l.Machine_Make__c}</p>
                        <p><strong>Model</strong>: {!l.Machine_Model__c}</p>
                        <p><strong>Year</strong>: {!l.Machine_Year__c}</p>
                        <p><strong>Equipment Hours</strong>: {!l.Machine_Hours__c}</p>
                        <p><strong>Equipment Serial Number</strong>: {!l.Machine_Serial_Number__c}</p> 
                        
                        <h4 class="slds-text-heading_small">Proof of Purchase</h4>
                        <div class="row"></div>
                        <h4 class="slds-text-heading_small">Service and Labor Costs</h4>
                        <p>{!l.Service_and_Labor_Cost__c}</p>                
                    </div>
                    <div  class="slds-col slds-size_4-of-12">
                        <h4 class="slds-text-heading_small">Issue with Tire</h4>
                        <p><strong>Defect Location</strong>: {!l.Defect_Location__c}</p>
                        <p><strong>Defect Type</strong>: {!l.Defect_Type__c}</p>
                        <p><strong>Tire Position</strong>: {!l.Tire_Position__c}</p>
                        <h4 class="slds-text-heading_small">Inspection Condition</h4>
                        <p><strong>Tire Hours</strong>: {!l.Tire_Hours__c}</p>
                        <p><strong>Tread Depth</strong>: {!l.Tread_Depth__c}</p>
                        <p><strong>Inflation</strong>: {!l.Tire_Inflation__c}</p>
                        <p><strong>Additional Comments</strong>: {!l.Issue_Additional_Comments__c}</p>
                        <h4 class="slds-text-heading_small">Evidence of Condition</h4>
                        <div>                            
                            <aura:iteration items="{!v.fileIds}" var="t">
                                <lightning:fileCard fileId="{!t.ContentDocumentId}" description="{!t.ContentDocument.title}"/>
                            </aura:iteration>
                        </div>
                        <h4 class="slds-text-heading_small">Proof of Stubble Stomper Purchase</h4>
                        <div class="row"></div>
                    </div>
                </div>
        </lightning:card>
    </aura:iteration>
    
</aura:component>
 
({
    loadLineItems : function(component, event, helper) {
        var action = component.get("c.getLineItems");
        action.setParams({
            MasterRecordId: component.get("v.recordId")
        });
        action.setCallback(this, function(response){
            if(response.getState()==="SUCCESS" && component.isValid()){
                component.set("v.lineItems",response.getReturnValue());
                console.log(JSON.parse(JSON.stringify(response.getReturnValue())));
            }
        });getWarrantyWithContent
        
        $A.enqueueAction(action);
        
        
        var action = component.get("c.fetchFiles");
        action.setParams({
            MasterRecordId : component.get("v.recordId")            
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state == "SUCCESS"){
                var result = response.getReturnValue()
                component.set("v.filesIds",result);
                console.log(result);
            }
        });	
        $A.enqueueAction(action); 
    }, 
    
     edit : function(component, event, helper) {
       var editRecordEvent = $A.get("e.force:editRecord");
         var recordId = event.getSource().get("v.name");
         
         console.log("record id: " + recordId);
        editRecordEvent.setParams({
            "recordId": recordId
        });
        editRecordEvent.fire();
    
    }
    
})
 
@AuraEnabled
    public static List<ContentDocumentLink> fetchFiles(String MasterRecordId){
        System.debug('MasterRecordId - - - - - - ' + MasterRecordId);
        return  [SELECT ContentDocumentId,ContentDocument.title,ContentDocument.LatestPublishedVersion.Warranty_Type__c 
                 FROM ContentDocumentLink 
                 WHERE ContentDocument.LatestPublishedVersion.Warranty_Type__c = 'Evidence' 
                 AND  LinkedEntityId IN (Select Id FROM Warranty_Claim_Line_Item__c WHERE Warranty_Case__c =: MasterRecordId)];        
    }

 
string server = null;
String host = URL.getSalesforceBaseUrl().getHost();
if(host.split('\\.')[2] == 'visual'){
	server = host.split('\\.')[1];            
}
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://' + server + '-api.salesforce.com/services/data/v34.0/sobjects/' + objName + '/describe/layouts/' + recordTypeId);
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
req.setHeader('Sforce-Call-Options', 'client=x');
Http http = new Http();
HTTPResponse res;
res = http.send(req);

This gives response: 

Request
|System.HttpRequest[Endpoint=https://na70-api.salesforce.com/services/data/v34.0/sobjects/Account/describe/layouts/01280000000HmSj, Method=GET]

Response
System.HttpResponse[Status=Service Unavailable, StatusCode=503] 

I also checked  
https://status.salesforce.com/instances/NAX/maintenances and looks all good. 

Can anybody help me figure out why is this occurring for a particular instance only? 
Hi All,

I have reached the last unit of the https://trailhead.salesforce.com/modules/sfdx_app_dev/units/sfdx_app_dev_setup_dx module yesterday and thought of continuing today. But unfortunately, force:org:open -u TempUnmanaged command is throwing an error. This command was working properly yesterday.

Please guide me.
 
D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:list --verbose
	=== Orgs
		 ALIAS   USERNAME              ORG ID              CONNECTED STATUS
	───  ──────  ────────────────────  ──────────────────  ────────────────
	(D)  DevHub  devhub@trailhead.com  00D7F000002ZgNYUA0  Connected


	  ALIAS          SCRATCH ORG NAME  USERNAME                            ORG ID
			   STATUS  DEV HUB             CREATED DATE                  INSTANCE UR
	L                                              EXPIRATION DATE
	  ─────────────  ────────────────  ──────────────────────────────────  ─────────
	─────────  ──────  ──────────────────  ────────────────────────────  ───────────
	─────────────────────────────────────────────  ───────────────
					 Demo Company      test-jm9x2pkl2h0s@demo_company.net  00D0l0000
	000XA6EAM  Active  00D7F000002ZgNYUA0  2017-10-13T10:52:15.000+0000  https://jav
	a-data-5232-dev-ed.cs58.my.salesforce.com      2017-10-20
	  GeoAppScratch  Demo Company      test-ty4lfw6cokgv@demo_company.net  00D0l0000
	000XHrEAM  Active  00D7F000002ZgNYUA0  2017-10-16T11:24:11.000+0000  https://pag
	e-data-2087-dev-ed.cs58.my.salesforce.com      2017-10-23
	  GeoTestOrg     Demo Company      test-plhfjartzy94@demo_company.net  00D0l0000
	000XIFEA2  Active  00D7F000002ZgNYUA0  2017-10-16T12:59:28.000+0000  https://cus
	tomer-ruby-9006-dev-ed.cs58.my.salesforce.com  2017-10-23
	  TempUnmanaged  Demo Company      test-eflatimr9jvm@demo_company.net  00D0l0000
	000XHqEAM  Active  00D7F000002ZgNYUA0  2017-10-16T13:28:46.000+0000  https://dat
	a-force-9071-dev-ed.cs58.my.salesforce.com     2017-10-23



	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged
	ERROR:  Failed to decipher auth data. reason: Unsupported state or unable to aut
	henticate data.

	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged --json
	{"message":"Failed to decipher auth data. reason: Unsupported state or unable to
	 authenticate data.","status":1,"stack":"authDecryptFailed: Failed to decipher a
	uth data. reason: Unsupported state or unable to authenticate data.\n    at ALME
	rror (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\salesforce
	-alm\\dist\\lib\\almError.js:35:19)\n    at Crypto.decrypt (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\crypto.js
	:157:19)\n    at Object.keys.forEach (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\p
	lugins\\node_modules\\salesforce-alm\\dist\\lib\\configValidator.js:61:36)\n
	at Array.forEach (<anonymous>)\n    at crypto.init.then (C:\\Users\\Nayana\\AppD
	ata\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\configValida
	tor.js:51:37)\n    at tryCatcher (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugi
	ns\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n    at Promise._settleP
	romiseFromHandler (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_module
	s\\bluebird\\js\\release\\promise.js:510:31)\n    at Promise._settlePromise (C:\
	\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\relea
	se\\promise.js:567:18)\n    at Promise._settlePromise0 (C:\\Users\\Nayana\\AppDa
	ta\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\promise.js:612:10
	)\n    at Promise._settlePromises (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plug
	ins\\node_modules\\bluebird\\js\\release\\promise.js:691:18)\n    at Async._drai
	nQueue (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird
	\\js\\release\\async.js:138:16)\n    at Async._drainQueues (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\async.js:148:
	10)\n    at Immediate.Async.drainQueues (C:\\Users\\Nayana\\AppData\\Local\\sfdx
	\\plugins\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n    at runCallb
	ack (timers.js:781:20)\n    at tryOnImmediate (timers.js:743:5)\n    at processI
	mmediate [as _immediateCallback] (timers.js:714:5)","name":"authDecryptFailed","
	warnings":[]}

I followed https://salesforce.stackexchange.com/questions/188735/im-unable-to-use-sfdx-forceorgopen-command-after-authorizing-an-org-via-the-s link's answer, still no luck.
 

 
DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0);
DateTime startDateOfSchedule = dtOrigin;
String timeVal = ' 02:03';
Date startDate = date.newinstance(startDateOfSchedule.year(), startDateOfSchedule.month(), startDateOfSchedule.day());

system.debug('=dtOrigin=='+dtOrigin);
system.debug('=startDateOfSchedule=='+startDateOfSchedule);
system.debug('=timeVal=='+timeVal);
system.debug('=startDate=='+startDate);
system.debug('=Formatted startDate=='+startDate.format());
DateTime dtVal = DateTime.parse(startDate.format()+''+timeVal);
system.debug('=dtVal=='+dtVal);

I have a problem in VF page for particular date time in apex controller. Above is snippet which I ran in dev console and got same error like appeared in VF.
In the above code, I am getting 'Invalid date/time: 12/03/2017 02:03'

If I change DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0); to DateTime dtOrigin = DateTime.newInstance(2017, 03, 13, 2, 3, 0);, I won't get error of invalid datetime while parsing DT and assining into dtVal variable. I wonder, why this behaviour only for this specific date and that too for 2hours:some minutes.  

For other date and time combo, there is no error. I find hard time in understanding this.

Please help.
Hi Developers,

TREKBIN is hiring 2-5 years of experienced salesforce developers.

Interested candidates, please mail your updated resume to nayana.kashigowda@trekbin.com.

Location : Mumbai, Bangalore.
Here is my code below:

<ul id="insideScroller" class="scrollable-menu scrollbar list-group" style="-webkit-overflow-scrolling: touch;" >
<aura:iteration var="sobj" items="{!v.SobjectRecords}">
<!-- Navigation to record detail page works only SF1-->
<li class="list-group-item" id="{!sobj.SId}" onclick="{!c.navigateToRecord}" >
<aura:renderIf isTrue="{!0 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[0]} : {!sobj.f1}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!1 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[1]} : {!sobj.f2}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!2 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[2]} : {!sobj.f3}<br/>
</aura:renderIf> </li>
</aura:iteration>
</ul>
I am using bootstrapcss in which I am able to see scrollbar in SF1 and even on the desktop.But when I load the same page in mobile the scrollbar disappears.

Any workarounds over this?
how to get the  custom objects and custom fields  of account object  to retrieve form the org


what will be the package.xml file
Thanks and Regards
Sri Reddy
 
Select I'd,( select I'd from pricebookEntries),(select id from opportunities where I'd='111') from pricebook2
I want to write this query on opportunity object.
I Just want to retrieve pricebookEntry and pricebook2 where opp id is 11
 
public with sharing class CSSChangePasswordController {
    @AuraEnabled
    public static String changePassword(String newPassword, String verifyNewPassword, String oldPassword) {
        String returnMessage = '';
        try{
            PageReference pr = changeExistingPassword(newPassword, verifyNewPassword, oldPassword);
            if (pr != null) {
                returnMessage = 'SUCCESS';
            } else {
                returnMessage = 'Error changing password. Contact Admin.';
            } 
            if(Test.isRunningTest()){
                throw new auraException();
            }
            
        } catch (Exception ex) {
            returnMessage = ex.getMessage();
        }
        return returnMessage;
    }
    
    public static PageReference changeExistingPassword(String newPassword, String verifyNewPassword, String oldPassword) {
        PageReference pf = Site.changePassword(newPassword, verifyNewPassword, oldpassword);
        return pf;
    }
}

=====here is my test class======
@isTest
public class CSSChangePasswordController_Test {
    public static List<User> userList=new List<User>();
    public static List<Contact> contactList=new List<Contact>();
    
    @testSetup static void setUp(){
        Profile profile=[Select id from Profile Where Name='System Administrator' LIMIT 1];
        User user=new User();
        user.JCI_Global_ID__c='GlobalId01';
        user.FirstName='First Name1';
        user.LastName='Last Name1';
        user.ProfileId=profile.id;
        user.Email='Dummymail@jci.com';
        user.Username='Dummymail@jci.com';
        user.Alias = 'Alias 1' ;
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.LocaleSidKey = 'en_US';
        user.EmailEncodingKey = 'UTF-8';
        user.LanguageLocaleKey = 'en_US';
        user.isActive = true;
        userList.add(user);
        insert userList;
        system.setPassword(userList[0].id, 'Abc@123456');
    }
    
    
    static testMethod void testChangePassword(){
        List<User> user1= [Select id,Email,Username from User where Username= 'Dummymail@jci.com' AND isActive=true ];
        Test.startTest();
        PageReference pf=null;
        String returnMessage=null;
        pf=CSSChangePasswordController.changeExistingPassword('Qwerty@1234', 'Qwerty@1234', 'Abc@123456');
        returnMessage= CSSChangePasswordController.changePassword('Qwerty@1234', 'Qwerty@1234', 'Abc@123456');
       
        Test.stopTest();
    }
}
Hi all, I'm working on get the current record with some fields (Name, Current_Balance__c) by <force:recordData /> in aura component. How do we get the value from Controller and update the record field?

Thanks!

Component
<aura:component controller="DueBalanceController" implements="force:lightningQuickAction,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
   <aura:attribute name="accountRecord" type="Object"/>
   <aura:attribute name="sumBalance" type="Object"/>
   <aura:attribute name="today" type="Date" />
   <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    
    <force:recordData aura:id="recordLoader"
                      recordId="{!v.recordId}"
                      fields="Name,Current_Balance__c"
                      targetFields="{!v.accountRecord}"
                      /> 
    <div>
        <lightning:card aura:id="warning-box" title="Billing So-far" >
			<lightning:layout>
               <lightning:layoutItem class="slds-p-around_x-small" size="12">
                       <lightning:formattedNumber value="{!v.accountRecord.Current_Balance__c}"/></div>
               </lightning:layoutItem>
            </lightning:layout>
        </lightning:card>
    </div>
</aura:component>
Contorller.js
({
    init: function(component, event, helper) {
        var today = $A.localizationService.formatDate(new Date(), "YYYY-MM-DD");
        component.set('v.today', today);
        var accountRecord = component.get("v.accountRecord");
        var recordId = component.get ("v.recordId");      
        var action = component.get("c.sumBalance");
        action.setParams({recordId:recordId});
        action.setCallback(this, function(response){
            let state = response.getState();
            if (state === "SUCCESS") {
            component.set("v.sumBalance",response.getReturnValue());
            component.set("v.accountRecord.Current_Balance__c",sumBalance.bl);
            component.find("recordLoader").reloadRecord();
            } else {
                console.log("Failed with state: " + state);
            }
        });
        $A.enqueueAction(action);
    },
})

Apex Contorller
public with sharing class DueBalanceController{
    @AuraEnabled
    public static Object sumBalance (String recordId){
        Date d_today = system.Date.today();
        AggregateResult[] groupedResults = [
            SELECT SUM(Balance__c)bl,SUM(Paid_Total__c)pt,SUM(Billing_Total__c)bt, Tenant__c
            FROM Billing__c 
            WHERE Tenant__c	= :recordId AND (User_Due_Date__c <= :d_today OR Paid_Date__c <=:d_today) AND (Status__c='Unpaid' OR Status__c='Paid' OR Status__c='Captured' OR Status__c ='Chasing Overdue')
            GROUP BY Tenant__c
        ];
        return groupedResults[0];
       
    }
}



 
  • February 01, 2021
  • Like
  • 0
Hi all, I'm having some issues with what I think is an access issue.
 
I have code where the user uploads a pdf to a VisualForce page, and clicks a button which sends that pdf both to Salesforce files and the files in the specified group. This works perfectly when I enter the VisualForce Page in "Preview" from the Developer Console.
 
However, this doesn't work when I go to the actual URL of my Site. I am taken to a "Authorization Required" page after clicking the button and no files are stored. To be clear, by "actual URL" I mean when you go to Salesforce Sites and click the URL of your Site (which has the VisualForce page as its home page).
 
I've found that the main reason this is probably happening is an error. In preview, the SOQL query which is assigned to the pantryGroups variable has a size of 1, indicating it returned the correct group, but at the URL, the pantryGroups variable has a size of 0. Up to this point I did a few hours of research on public access settings to fix other Authorization Required pages but couldn't solve this issue. I was looking into "Profile" and see that I am a System Administrator so I went to give SysAdmins access to the VisualForce page and Apex class, but they already did.
 
What's going on here? When I go to the URL am I not actually a System Administrator at that point? Would I be considered a guest user? Any help is appreciated. I am trying to upload the file to both my Salesforce files and the groups files. Works perfectly fine in Preview, SOQL fails at the URL.
 
 
 
Here's the Apex code that runs when the button is clicked (pdfFile is a ContentVersion object):
 
// insert the file into the SF backend
pdfFile.PathOnClient = pdfFile.Title + '.pdf'; // The files name which will help in preview
pdfFile.ContentLocation = 'S'; // to use S specify this document is in Salesforce, to use E for external files
insert pdfFile;
 
// retrieve the uploaded file ID
Id pdfFileId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =: pdfFile.Id].ContentDocumentId;
 
// insert ContentDocumentLink to share file with
ContentDocumentLink pdfLink = new ContentDocumentLink();
pdfLink.ContentDocumentId = pdfFileId;
List<CollaborationGroup> pantryGroups=[select id, MemberCount from CollaborationGroup where Name=:groupName]; // grab the group from SF backend.
System.debug('groups size: ' + pantryGroups.size()); // prints 1 in preview, 0 at URL
CollaborationGroup pantryGroup = pantryGroups[0];
pdfLink.LinkedEntityId = pantryGroup.Id; // link the file to group
pdfLink.Visibility = 'AllUsers'; // all users in group can see
pdfLink.ShareType = 'C'; // all users in group can edit file
insert pdfLink;

 
Im getting error like Nan during subtraction of two times. Can anyone help me how to resolve this?

var startDate = component.get("v.time");
        var endDate = component.get("v.time1");
        var days = (endDate-startDate)/8.64;
        alert(days);

please say me how to find difference between two times not two days
Hi. I return custom object to js by callback, then take it in aura component like ​​​​​.
<aura:attribute name="customObj" type="customObj__c[]"/>
Also i have list of custom fields in this object (endless) 
<aura:attribute name="listObjKeys" type="String" default='["Field1__c","Field2__c","Field3__c","Field1__c","Date__c"]'/>
How i can iterate through my object to display values by field. I try this, but with no result 
<aura:iteration items="{!v.customObj}" var="co">
  <aura:iteration items="{!v.listObjKeys}" var="keys">
    <tr>{!keys}</tr>
  </aura:iteration>
</aura:iteration>
I have created a flow and a lightning component which run on new.
The flow creates a record and I want at the end of the flow to be redicted inside the record which was  just created.
In the flow I store the new record's id as {!recordId}

The controller is:
 
({
    init : function (component) {
        // Find the component whose aura:id is "flowId"
        var flow = component.find("flowId");
        // In that component, start your flow. Reference the flow's Unique Name.
        flow.startFlow("Internal_Requests");
        
    },
handleStatusChange : function (component, event) {
    
    if(event.getParam("status") === "FINISHED") {
       var navEvt = $A.get("e.force:navigateToSObject");
            navEvt.setParams({
                "recordId": "??????????",
                "slideDevName": "related"
            });
            navEvt.fire();
         }
      },
})


What do i set at the record Id though to be redicted in the new record?

All the threads I have found, provide specific Id which of course does not apply to our needs.

Hi,
I have one use case where We want to update the lightning web component to show the "Lowest Cost" column in red if the lowest cost is lower than the Unit cost.


User-added image
Welcome to your suggestions.

Thanks
Nikhil
Hi all,
We are trying to switch to lightning , and inside an object I can't see the "Detail page buttons".
They are not Javascript buttons, they are just a button who redirect to a visualforce page.

I can't find any information regarding this buttons and why I can't see them.

Any help?
Thanks

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.