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

How to pass the variables from REST API to Apex

Hi All,

I have created login form with username and passsword.I have created new custom fields in the contact object.
On click of submit button.It will validates the contact is existing or not and returns contact's FirstName,LastName,Email,Phone.

For this I created a RESTAPI which will take the username and password as a parameters and validates against the credentials and  returns the contact details for that valid user.Login form i have created in my org. using lightning.

Now my challenge is  when the user clicks on submit button it should get the contact details from the RESTAPI and maps with the contact object fields and   reload or refresh the page with contact details and displays the field values FirstName,LastName,Email and Phone.
I am trying to pass the variables or map the variables which are returned from REST API to APEX.

How can I acheive this scenario.Do I need to create another lightning component to refresh the parent component to child component and returns the login contact details.

If anyone can provide a sample code that would be a great help.

Any help would be greatly appreciated.

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi Sirisha,
If your API function returns required attributes which you want to display in the component then you can extract them using json string.
if you want to further guidence please let me see your API call and the component code.
I suggest you to create another child component and refresh it once you get response from submit button

Regards
Sampath
Sampath SuranjiSampath Suranji
Hi Sirisha,
Try like below,
Map<String, object> fieldList =  (Map<String, object>) JSON.deserializeUntyped(response);
        System.debug(' '+ fieldList.get('Contact Data') );
        List<object>objList= fieldList.values() ;
        map<String,Object> m = (map<String,Object>) objList[0];
        string email= m.get('Email');
        string lastName= m.get('LastName');
        string phone= m.get('Phone');

regards
SFDC New learnerSFDC New learner
Hi Sampath,
Thanks for the reply.
I tried code given by you.Just did small change like below .It worked.
string email=string.valueOf(m.get('Email');

Thanks,
Sirisha
SFDC New learnerSFDC New learner
Hi Sampath,

In the LoginPageform component ,on click of submit button,I am getting the data from the REST resource using httprequest in Apex controller and now I have to return the values and display in LoginPageContactDetails child component.
 

I am getting data from the response.ReturnValue() ,but not able to set in the component.
{
  "Contact Data" : {
    "LastName" : "han2",
    "Phone" : "980987098",
    "Email" : "test@123.com"
  }
}
Is it possible to set the values returned from REST API to lightning component.
How to pass the RESTResource Return Values like Last Name, First Name, Email from Apex Controller to Parent Component "LoginPageform"?
Any suggestions on this would be helpful.

Thanks,
Sirisha
 
Sampath SuranjiSampath Suranji
Hi,
You can get the return values of the apex method inside the helper class after you call the apex method something like below,
// code part to call apex method
 var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
         var a=  response.getReturnValue();
       // then call the child component by passing the required attributes
}
SFDC New learnerSFDC New learner
Hi Sampath,

Thanks for the suggestion.
As per your suggestion,I have modified like this.
Parentcomponent
 <c:LoginContactDetailsComponent aura:id="childDetails"/>
<ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clicklogin}" />
Helper
action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var acc = response.getReturnValue();
                console.log(acc);
             var childComponent = component.find("childDetails");
        console.log(childComponent);
        childComponent.getMethod('aa','bb','cc','dd');           
        }

ChildComponent
<aura:method name="getMethod" action="{!c.details}" access="PUBLIC">
        <aura:attribute name="firstname" type="String"/>
        <aura:attribute name="lastname" type="String"/>
        <aura:attribute name="phone" type="String"/>
        <aura:attribute name="Email" type="String"/>
    </aura:method>
ChildJS:
 ({
    calcdetails : function(component,event,helper){
        helper.newdetails(component);
        
    }
})
ChildHelper:
({
    newdetails : function(component) {
    var args = event.getParam("arguments");
        var firstname = args.firstname;
       var lastname = args.lastname;
        var phone = args.phone;
        var email = args.Email;
        console.log('Inside Calc Score: ' + firstname + ' -'+ phone + '-' + email);
        }
})
what should I declare in Javascript to pass it helper.
I m getting error sayingc:LoginFormcomponent$controller$clicklogin [Cannot read property 'getMethod' of undefined] Failing descriptor: {c:LoginFormcomponent$controller$clicklogin}
Where I am going wrong?

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
When you get response from the rest ApI, create the child component. Try something like below.
action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var acc = response.getReturnValue();
                console.log(acc);
            
               $A.createComponent(
            "c:yourChildComponent",
            {
                "lastName":'dsdsdsd' ,
               "firstName":'sasa'
                "email  ":'sa@sa.lk,
               "phone":'1212121''              
            },
            function(newCmp){
                if (component.isValid()) {
                  //if you want to hide the parent, wrap it with a div and hide it as below
                    $A.util.addClass(component.find("divMain"), "slds-hide");
                    var body = component.get("v.body");
                    body.push(newCmp);
                    component.set("v.body", newCmp);
                }
            }
        );	        
		
        }

 
SFDC New learnerSFDC New learner
Hi Sampath,

Thanks for the solution.
I got the solution by creating the application event and called the child component in parent component and sent the values to that component .But I will try your solution too.

 var myEvent = $A.get("e.c:LoginEvent"); 
            myEvent.setParams({
                "Acc" : acc
            });
             myEvent.fire();           
            $A.util.addClass(component.find("parent"),"slds-hide");

Thanks,
Sirisha
SFDC New learnerSFDC New learner
Hi Sampath,

I am trying to implement another functionality ChangePassword in the same login form.
Here is the code:
Helper:
({
    click : function(component,event) {
        console.log('inside helper');
        var pass=component.find("Pswd").get("v.value");
        console.log(pass);
        var id=component.get("v.passID");
        console.log(id);
        //var user=component.get("userid");
        
        var action=component.get("c.login");
        action.setParams({
            "passid":id,
            "pass":pass
            
        });
        action.setCallback(this, function(response){
            console.log('response is success');
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            
            var acc = response.getReturnValue();
            console.log(acc);
             component.set("v.passID",response.getReturnValue());
        }
        });
        $A.enqueueAction(action);
    }
})
Apex:
public class PasswordResetapex {
    
    //@AuraEnabled
    public static void login(string pass,string passid){
        LIST< contact > c = new LIST< contact >();
        try{
        if(passid!=null){
             c=[select id,loginId__c,Password__c from contact where id=:passid limit 1];
            if(c.size()>0){
                c[0].Password__c=pass;
                update c[0];
            }
            
            
        }
        
    }
    
        catch(Exception ex){}
}
}
component:
<aura:component controller="PasswordResetapex" >
    <aura:attribute name="passID" type="String"/>
    <aura:attribute name="NewLogin" type="contact" default="{'sobjectType': 'Login__c',
                         'Name': '',
                         'loginId__c': '',
                          'Password__c':''                                                                 
                         }"/>
     <fieldset class="slds-box slds-theme--default slds-container--small">

    <legend id="Login form" class="slds-text-heading--small 
      slds-p-vertical--medium">
      Login
    </legend> 
    <form class="slds-form--stacked">
    <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="Pswd" label="Password"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.NewLogin.Password}"
                  required="true"/>
          </div>
     </div>
     <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clicklogin}" />
    </div>
      <p>ID:  <ui:outputText value="{!v.passID}"/>
        </p>
    </form>
    </fieldset>
    
</aura:component>

Apex code is working fine.I am getting error as This page has an error. You might just need to refresh it. Unknown controller action 'login' Failing descriptor: {markup://c:PasswordResetcomponent}
where I am going wrong?

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
In the apex clas, method should be auraEnabled,
 @AuraEnabled
    public static boolean login(string pass,string passid){
----------
And make sure you are passing correct values for the pass & passid from the helper method
SFDC New learnerSFDC New learner
Hi Sampath,

How to send notification email to contact once the password changed?

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
You can try with a work flow Email alert to send an email once the password field was changed.
Also you can try with the apex code (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm) at the time when you update the password field.

Regards
Sampath
SFDC New learnerSFDC New learner
Hi Sampath,

I m trying to implement Forgot Password functionality in Login Form.
I added code like this
<a href="javascript:void(0)" onclick="{!c.doSomething}">
            Forgot Password
    </a>
      <div class="slds-hide" aura:id="forgot">
      <c:ForgotPasswordcomponent/>
       </div>
Javascript controller
--------------------------
dosomething:function(component,event,helper){
        $A.util.addClass(component.find("parent"),"slds-hide");
            $A.util.removeClass(component.find("forgot"),"slds-hide");
    }
I'm getting error Unable to find 'doSomething' on 'compound://c.LoginFormcomponent'. Failing descriptor: {markup://c:LoginFormcomponent}.
where I am going wrong?

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
According to the error you have missed the 'doSomething' method in LoginFormcomponent.
Please make sure that method is included in the controller.js in the LoginFormcomponent component
SFDC New learnerSFDC New learner
Hi Sampath,

I am new to the lightning.As part of learning, I have build a Login Page form along with ForgotPassword and Changepassword functinality in the Login Form.
While doing this process ,I have generated Access token using Postman and hardcoded in my code and also added Postman callback link in ManagedApps.But I don't think this is better way to do.I didn't understand concept of token and refresh token .
Below is my code:
public class LoginRegistrationForm {
    public static String responseFormat='application/json';
     public static String bodyContentType='application/json';
@AuraEnabled
    public static string login(string uname,string pwd){
        string u1=string.valueOf(uname);
         string p1=string.valueOf(pwd);
        
            HttpRequest req = new HttpRequest();
                Http http = new Http();
 
        try{
           string url = 'https://siri0428-dev-ed.my.salesforce.com/services/apexrest/LoginDetails/?login='+u1+'&password='+p1;
            req.setEndpoint(url);
            req.setMethod('GET');  
     
            req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.setHeader('accept','application/json');
           //This token is generated from Postman 
            req.setHeader('Authorization', 'Bearer ************************************************************************************************************');
            HTTPResponse resp = http.send(req);
           }
Is there any simple way I can do instead of hardcoding the token.
Please help me on this.Any help is greatly appreciated.

Thanks,
Sirisha
    
Sampath SuranjiSampath Suranji
Hi,
I think you don't need such kind of things.
You can add custom login page for communities. for that firstly you have to create a community (https://help.salesforce.com/articleView?id=networks_creating.htm&type=5). then using the community builder replace the existing login page component by a custom component like this (https://sfdcbrothers.wordpress.com/2017/11/01/custom-community-login-lightning-component-salesforce/).
Then create a community user and try to login your community using user name and password.
SFDC New learnerSFDC New learner
Hi Sampath,

   I have created two custom fields in Contact object loginId,Password and validating  the user credentails in RESTAPI which will pull the data based on these fields in my lightning component.But I dont know how to set up community concept in this one.
SFDC New learnerSFDC New learner
Hi Sampath,

  I am trying to populate the picklist values on click of button .For this ,I am trying to pass values from parent component to child component .
Below is the code .
var pro = component.get("c.myProjects");
        pro.setParams({
            "uname":uname,
             "pwd": pwd 
        });
        pro.setCallback(this,function(a){
            var s = a.getState();
            
            if(s === "SUCCESS"){
                console.log(a.getReturnValue());
                var p = a.getReturnValue();
                alert(a.getReturnValue());
                var myEvent = $A.get("e.emitCS:LoginEvent"); 
                myEvent.setParams({
                    "project" : p
                });
                myEvent.fire();
            }
        });
Child component
----------------------
<aura:handler event="emitCS:LoginEvent" action="{!c.handleLoginEvent}" aura:id="click"/>
    <ui:inputselect aura:id="input_select"  change="{!c.handleChange}">
        <aura:iteration items="{!v.myProj}" var = "a">
            <ui:inputselectoption text="{!a}" label="{!a}" />
        </aura:iteration>
    </ui:inputselect>
handleLoginEvent : function(component,event,helper){
       
          helper.handleEvent(component,event);
       // this.handleChange:function(component,event,helper);
          
    },
    handleChange:function(component,event,helper){
          helper.handleprojectEvent(component,myProj);
    }

({
    handleEvent : function(component,event){
        $A.util.removeClass(component.find("child"), "slds-hide");
        var  acc = event.getParam("Acc");
        //var x = p.getParam("project");
        //this.handleprojectEvent:function(component,changeId,myProj);
        //component.set("v.Acc1",acc);
        console.log("This is from Child Component",acc);
        var parsed = JSON.parse(acc);
        console.log(parsed[0]);
        console.log(parsed.LastName);
        JSON.parse(acc, (key, value) => {
        if(key=='LastName'){
                cmp.find("lastName").set("v.value",value);
        }
         if(key=='FirstName'){
                cmp.find("FirstName").set("v.value",value);
        }
        if(key=='Email'){
                cmp.find("Email").set("v.value",value);
        }
        if(key=='Phone'){
                cmp.find("Phone").set("v.value",value);
        }
        });
    },
     handleprojectEvent:function(component,event){
        //var p=myProj.get("e.c.LoginEvent");
        this.handleEvent(component,event);
        var x=event.get("project");
         component.set("v.myProj",x);
        console.log('x',x);
        alert('@@@',x);
    }
})

Im getting error saying  Action failed: emitCS:LoginContactDetailsComponent$controller$handleLoginEvent [Unexpected token u in JSON at position 0] Callback failed: apex://emitCS.LoginRegistrationForm/ACTION$myProjects Failing descriptor: {emitCS:LoginContactDetailsComponent$controller$handleLoginEvent}
How can I fix this issue.Pls help me.

Thanks,
Sirisha
 
SFDC New learnerSFDC New learner
Hi Sampath,
Now I am not getting error.But not able to pass the data  from parent to child .
handleprojectEvent:function(component,event){
           var x=event.get("project");
         component.set("v.myProj",x);
        console.log('x',x);//It is showing undefined
        alert('@@@',x);
    }
I have defined attribute as list type in the event 
<aura:attribute name="project" type="list"/>
where I am going wrong?
Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
According to your code when you click the button in parent it should be passed the values to the child component.
Put a console log in to the 'handleLoginEvent' function in the child component controller.js and make sure you are getting a value from
var  acc = event.getParam("project");
if not means that you have a problem in calling the aura:event. Reason may be attribute types mismatch or something like that
SFDC New learnerSFDC New learner
Hi Sampath,
I am new to lightning.I am learning the tool by creating a sample Employee Timesheet application.while coding I am facing some issues.I would like check with you if you can guide me with this learning project with couple of hours help.If you are ok ,we can talk other things through email.You can reach @ sirisha.yada@gmail.com. 
Any support is really appreciated.
Thanks,
Sirisha