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 

creating contact

Hi All,
I am trying to create new contact using Lightning component.
Here is my code:
<aura:component controller="CreateContact">
    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:attribute name="contact" type="Contact" default="{'sobjectType': 'Contact',
                         'FirstName': '',
                         'LastName': ''
                         
                       }"/>
    <form class="slds-form--stacked">   
    <p>Name:
        <ui:inputText value="{!v.contact.Name}"/>
    </p>
       <div class="slds-form-element slds-is-required">
        <div class="slds-form-element__control">
    <p>FirstName:
        <ui:inputText aura:id="fstname"  value="{!v.contact.FirstName}"/>
    </p>
        </div>
        </div>
    <p>LastName:
        <ui:inputText value="{!v.contact.LastName}"/>
    </p>
    <p>Email:
        <ui:inputText value="{!v.contact.Email}"/>
    </p>
    <p>Phone:
        <ui:inputText value="{!v.contact.Phone}"/>
    </p>
    <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clickSubmit}"/>
      </div>
    </form>
</aura:component>

JS:
({
    clickSubmit : function(component, event, helper) {
        console.log('inside controller');
        var action=component.get("c.savecontact");
        console.log(" inside action variable");
        action.setParams({
        "Contact": contact
        //component.get("v.contacts")
         
    });
        action.setCallback(this,function(response){
         var state=response.getstate();
         var contacts = component.get("v.contacts");
            
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.contacts", response.getReturnValue());
            alert('Contact is created successfully');
        }
                           });
        $A.enqueueAction(action);
        
    }
})
apex:
public class CreateContact {
   @AuraEnabled
    public static void savecontact(){
        //account acc = new account();
       contact contact1;
        //contact1.accountId = acc.id;
        insert contact1;
        system.debug('contact1' +contact1);
    }

}

When I click on the submit button it is showing error as Action failed: c:CreateContacts$controller$clickSubmit [contact is not defined].
Failing descriptor: {c:CreateContacts$controller$clickSubmit}.Can anyone help me to fix this problem.

Thanks,
Sirisha
Best Answer chosen by SFDC New learner
Sampath SuranjiSampath Suranji
Hi,
Please try with the exact code which I given above. It is saving and giving the success message also.
In apex code you can retrieve up to 50000 records( so you can use any number below to 50000 for the Limit number).
In your scenario I think you anly want to save contact records. If you want to display existing contact records you can reffer "contacts" variable

All Answers

Sampath SuranjiSampath Suranji
Hi try like below,
controller.js
({
    clickSubmit : function(component, event, helper) {
        console.log('inside controller');
        helper.save(component);
    }
})

helper.js
({
    save : function(component) {
        var action=component.get("c.savecontact");
        
        var contact = component.get("v.contact");
        action.setParams({
            "objContact": contact
        });
        action.setCallback(this,function(response){
            var state=response.getState();
            var contacts = component.get("v.contacts");
            
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.contacts", response.getReturnValue());
                alert('Contact is created successfully');
            }
        });
        $A.enqueueAction(action);
        
    }
})

apex class
public class CreateContact {
    @AuraEnabled
    public static LIST<Contact> savecontact(Contact objContact){
        if(objContact!=null)
        {
            insert objContact;
            system.debug('contact1' +objContact);
        }
        List<COntact> c= [select id, name from contact limit 10];
        return c;
    }
    
}

regards​​
SFDC New learnerSFDC New learner
Thanks for the quick Solution Sampath.Now when I click on submit new contact is created.But I have couple of questions.
First,why the alert pop up message is not showing on click of submit button.
Second,In Apex class do I need to give limit 10,bcoz when I change it to 1,2,5 record is not getting saved.
Please guide me on these points.

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
Please try with the exact code which I given above. It is saving and giving the success message also.
In apex code you can retrieve up to 50000 records( so you can use any number below to 50000 for the Limit number).
In your scenario I think you anly want to save contact records. If you want to display existing contact records you can reffer "contacts" variable
This was selected as the best answer
SFDC New learnerSFDC New learner
Hi Sampath,

  I am trying to create new Rating form using lightning component.when I case status is closed a new rating record needs to be inserted for that contact.
I have created lookup fields in Rating to relate with case and contact.

Below is my code:
App:
<aura:application access="Global" >
    <aura:dependency resource="ui:button"/>
    <c:RatingComponent />
</aura:application>
Component:
<aura:component controller="CreateContact">
    <aura:attribute name="Ratings" type="Rating__c[]"/>
    <aura:attribute name="NewRating" type="Rating__c" default="{'sobjectType': 'Rating__c',
                         'Name': '',
                         'Rating__c': ''
                         
                       }"/>
    <form class="slds-form--stacked">   
    <p>Name:
        <ui:inputText value="{!v.NewRating.Name}"/>
    </p>
        <div class="slds-form-element slds-is-required">
        <div class="slds-form-element__control">
     <ui:inputSelect >
    <ui:inputSelectOption text="1" label="1" value="true"/>
    <ui:inputSelectOption text="2" label="2"/>
    <ui:inputSelectOption text="3" label="3"/>
         <ui:inputSelectOption text="4" label="4"/>
         <ui:inputSelectOption text="5" label="5"/>
         <ui:inputSelectOption text="6" label="6"/>
         <ui:inputSelectOption text="7" label="7"/>
         <ui:inputSelectOption text="8" label="8"/>
         <ui:inputSelectOption text="9" label="9"/>
         <ui:inputSelectOption text="10" label="10"/>
         
</ui:inputSelect>  
    </div>
        </div>
    
    <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clickSubmit}"/>
      </div>
    </form>
</aura:component>
JS:
({
    clickSubmit : function(component, event, helper) {
        console.log('inside controller');
        helper.save(component);
    }
})
Helper:
({
    save : function(component) {
        var action=component.get("c.saveRating");
        
        var contact = component.get("v.NewRating");
        action.setParams({
            "objRating": NewRating
        });
        action.setCallback(this,function(response){
            var state=response.getState();
            var contacts = component.get("v.Ratings");
            
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.Ratings", response.getReturnValue());
                alert('Rating is created successfully');
            }
        });
        $A.enqueueAction(action);
        
    }
})

ApexClass:

public class SurveyRatingformclass {

    @AuraEnabled
    public static LIST<Rating__c> saveRating(Rating__c objRating){
        if(objRating!=null)
        {
            case c = new case();
             c.Status='CLOSED';
            insert c;
            
         objRating.CaseId__c = c.id;
            objRating.ContactId__c=objRating.CaseId__c;
            insert c;
            insert objRating;
            system.debug('contact1' +objRating);
        }
        List<Rating__c> c= [select id, name from Rating__c limit 10];
        return c;
    }
    

}
Again I am getting error as Unable to find 'saveRating' on 'compound://c.RatingComponent'. Failing descriptor: {markup://c:RatingComponent}.Also Can you please tell me where I am doing wrong.
Any help to fix this issue would be greatly appreciated. 

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi Sirisha,
change the controller name according to the new controller class
<aura:component controller="SurveyRatingformclass">

change the parameter setting part In the helper as below
var objRating = component.get("v.NewRating");
        action.setParams({
            "objRating": objRating
        });

Controller method should like below
public static LIST<Rating__c> saveRating(Rating__c objRating){
        if(objRating!=null)
        {
            case c = new case();
            c.Status='CLOSED';
            insert c;
            
            objRating.CaseId__c = c.id;
            objRating.ContactId__c=objRating.CaseId__c;
            
            insert objRating;
            system.debug('contact1' +objRating);
        }
        List<Rating__c> c= [select id, name from Rating__c limit 10];
        return c;
    }

best regards
SFDC New learnerSFDC New learner
Hi Sampath,

I changed the controller name and now the error has gone.But the record is not getting inserted in Rating Object and also the same problem as previous message is not getting displayed.

And also I have one more question ,So basically whenever case status ='CLOSED'  a new record has to be inserted in Rating object and should be sent to contact.How to implement this logic?
I have created Email Template and I want this Rating form URL link to be sent to contact ,so that contact will click the link give the rating and submits back.
How to keep Rating form link in Email Template?How to pass the CaseId variable in URL link?

Can you please help me on this?

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
I couldn't get your requirement properly.. can u please explain in details.
do you want to send an email with the rating page url to be send to the contat when u change the status of the case to 'closed'?
 
SFDC New learnerSFDC New learner
Hi Sampath,
when a case status is closed ,an email with case rating link has to be sent to customer based on case contact email.Once customer submits with  rating 1-5 then this information need to be captured in rating custom object.I created rating custom object with caseId,contactId,rating.Also created rating form as u can see my code above.
Now my challenge is how to have a custom url link of this form within email template which goes to customer once case status closed.And also when customer submits this rating has to be updated in rating object for that caseid.
Any help much appreciated.

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi ,
try something like below.
Build a process to create new Rating record when the case status is changed to 'closed' as below
Using process builder start with case object and check the status = 'closed' in the criteria.

User-added image

then in the action, create new rating record by referring caseId and contactId in the case object..
User-added image

create an email template.
The HTML body should somthing like below
<a href=https://yourSFdomain.com/c/yourRatingPageApp.app?{!Rating__c.Id} >rate us
</a>
(change the variable names according to yours)

Then create an email alert by referring above template. The recipient should be 'related contact:contactId '

Create another process to send the email.
Start with Rating object (when record is created)
check contactId<>null in the criteria.
User-added image
In the immediate action select Email alerts and assign the alert which you created before.

check it and let me know
regards
SFDC New learnerSFDC New learner
Hi Sampath,
Thanks for solution.First ProcessBuilder is working now.
But I got stuck here.In the Rating form Apex class code below what should I update Rating as input.
public class SurveyRatingformclass {

    @AuraEnabled
    public static Rating__c saveRating(Rating__c objRating){
        
            Rating__c rate = new Rating__c();
               // rate.name = '';
                rate.Status__c = 'Completed';
                rate.CaseId__c = C2.id;
                rate.ContactId__c=rate.CaseId__c;
                //rate.Rating__c=objRating;
                Rating .add(rate);
        
    }
   
    update Rating ;
     
      return objRating;   
    }
    
Thanks,
Sirisha
SFDC New learnerSFDC New learner
Rating is a picklist value having 1-10
Sampath SuranjiSampath Suranji
Hi Sirisha,
Change the url value of the email template somthing like below
<a href=https://yourSFdomain.com/c/yourRatingPageApp.app?ratingId={!Rating__c.Id} >rate us
</a>

App
<aura:application >
    <aura:attribute name="ratingId"        type="String"   access="public" />
    <c:devforum1 ratingId="{!v.ratingId}" />
</aura:application>

component
<aura:component controller="SurveyRatingformclass">
     <aura:attribute name="ratingId" type="string"/>
    <aura:attribute name="ratingValue" type="Integer"/>
    <aura:attribute name="Ratings" type="Rating__c[]"/>
    <aura:attribute name="NewRating" type="Rating__c" default="{'sobjectType': 'Rating__c',
                         'Name': '',
                         'Rating__c': ''
                         
                       }"/>
    <form class="slds-form--stacked">   
    <p>Name:
        <ui:inputText value="{!v.NewRating.Name}"/>
        
    </p>
        <p>ID:
            <ui:outputText value="{!v.ratingId}" />
        </p>
        
        <div class="slds-form-element slds-is-required">
        <div class="slds-form-element__control">
     <ui:inputSelect value="{!v.ratingValue}">
    <ui:inputSelectOption text="1" label="1" value="true"/>
    <ui:inputSelectOption text="2" label="2"/>
    <ui:inputSelectOption text="3" label="3"/>
         <ui:inputSelectOption text="4" label="4"/>
         <ui:inputSelectOption text="5" label="5"/>
         <ui:inputSelectOption text="6" label="6"/>
         <ui:inputSelectOption text="7" label="7"/>
         <ui:inputSelectOption text="8" label="8"/>
         <ui:inputSelectOption text="9" label="9"/>
         <ui:inputSelectOption text="10" label="10"/>
         
</ui:inputSelect>  
    </div>
        </div>
    
    <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clickSubmit}"/>
      </div>
    </form>
</aura:component>

helper
({
    save : function(component) {
        var action=component.get("c.saveRating");
        
        var ratingId = component.get("v.ratingId");
         var ratingValue = component.get("v.ratingValue");
        action.setParams({
            "ratingId" :ratingId,
            "ratingValue": ratingValue
        });
        action.setCallback(this,function(response){
            var state=response.getState();
           // var contacts = component.get("v.Ratings");
            
            if (component.isValid() && state === "SUCCESS") {               
                alert('Rating is created successfully');
            }
        });
        $A.enqueueAction(action);
        
    }
})

Apex class
@AuraEnabled
    public static void saveRating(string  ratingId,Integer ratingValue){
        try{
             if(ratingId!=null)
        {
           LIST< Rating__C >objRatingList =[select id,name from rating__C where id=:ratingId limit 1];
            if(objRatingList.size()>0){
                objRatingList[0].rate__C= ratingValue;
                update objRatingList[0];
            }
            
           
        }
        
        }
        catch(Exception ex){}
       
    }

you can test this by calling your app url in the browser,
https://yourSFdomain.com/c/yourRatingPageApp.app?ratingId=anyRatingRecordId
Best regards
SFDC New learnerSFDC New learner
Hi Sampath,

Process builder is working properly.Also,I am getting email .But the Rating field is not getting updated.
I am using another field status as Pending/completed which has to be updated when user selects the rating and submits the button.
should I mention status also in component and apexcode or It will work without giving status field anyway.
where I am going wrong.Pls guide me.

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
If ithe status value is hard coded and not comming from the component, you don't need to mention in the component.
You can just mention in the apex class. check the debug log in the developer console. then you'll be able to find the error.

regards
SFDC New learnerSFDC New learner
Hi Sampath,
Thank You for quick reply .Your solution worked perfectly.

Thanks,
Sirisha
 
SFDC New learnerSFDC New learner
Hi Sampath,

  I have  created 2 process builders,emailtemplate with the URL link included in it which will send the URL link to customer for that case as you mentioned.

Now my requirement is ,If the customer has already submitted the form ,he should not be able to refill the form and show the message as 'Already you have submitted the Rating form'

How can I achieve this functionality?Where should I write this code ,In the submit button or any other better way to do this?
Can you please guide me on this.

Thanks,
Sirisha
Sampath SuranjiSampath Suranji
Hi,
Create a flag field in the rating object and update it once the user rated the record. then create a apex method to check this field at the init of thecomponent.
Try like below,
add below attribute and the lister to the component
<aura:attribute name="alreadyRated" type="boolean" default="false"/>
    <aura:handler name="init" value="{!this}" action="{!c.checkStatus}" />
And add if condition the the page component which check at the page load and move your form inside to the aura:if
<aura:if isTrue="{!!v.alreadyRated}">
        <form class="slds-form--stacked"  > 
         -------------------------
    </aura:if>

controller 
({
    clickSubmit : function(component, event, helper) {
        console.log('inside controller');
        helper.save(component);
    }
    ,
    checkStatus: function(component, event, helper){
        helper.checkStatus(component,event);
    }
})

helper​
({
    save : function(component) {
        var action=component.get("c.saveRating");
        
        var ratingId = component.get("v.ratingId");
         var ratingValue = component.get("v.ratingValue");
        action.setParams({
            "ratingId" :ratingId,
            "ratingValue": ratingValue
        });
        action.setCallback(this,function(response){
            var state=response.getState();
           // var contacts = component.get("v.Ratings");
            
            if (component.isValid() && state === "SUCCESS") {               
                alert('Rating is created successfully');
            }
        });
        $A.enqueueAction(action);
        
    },
    checkStatus : function(component) {
        var action=component.get("c.checkAlreadyRated");        
        var ratingId = component.get("v.ratingId");
        
        action.setParams({
            "ratingId" :ratingId
           
        });
        action.setCallback(this,function(response){
            var state=response.getState();
            
            if (component.isValid() && state === "SUCCESS") { 
                component.set("v.alreadyRated",response.getReturnValue());
                if(response.getReturnValue()==true){
                     alert('You have already rated');
                }
               
            }
        });
        $A.enqueueAction(action);
        
    }
})
and add  the apex controller method as below,
 
@AuraEnabled
    public static boolean checkAlreadyRated(string  ratingId){
        boolean rated=false;
        if(ratingId!=null)
            {
                LIST< Rating__C >objRatingList =[select id,name from rating__C where id=:ratingId and rated__C=true limit 1];
                if(objRatingList.size()>0){
                   rated =true;
                }
               
                
            }
        return rated;
    }

regards
Sampath​
SFDC New learnerSFDC New learner
Hi Sampath,

I am getting error as
An internal server error has occurred
Error ID: 2008886120-228752 (1882392599)
I have used your code and and tested apex class method also.
Please help me to fix this error.

Thanks,
Sirisha
SFDC New learnerSFDC New learner
Hi Sampath,
Its working .Thanks again for  the solution.
SFDC New learnerSFDC New learner
Hi  Sampath,
Can you pls guide me ?
https://developer.salesforce.com/forums/ForumsMain?id=9060G0000005dKuQAI
Thanks in Advance.

Thanks,
Sirisha