- Shivdeep Kumar
- NEWBIE
- 435 Points
- Member since 2014
- Accenture Solutions Pvt Ltd
-
ChatterFeed
-
14Best Answers
-
0Likes Received
-
1Likes Given
-
3Questions
-
93Replies
I am facing error on apex class "List has more than 1 row for assignment to SObject"
I am facing errror when execute this class through vf page and also it is showing one record instead of more record .
it is show error "List has more than 1 row for assignment to SObject
Error is in expression '{!getData}' in component <apex:commandButton> in page cpqvf: Class.ProductEntry.getData: line 13, column 1
An unexpected error has occurred. Your development organization has been notified.
"
Please help .
public class ProductEntry{
public List<sObjectWrapper> wrappers{get;set;}
Public string selectedname{get;set;}
public List<PricebookEntry> PriceEntry{get;set;}
public ProductEntry()
{
PriceEntry=new List<PricebookEntry>();
}
public void getData()
{
List<sObjectWrapper> wrapper=new List<sObjectWrapper>();
product2 productList=[select id,name,Units_of_Measure__c from product2 where Bundle_Type__c=:selectedname];
PriceBook2 pricebook=[select id from pricebook2 where name In('BlackBeltHelp V2')];
PriceEntry=[SELECT id,Name,Pricebook2Id,Product2Id,ProductCode,UnitPrice,UseStandardPrice FROM PricebookEntry WHERE Pricebook2Id=:pricebook.id and product2Id=:productList.id];
}
Public List<string> optionList=new List<String>{'Basic','Advance','Primium'};
Public List<Selectoption> getselectedaccnamefields(){
List<Selectoption> lstnamesel = new List<selectoption>();
lstnamesel.add(new selectOption('', '- None -'));
for(String s :optionList){
lstnamesel.add(new selectoption(s,s));
}
return lstnamesel;
}
}
and my viasulforce page is
<apex:page controller="ProductEntry">
<apex:form >
<apex:pageBlock title="Select Product List">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Bundle Type"/>
<apex:selectList size="1" value="{!selectedname}">
<apex:selectOptions value="{!selectedaccnamefields}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockTable value="{!PriceEntry}" var="a">
<apex:column value="{!a.id}"/>
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Pricebook2Id}"/>
<apex:column value="{!a.UnitPrice}"/>
<apex:column value="{!a.ProductCode}"/>
<apex:column value="{!a.UseStandardPrice}"/>
</apex:pageBlockTable>
<apex:pageBlockButtons >
<apex:commandButton value="GetData" action="{!getData}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
-
- devloper sfdc
- May 17, 2018
- Like
- 0
How to edit my custom button to work in Lightning?
/_ui/core/email/author/EmailAuthor?rtype=003&p3_lkid={!GIS_New_Account_Set_Up__c.Id}&retURL=%2F{!GIS_New_Account_Set_Up__c.Id}&p5={!$User.Email}&p24="smorgan@geninfo.com,rmercado@geninfo.com,amoore@geninfo.com,skeele@geninfo.com,scausey@geninfo.com,jdailey@geninfo.com,jsowell@geninfo.com,nprabhakaran@geninfo.com,cvodila@geninfo.com,implogging@geninfo.com,impcontract@geninfo.com&template_id=00X500000015TvQ
Could anyone tell me what I need to change? I've read a few resources and I think I need to create an action but it's not clicking for me. I do not see how I can have the same result which is clicking the action and an email popping up in a new window with all of the information needed from Salesforce (based on an email template I have in place), all the email addresses needed are populated in and all the sales person has to do is click send.
Thank you!
-
- Jaime Blalock
- April 26, 2018
- Like
- 0
issue in using base utility helper method
I am trying to understand how to use base utility helper method in lighting component.
Base.cmp -------- <aura:component abstract="true"> {!v.body} </aura:component> BaseHelper.js -------------- ({ callServer : function(component,method,callback,params) { var action = component.get(method); if (params) { action.setParams(params); } action.setCallback(this,function(response) { var state = response.getState(); if (state === "SUCCESS") { // pass returned value to callback function callback.call(this,response.getReturnValue()); } else if (state === "ERROR") { // generic error handler var errors = response.getError(); if (errors) { console.log("Errors", errors); if (errors[0] && errors[0].message) { throw new Error("Error" + errors[0].message); } } else { throw new Error("Unknown Error"); } } }); $A.enqueueAction(action); } }) ApexController.axpc ------------------- public with sharing class ApexController { @AuraEnabled public static List<Contact> getContacts() { List<Contact> contacts = [select Id, Name, MailingStreet, Phone, Email FROM Contact]; return contacts; } } CallApexClassCmpBase.cmp ------------------------ <aura:component controller="ApexController"> <lightning:card title="Bring Contact data"> <aura:set attribute="actions"> <lightning:button label="Contact Data" onclick="{!c.Condata}" /> </aura:set> </lightning:card> </aura:component> In the controller.js of the above component ({ Condata : function(component,event,helper) { helper.callServer( component, "c.getContacts", function(response) { console.log('Contacts data'+JSON.stringify(response)); } ); } }) <aura:application extends="force:slds"> <c:CallApexClassCmpBase/> </aura:application>when I preview this I am getting an error as below:
This page has an error. You might just need to refresh it. Action failed: etaPrime:CallApexclassCmpBase$controller$Condata [helper.callServer is not a function] Failing descriptor: {etaPrime:CallApexclassCmpBase$controller$Condata}
I am not able to figure out what is causing the issue,
Please help.
smita
-
- smita bhargava
- April 19, 2018
- Like
- 0
Update Campaign Member from Campaign
I've been working on a trigger for a few days and continue to run into roadblocks. I'm currently facing an error stating: Variable Does Not Exist: 'CampaignMember'.
Can anyone please point me in the right direction? Once I can get the list, I'll be able to update the field. But I have had the hardest time simply getting a list of CampaignMembers from Campaigns.
trigger deactivateCampaignMember on Campaign (after insert) { if(Trigger.isAfter){ if(Trigger.isInsert){ Map<id, list<CampaignMember>> campaignMemberMap = new Map<Id, List<CampaignMember>>(); for(campaign camp : [SELECT Id, (SELECT LeadId,ContactId FROM CampaignMembers) FROM Campaign]) { list<CampaignMember> campMemebersList = camp.CampaignMember; if(campMemebersList!= null) { campaignMemberMap.put(camp.Id, campMemebersList); } } } } }
-
- Patrick G. Brown
- October 13, 2017
- Like
- 0
Create case upon record approval
Hi Guys,
My scenario is I need a process that creates a case when a new record called "Change Request" is approved.
However, I cannot find any option under 'approval process' to create a record upon approval. I am unsure of this is actually possible. I hope you can help me.
Thank you,
Roberto
-
- Roberto Cialfi
- May 02, 2017
- Like
- 0
Hi, I m new at salesforce. Anybody help me to write Test class for this apex class.
public Boolean isSelected{get;set;}
public Account accounts{get;set;}
public List<Account> selectedAccounts{get;set;}
// public Boolean sendEmail{get;set;}
public AccountOwnerUpdate(ApexPages.StandardSetController standardController)
{
if(standardController.getSelected().size() == 0){
isSelected = false;
ApexPages.Message msg = new ApexPages.message(ApexPages.Severity.ERROR,'No Account Selected');
ApexPages.addMessage(msg);
}else{
isSelected = true;
selectedAccounts= [SELECT id,name,ownerid from Account where id=:standardController.getSelected()];
accounts = selectedAccounts[0];
// accounts.ownerid = null;
}
}
public PageReference updateAccount()
{
for(Account a: selectedAccounts){
a.ownerid = accounts.ownerid;
}
update selectedAccounts;
return new Pagereference('/001/o');
}
}
-
- sachitanand kumar
- April 25, 2017
- Like
- 0
please help me with process in order to update a field by using flow
I have requirement where i have to update a field in an object using flow. please help me with procedure for the same. below is the exact requirement
in my org i have a object obj with fields FF(formula field), textField i have to update the value of the FF into textField using flow. can you please help me with step by step procedure for the same. Thanks
Best Regrads,
Mohammad Yaseen.
-
- SHAIK MOHAMMAD YASEEN
- April 24, 2017
- Like
- 0
code coverage issue during deployment
I am Facing strange issue. My class has 94% code coverage, i checked in eclipse as well. but while deploying this class it shows code coverage failure, only 61% code coverage, Even though i used RUN specified tests option.
Any help on this will be appriciated.
-
- Abhishek Singh 88
- April 21, 2017
- Like
- 0
NEW CASE button in Opportunity Object
I want to bring the New Case creation button in the opp object. i used as per below,
Its working OK, while creating a new case, But its neither returning to the Opportunity object after case creation nor in the Case object Opportunity lookup , its showing the related Opp ID. Can you plz suggest on my below URL how to achieve it?. Thanks
https://cs6.salesforce.com/500/e?retURL=%2F{!Opportunity.Id}&save_new_url={!Opportunity.Name}
-
- Sourav P
- April 21, 2017
- Like
- 0
Trigger to run Case Assignment Rule when User edit with Inline editing
do you have any trigger to force Case Assignment Rule to run when a User edit with inline editing?
I know that there are some ideas to correct this and the only workaround is to use a trigger.
I'm using this code but is not triggering any Rule:
trigger CaseAssignmentTrigger on Case (before update) { for (Case theCase:trigger.new) { Database.DMLOptions dmo = new Database.DMLOptions(); dmo.assignmentRuleHeader.useDefaultRule = true; theCase.setOptions(dmo); System.debug ('working'); } }
Thank you.
-
- User Migration 6
- April 12, 2017
- Like
- 0
Passing List of Accounts to aura iteration and displaying them in component
Hi Folks, I am having an apex class which is having AuraEnabled method which returns list of accounts to <aura:iteration >. I am not able to display the list in component.Code is very simple nothing complicated. Need help ASAP. <aura:component controller="Accounts"> <aura:attribute name="Acc" type="Account[]" default="{'sObjectType':'Account', 'Name':'', 'Id':''}"/> <aura:iteration items="{!v.Acc}" var="acc"> <p>{!acc.Name}</p> </aura:iteration> </aura:component> //Server side controller public with sharing class Accounts { @AuraEnabled Public Static List<Account> getAccount(){ return [Select Name,id from Account LIMIT 2]; } }
-
- Deepak agarwal 9
- April 11, 2017
- Like
- 0
Aggregate Query Has Too Many Rows for Direct assignment, Use For Loop | Counting Tasks
I am stuggling with this trigger to count the number of open tasks on a lead. I am receiving the following error:
UpdateContactClosedTasks: execution of AfterDelete caused by: System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop: External entry point
Here is the trigger:
trigger UpdateLeadOpenTasks on Task (after insert, after undelete,
after update, after delete) {
// Declare the variables
public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
// Build the list of Leads and Contacts to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
for(Task t: Trigger.new){
if(t.WhoId<>null){
if(string.valueOf(t.WhoId).startsWith('00Q'))
LeadIDs.add(t.WhoId);
}
}
}
if(Trigger.isDelete || Trigger.isUpdate){
for(Task t: Trigger.old){
if(t.WhoId<>null){
if(string.valueOf(t.WhoId).startsWith('00Q'))
LeadIDs.add(t.WhoId);
}
}
}
// Update the Leads
if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Open_Activities__c,
(Select Id From Tasks where IsClosed = False)
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Open_Activities__c = l.Tasks.size()));
update LeadsToUpdate;
}
if(LeadstoUpdate != null && !LeadsToUpdate.isEmpty())
Database.update(LeadsToUpdate);
}
Any help would be greatly appreciated.
-
- Mollie Bodensteiner 6
- April 04, 2017
- Like
- 0
trigger.oldmap returning same values as trigger.newmap
trigger WorkOrderJobRollUp on Work_Order__c (before update, after insert, after delete, after undelete) {
// Check to make sure work order is not being deleted
IF (trigger.isdelete == FALSE)
{
// Run trigger for all situations with the exception of the AFE Approval process
For(Work_Order__c wo : Trigger.New)
{
try
{
Work_Order__c beforeUpdate = Trigger.oldMap.get(wo.ID);
system.debug('Work Order ID New: ' + wo.ID);
system.debug('Work Order ID Old: ' + beforeUpdate.ID);
string oldstatus = beforeUpdate.Work_Order_Status__c;
system.debug('New WO Status: ' + wo.Work_Order_Status__c);
system.debug('Old WO Status: ' + beforeUpdate.Work_Order_Status__c);
system.debug('Old WO Status: ' + trigger.oldmap.get(wo.ID).Work_Order_Status__c);
system.debug('Old WO Status: ' + oldstatus);
IF (wo.Work_Order_Status__c == 'Approved' && beforeUpdate.Work_Order_Status__c == 'Pending Approval') return;
}
catch(exception e){}
}
}
Here is a snippit of the debug log:
14:09:14.853 (9285875790)|USER_DEBUG|[12]|DEBUG|Work Order ID New: a270j0000009ASKAA2 14:09:14.853 (9285880579)|STATEMENT_EXECUTE|[13] 14:09:14.853 (9285889523)|HEAP_ALLOCATE|[13]|Bytes:18 14:09:14.853 (9285894991)|HEAP_ALLOCATE|[13]|Bytes:37 14:09:14.853 (9285898897)|USER_DEBUG|[13]|DEBUG|Work Order ID Old: a270j0000009ASKAA2 14:09:14.853 (9285901596)|STATEMENT_EXECUTE|[15] 14:09:14.853 (9285907986)|VARIABLE_SCOPE_BEGIN|[15]|oldstatus|String|false|false 14:09:14.853 (9285914795)|VARIABLE_ASSIGNMENT|[15]|oldstatus|"Approved" 14:09:14.853 (9285916837)|STATEMENT_EXECUTE|[17] 14:09:14.853 (9285920997)|HEAP_ALLOCATE|[17]|Bytes:23 14:09:14.853 (9285925680)|USER_DEBUG|[17]|DEBUG|New WO Status: Approved 14:09:14.853 (9285928468)|STATEMENT_EXECUTE|[18] 14:09:14.853 (9285932040)|HEAP_ALLOCATE|[18]|Bytes:23 14:09:14.853 (9285935598)|USER_DEBUG|[18]|DEBUG|Old WO Status: Approved 14:09:14.853 (9285938221)|STATEMENT_EXECUTE|[19] 14:09:14.853 (9285964009)|HEAP_ALLOCATE|[19]|Bytes:23 14:09:14.853 (9285968749)|USER_DEBUG|[19]|DEBUG|Old WO Status: Approved 14:09:14.853 (9285971863)|STATEMENT_EXECUTE|[20] 14:09:14.853 (9285974149)|HEAP_ALLOCATE|[20]|Bytes:23 14:09:14.853 (9285978158)|USER_DEBUG|[20]|DEBUG|Old WO Status: Approved
The value of the Work Order Status field is changing from Pending Approval to Approved and I don't want the body of the trigger to fire off when this happens. How does the Trigger.newmap and trigger.oldmap values equal each other?
-
- Michael Davis 15
- April 04, 2017
- Like
- 0
code coverage and functionality due to debug log activation
Today I saw a weird thing in my org, my test class code coverage in sandbox org is 90% but when I tried to deploy in production my test class code coverage becomes 63%.
After activating the debug log in prod org, my test class code coverage becomes the same as sandbox org. How is it possible? due to this my code functionality is not working perfectly in prod but in the sandbox, it is working fine.
If activate the debug log in prod then functionality also works fine.
Please let me know if anyone faced this issue before.
Thanks,
-
- Shivdeep Kumar
- December 17, 2019
- Like
- 0
Test Class for custom controller!!!!
public with sharing class ListContactDetailOnCallController {
public List<Contact> contacts {get;set;}
public Integer contactsCount {get;set;}
public List<Case> cases {get;set;}
public string cPhone {get;set;}
Public ListContactDetailOnCallController(){
cphone=ApexPages.currentPage().getParameters().get('phone');
String orderId=ApexPages.currentPage().getParameters().get('orderId'); cases = [Select Id, Order_Id__c, SuppliedPhone From Case where Order_Id__c =:orderId];
if(cphone!='' && cphone!=null){
contacts = [Select Name, mobilephone, ( Select Id, Order_Id__c, SuppliedPhone From Cases where Order_Id__c =:orderId ) , Email,customer_id__c,birthdate,phone,title,ownerid,source__c from contact where phone like :('%' + cphone + '%') OR MobilePhone like :('%' + cphone + '%') ORDER BY lastModifieddate];
if(contacts.size()==0){
contactsCount=0;
}else if(contacts.size()==1){
contactsCount=1;
}
}else{
contactsCount=0;
}
}
public PageReference redirPage(){
PageReference pR;
if(contactsCount==0){
pR=new PageReference('/003/e?retURL=%2F003%2Fo&con12='+cPhone);
return pR;
}if(contactsCount==1){
pR= new PageReference('/'+contacts[0].Id);
return pR;
}else{
return null;
}
}
}
-
- Shivdeep Kumar
- November 08, 2015
- Like
- 0
Need a trigger
A has a lookup on B.
A has two text field Type and year.
B has one text field Type and year
I want to populate the lookup field of A by matching Type and Year field of A with type and Year field of B. Trigger code should be bulkified. Need help, its urgent. Thank you
-
- Shivdeep Kumar
- July 18, 2015
- Like
- 0
Nested SOQL for FSL Objects
Here is what I have Tried :-
A) SELECT ID , Name, (SELECT FSL__Service_Appointment__r.AppointmentNumber, FSL__Service_Appointment__r.SchedStartTime FROM FSL__Service_Appointment__r WHERE Status = 'Scheduled' ORDER BY SchedStartTime ) FROM Account GROUP BY ID
B) SELECT ID , Name, (SELECT AppointmentNumber, SchedStartTime FROM ServiceAppointment WHERE Status = 'Scheduled' ORDER BY SchedStartTime ) FROM Account GROUP BY ID
Both throws an Error Unable to Undertand the relationship.
- Admin User 8648
- November 16, 2018
- Like
- 0
How to pass Object Id dynamically
I am trying to get the object prefix of Parent objects from child object.
In Case, I have the lookup to Opportunity and 2 custom objects. Here In my scenario, I am trying to create 2 records if an email is sent out to the customer. So, If an email is sent related to Opportunity object, my custom object field need to populate only opportunity id. Similarly with other objects should populate the caseid and that objectid.
I have written my code something like this.
for(Case cs : Trigger.New){
if(cs.Email_Template__c != Null && cs.Email_Template__c != ''){
e = new EmailNotifications();
e.CaseId= cs.id;
e.OpporunityId = cs.Opportunity__c;
e.EngagementId = cs.Engagement_ID__c;
e.SessionId = cs.Session_ID__c;
EmailList.add(e);
}
}
if(EmailList.size()>0){
CaseHandler.sendEmail(EmailList,MapEmailTemplate);
}
public static void sendEmail(List <EmailNotifications> EmailList ,Map <String , CaseEN__c > MapParentEmailTemplate){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
Map<Id, Id> map_Formfields = new Map<Id, Id>();
for(EmailNotifications en:Emaillist){
string myIdPrefix;
myIdPrefix = String.valueOf(en.CaseId).substring(0,3);
if(myIdPrefix == '006'){
map_Formfields.put(en.CaseId,en.OpporunityId);
}
if(myIdPrefix == 'a00'){
map_Formfields.put(en.CaseId,en.EngagementId);
}
if(myIdPrefix == 'a05'){
map_Formfields.put(en.CaseId,en.SessionId);
}
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'abc@abc.com'};
system.debug('toAddresses' +toAddresses);
mail.setToAddresses(toAddresses);
mail.setSubject('Hi');
system.debug('hi');
mail.setSenderDisplayName('Hi');
system.debug('xyz');
String body = 'Dear ' + cas.ContactEmail + ', ';
body += 'First mail';
system.debug('body'+body);
mail.setHtmlBody(body);
mail.setWhatId(cas.Id);
mails.add(mail);
List<Messaging.SendEmailResult> list_mr =Messaging.sendEmail(mails);
Integer i=0;
for(Messaging.SendEmailResult ser : list_mr){
if(ser.isSuccess()){
Messaging.SingleEmailMessage maill = mails[i];
Id caseId = maill.getwhatId();
system.debug('caseId'+caseId);
Id ObjId = map_Formfields.get(caseId);
ManageEmailNotification( etname , myIdPrefix , ObjId,caseId,Emaillist);
}
}
public static void ManageEmailNotification(String EmailTemplateName , String ObjectType , String ObjectId , Id caseId,List <EmailNotifications> EmailList){
list<Email_Notification__c> notificationlist = new list<Email_Notification__c>();
List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
for(EmailNotifications en : EmailList){
if (ObjectType == '006')
{
en.OpporunityId = ObjectId;
}
if (ObjectType == 'a00')
{
en.EngagementId= ObjectId;
}
if (ObjectType == 'a05')
{
system.debug('ObjectType'+ObjectType);
en.SessionId = ObjectId;
system.debug('ObjectId'+ObjectId);
system.debug('ObjectId'+en.SessionId);
}
/*After Sending the Scheduled Email , Details will be updated to Email Notification Object*/
Email_Notification__c em= new Email_Notification__c();
if(en.ScheduledFlag == False){
system.debug('scheduled flag'+en.ScheduledFlag);
if(en.OpporunityId != null)
{
em.opportunity__c = en.OpporunityId;
}
else if (en.SessionId != NUll){
em.Session__c = en.SessionId;
}
else if (en.EngagementId != NULL){
em.Engagement__c = en.EngagementId;
}
em.Case__c = en.CaseId;
em.Status__c = 'Sent';
em.Email_Template__c = en.EmailName;
notificationlist.add(em);
}
/*After Sending the Scheduled Email , Details will be updated to Email Notification Object*/
system.debug('Scheduled Flag boolean'+en.ScheduledFlag);
system.debug('EmailTemplateName'+en.EmailTemplateName);
if(en.ScheduledFlag == True){
system.debug('update ');
Email_Notification__c updatelist = new Email_Notification__c();
system.debug('opp id'+en.OpporunityId);
system.debug('Email_Template__c :::'+ en.EmailName );
updatelist = [select id,status__c,Sent_Date__c from Email_Notification__c where Opportunity__c = :en.OpporunityId ];
updatelist.Status__c = 'Sent';
updatereminderNotification.add(updatelist);
break;
}
/*Check if the any remainder emails need scheduled*/
if(en.ParentEmail == em.Email_Template__c ){
Email_Notification__c em1 = new Email_Notification__c();
if(en.OpporunityId != null)
{
em1.opportunity__c = en.OpporunityId;
}
else if (en.SessionId != NUll){
em1.Session__c = en.SessionId;
}
else if (en.EngagementId != NULL){
em1.Engagement__c = en.EngagementId;
}
em1.Case__c = en.CaseId;
em1.Status__c = 'Scheduled';
system.debug('em1'+em1.Status__c);
system.debug('em1'+em1.Scheduled_Date__c);
em1.Email_Template__c = en.getParentname(en.ParentEmail).Name;
system.debug('em1'+em1.Email_Template__c);
reminderNotification.add(em1);
}
}
if(notificationlist.size()>0){
insert notificationlist;
}
if(updatereminderNotification.size()>0){
Update updatereminderNotification;
}
if(reminderNotification.size()>0){
insert reminderNotification;
}
}
1) How to dynamically I pass the object Id for that particular case?
2) Is there any way I can pass the object name and get the Opportunity prefix or other custom objects?
3) How to avoid writing code multiple times?
4) How to pass id dynamically in Update query
select id,status__c,Sent_Date__c from Email_Notification__c where Opportunity__c = :en.OpporunityId
Please anyone help me on this?
Any help will be greatly appreciated.
Thanks,
Sirisha
- SFDC New learner
- November 16, 2018
- Like
- 0
Test class not covering for execute method
global class ACMContactDocumentExpiration implements Database.Batchable<sObject>,database.stateful { public List<Aircraft_Training__c> AirTrn = new List<Aircraft_Training__c>(); public List<Crew_Staff__c> Crewlist=new List<Crew_Staff__c>(); public List<Experience__c> Exp = new List<Experience__c>(); public List<Training__c> Trn = new List<Training__c>(); public List<Contact> Con = new List<Contact>(); global Database.QueryLocator start(Database.BatchableContext BC) { AirTrn = [Select Id, Name, Experience__c,Experience__r.Name, Aircraft_Rating__c, PPC_Expiration_Date__c, PPC_Date__c, Training_Date__c FROM Aircraft_Training__c WHERE PPC_Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.AL_PPC_Expiration_Days)]; Set<String> AirTrnIds = new Set<String>(); for(Aircraft_Training__c a: AirTrn) { AirTrnIds.add(a.Experience__r.Name); } system.debug('----------'+AirTrnIds.size()); Exp = [Select Id, Name, Contact__c, Contact__r.Id, Last_Recurrent_Date__c FROM Experience__c WHERE Name IN: AirTrnIds AND (Last_Recurrent_Date__c =: Date.today()-Integer.valueOf(System.label.Exp_Last_Recurrent_Days) OR Last_Recurrent_Date__c != null OR Last_Recurrent_Date__c =: null)]; Set<String> ExpIds = new Set<String>(); for(Experience__c e: Exp) { ExpIds.add(e.Contact__r.Id); } system.debug('----------'+ExpIds.size()); Trn = [Select Id, Name, Contact__c, Contact__r.Id, Expiration_Date__c, Exam_Date__c, Training_Type__c FROM Training__c WHERE Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.Training_Expiration_Days) AND (Training_Type__c =: System.label.Training_Type_Intl_Procedures OR Training_Type__c =: System.label.Training_Type_RVSM)]; Set<String> TrnIds = new Set<String>(); for(Training__c t: Trn) { TrnIds.add(t.Contact__r.Id); } system.debug('----------'+TrnIds.size()); Con = [Select Id, Email FROM Contact WHERE ID IN: ExpIds OR ID IN: TrnIds]; Set<String> ConIds = new Set<String>(); for(Contact c: Con) { ConIds.add(c.Id); } system.debug('----------'+ConIds.size()); string query= 'Select Id, Contact__c, Contact__r.Name, Active_License__r.License_Type__c, Active_Medical__r.Medical_Type__c, Mandate_Record_Type__c, Contact_Record_Type__c, License_Expiration_Date__c, Medical_Expiration_Date__c,Training_Expiration_Date__c, Crew_Email__c from Crew_Staff__c WHERE Contact__r.Id IN : ConIds'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Crew_Staff__c> scope) { List<Crew_Staff__c> newCrew = new List<Crew_Staff__c>(); Set<Id> newCrewIds = new Set<Id>(); for(Crew_Staff__c crew:scope) { if( ((crew.Contact_Record_Type__c == 'Pilot') && (crew.Mandate_Record_Type__c == 'ACM') && (crew.Crew_Email__c != null)) || (date.valueof(crew.License_Expiration_Date__c) == System.today()+Integer.valueOf(System.label.Date_2)) || (date.valueof(crew.Medical_Expiration_Date__c) == System.today()+Integer.valueof(System.label.Medical_Expiration_Days)) ) { Crewlist.add(crew); } newCrewIds.add(crew.Id); } system.debug('----------'+Crewlist.size()); } global void finish(Database.BatchableContext BC) { system.debug('------>'+Crewlist.size()); List<Messaging.SingleEmailMessage> maillist = new List<Messaging.SingleEmailMessage>(); if(Crewlist.size()>0) { for(Crew_Staff__c crewrec:Crewlist) { // Query on OrgWideEmailAddress would set "FROM address" in the email OrgWideEmailAddress[] owea = [Select Id From OrgWideEmailAddress where Address = 'test@test.com']; Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); if (owea.size()>0) { mail.setOrgWideEmailAddressId(owea.get(0).Id); } mail.setSubject('Pilot Documents Expiring Soon'); mail.setToAddresses(new String[]{crewrec.Crew_Email__c}); mail.setReplyTo('flightops@acass.ca'); string htmlBody; htmlBody = '<p><span style=font-family:calibri, monospace> Dear '+ crewrec.Contact__r.Name +', </span> </p>' + '<p><span style=font-family:calibri, monospace> This is a friendly reminder that you have the following documents coming due for renewal: </span></br>'; String lType = crewrec.Active_License__r.License_Type__c; Date lExpDate = date.newInstance(crewrec.License_Expiration_Date__c.year(), crewrec.License_Expiration_Date__c.month(), crewrec.License_Expiration_Date__c.day() ); String mType = crewrec.Active_Medical__r.Medical_Type__c; Date mExpDate = crewrec.Medical_Expiration_Date__c; htmlBody += +lType+ ' license will expire on ' +lExpDate+'</br>'; htmlBody += +mType+ ' medical will expire on ' +mExpDate+'</br>'; for(Training__c t: Trn) { String tType = t.Training_Type__c; Date tExpDate = t.Expiration_Date__c; htmlBody += +tType+' training will expire on ' +tExpDate +'</br>'; } for(Aircraft_Training__c a1: AirTrn) { String aName = a1.Aircraft_Rating__c; Date aPPCexp = a1.PPC_Expiration_Date__c; htmlBody += +aName+' aircraft training will expire on ' + aPPCexp +'</br>'; } htmlBody += '<p><span style=font-family:calibri, monospace> Please send clear, colour photos/scans the renewed document prior to the expiration date. </span></p>'+ '<p><span style=font-family:calibri, monospace>Kindest regards,</span></br>'+ '<span style=font-family:calibri, monospace>Flight Operations </span></p>'; mail.setHtmlBody(htmlBody); maillist.add(mail); } Messaging.sendEmail(maillist); } }
@isTest public class SendEmailToCrewJobscheduledtest { public static testmethod void myUnitTest() { List<Contact> con = new List<Contact>(); Contact c = new Contact( Accident_Note__c = 'Test',FirstName = 'Test',LastName = 'test'); con.add(c); insert con; Test.startTest(); String CRON_EXP = '0 0 0 3 9 ? 2022'; String jobId = System.schedule('SendEmailToCrewJobscheduledtest', CRON_EXP, new SendEmailToCrewJobscheduled()); CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; System.assertEquals(0, ct.TimesTriggered); System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime)); ACMContactDocumentExpiration b = new ACMContactDocumentExpiration(); Database.QueryLocator q1 = b.start(null); Database.executeBatch(b, 200); Test.stopTest(); } }
- Jay reddy
- November 15, 2018
- Like
- 0
SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true
SELECT Id, MasterLabel
FROM LeadStatus WHERE IsConverted=true,
result is only one record:
SELECT Id, MasterLabel
FROM LeadStatus WHERE IsConverted=false:
result is 3 records:
is it like only 4 master lables we have in leadstatus
- DEV_CG
- November 15, 2018
- Like
- 0
I need to share a public calandar with Comminity users. So that it will share just my avaialbility and NOT details of events with community users. Is there a paid/free app or any other solution?
I need to share a public calandar with Comminity users. So that it will share just my avaialbility and NOT details of events with community users. It should allow community user to add time on my calandar.
Is there a paid/free app or any other solution?
- IntegrationGuy
- November 15, 2018
- Like
- 0
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:TriggerToUpdatePRPCInvoiceDisplayName: System.LimitException: Too many DML rows: 10001(please help me)
public class ZuoraProductRatePlanChargeTriggerHandler{
public static void UpdatePRPCIDNLineitems(map<Id,zqu__ProductRatePlanCharge__c> mapPRPC){
Map<Id,Id> mapInvName = new Map<Id,Id>();
List<Zuora__SubscriptionRatePlan__c> lstSub = new List<Zuora__SubscriptionRatePlan__c>();
for(SPG_Product_User__c lstpc:[select id,Subscription__c,Rate_Plan_Charge__c from SPG_Product_User__c where Rate_Plan_Charge__c IN :mapPRPC.keyset() AND Subscription__c != Null])
{
mapInvName.put(lstpc.Subscription__c,lstpc.Rate_Plan_Charge__c);
}
for(Zuora__SubscriptionRatePlan__c lstsrp : [select id,PRPC_Invoice_Display_Name__c,Zuora__Subscription__c from Zuora__SubscriptionRatePlan__c where Zuora__Subscription__c IN :mapInvName.keyset()])
{
Id IdVal =mapInvName.get(lstsrp.Zuora__Subscription__c);
lstsrp.PRPC_Invoice_Display_Name__c = mapPRPC.get(IdVal).Invoice_Display_Name__c;
lstSub.add(lstsrp);
}
if(lstSub.size()>0)
update lstSub ;
}
}
Trigger:
trigger TriggerToUpdatePRPCInvoiceDisplayName on zqu__ProductRatePlanCharge__c(after insert, after update)
{
if(Trigger.isAfter)
{
// Added this line as part of US#1168855
if ((Trigger.isInsert || Trigger.isUpdate)&& (Test.isRunningTest() ||SPG_checkRecursive.runOnce()) ){
ZuoraProductRatePlanChargeTriggerHandler.UpdatePRPCIDNLineitems(trigger.newmap);
}
}
}
- Sri 7
- November 15, 2018
- Like
- 0
variable not found error
Below is my code which looks prety good for me but dont know what the problem is.
I get the below error sayimg Variable does not exist: CampaignId in line 10 and 20
trigger LeadCampaignTrigger on Lead(before insert, before update){
Id canadaLeadRecTypId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Canada Leads').getRecordTypeId();
Id usLeadRecTypId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('US Leads').getRecordTypeId();
Map<String, String> CampaignIdMap = new Map<String, String>();
Set<String> setOfCampaignIds = new Set<String>();
for(Lead l : Trigger.new){
if(l.RecordTypeId == canadaLeadRecTypId || l.RecordTypeId == usLeadRecTypId){
setOfCampaignIds.add(l.CampaignId);
}
}
for(Campaign camp : [SELECT Id, Name FROM Campaign WHERE Id IN :setOfCampaignIds]){
CampaignIdMap.put(camp.Id, camp.Name);
}
for(Lead l : Trigger.new){
if(l.RecordTypeId == canadaLeadRecTypId || l.RecordTypeId == usLeadRecTypId){
l.Campaign_Name__c = CampaignIdMap.get(l.CampaignId);
}
}
}
- Sneha Goli 7
- May 29, 2018
- Like
- 0
Trigger when attachment is inserted: help!
trigger addToCList on Contact (after update) {
for (Contact cont : Trigger.New)
{
if (cont.Jenzabar_ID__c !=null)
{
if (cont.TargetX_SRMb__Student_Type__c=='First-Time Freshman'||cont.TargetX_SRMb__Student_Type__c=='International Freshman')
{
if (cont.TargetX_SRMb__Status__c=='Deposit Paid')
{
addAllAttachments.getAttachmentsForStudent(cont.X18_digit_ID__c,cont.Jenzabar_ID__c);
}
} else
{
if (cont.TargetX_SRMb__Status__c=='Accept')
{
addAllAttachments.getAttachmentsForStudent(cont.X18_digit_ID__c,cont.Jenzabar_ID__c);
- Jennifer24w
- May 25, 2018
- Like
- 0
- Niharika Goud
- May 18, 2018
- Like
- 0
Dusting off Apex Chops
Sadly I havent been writing apex for a long time and could use some help. I'm repurposing some code I have to compare two records and throw an error if there is a match on date. This is a before trigger that calls the below helper class . I'm getting a null pointer error on line 30 when I try to get the date from my Map which leads me to beleive I'm not populating my map correctly. Any help would be greatly appreciated.
public class EventTriggerHelper { public static void CheckForDoubleBookedLocations(List<Event__c> locEvts){ //collect ID's to reduce data calls List<ID> locationIds = new List<ID>(); Map<ID,Event__c> requestedEventTime = new map<ID,Event__c>(); //get all Locations related to the trigger for(Event__c newEvent : locEvts){ if(newEvent.Event_Location__c != null){ locationIds.add(newEvent.Event_Location__c); } //Populate Map List<Event__c> relatedEvents = [SELECT Event_Location__c, Start_Date_Time__c FROM Event__c WHERE Event_Location__c IN :locationIds]; for(Event__c relatedEvent : relatedEvents){ requestedEventTime.put(relatedEvent.Id, relatedEvent); //get existing events to check against list<Event__c> existingEvents = [SELECT ID, Event_Location__c, Start_Date_Time__c FROM Event__c WHERE Event_Location__c IN :locationIDs]; //check one list against the other for(Event__c evs : locEvts){ DateTime existStartTime = requestedEventTime.get(evs.Id).Start_Date_Time__c; for(Event__c event : existingEvents){ ////Add location and end date range Logic if(event.Start_Date_Time__c == existStartTime){ event.addError('The Location is already booked at that time'); } } } } } } }
- Jonathan Osgood 3
- May 17, 2018
- Like
- 0
I am facing error on apex class "List has more than 1 row for assignment to SObject"
I am facing errror when execute this class through vf page and also it is showing one record instead of more record .
it is show error "List has more than 1 row for assignment to SObject
Error is in expression '{!getData}' in component <apex:commandButton> in page cpqvf: Class.ProductEntry.getData: line 13, column 1
An unexpected error has occurred. Your development organization has been notified.
"
Please help .
public class ProductEntry{
public List<sObjectWrapper> wrappers{get;set;}
Public string selectedname{get;set;}
public List<PricebookEntry> PriceEntry{get;set;}
public ProductEntry()
{
PriceEntry=new List<PricebookEntry>();
}
public void getData()
{
List<sObjectWrapper> wrapper=new List<sObjectWrapper>();
product2 productList=[select id,name,Units_of_Measure__c from product2 where Bundle_Type__c=:selectedname];
PriceBook2 pricebook=[select id from pricebook2 where name In('BlackBeltHelp V2')];
PriceEntry=[SELECT id,Name,Pricebook2Id,Product2Id,ProductCode,UnitPrice,UseStandardPrice FROM PricebookEntry WHERE Pricebook2Id=:pricebook.id and product2Id=:productList.id];
}
Public List<string> optionList=new List<String>{'Basic','Advance','Primium'};
Public List<Selectoption> getselectedaccnamefields(){
List<Selectoption> lstnamesel = new List<selectoption>();
lstnamesel.add(new selectOption('', '- None -'));
for(String s :optionList){
lstnamesel.add(new selectoption(s,s));
}
return lstnamesel;
}
}
and my viasulforce page is
<apex:page controller="ProductEntry">
<apex:form >
<apex:pageBlock title="Select Product List">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Bundle Type"/>
<apex:selectList size="1" value="{!selectedname}">
<apex:selectOptions value="{!selectedaccnamefields}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockTable value="{!PriceEntry}" var="a">
<apex:column value="{!a.id}"/>
<apex:column value="{!a.name}"/>
<apex:column value="{!a.Pricebook2Id}"/>
<apex:column value="{!a.UnitPrice}"/>
<apex:column value="{!a.ProductCode}"/>
<apex:column value="{!a.UseStandardPrice}"/>
</apex:pageBlockTable>
<apex:pageBlockButtons >
<apex:commandButton value="GetData" action="{!getData}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
- devloper sfdc
- May 17, 2018
- Like
- 0
code coverage issue of test class
I am wrirting test class. I have included all the objects in my test class but its coverage is 0%. Can anyone suggest me what to do so test coverage will increase.
Apex Class:
/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
Create book record from the inbound email
*/
global class InboundEmailtoVacancy implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
Review_Vacancy__c vacancy = new Review_Vacancy__c();
//----Insert Record
vacancy.Email_Subject__c = email.subject;
vacancy.From_Address__c = email.fromAddress;
if(email.htmlBody == Null){
vacancy.Email_Body__c = email.plainTextBody;
}
else
vacancy.Email_Body__c = email.htmlBody;
String emailBody1 = email.plainTextBody;
String s1 = 'Order Reference:';
String s2 = 'Job:';
String s3 = 'Job Location:';
String s4 = 'StartDate:';
String s5 = 'EndDate:';
String s6 = 'Start Time';
String s7 = 'End Time';
String s8 = 'Number Required:';
String s9 = 'Additional Details';
String s10 = 'Borough:';
//-----Order Num
String AfterS1 = emailBody1.substringAfter(s1);
String OrRefS1 = AfterS1.substringBefore(s2);
System.debug('AfterS1--Order Ref----'+AfterS1);
System.debug('OrRefS1--Order Ref----'+OrRefS1);
//-----Job
String AfterS2 = emailBody1.substringAfter(s2);
String OrRefS2 = AfterS2.substringBefore(s3);
//-----Job Location
String AfterS3 = emailBody1.substringAfter(s3);
String OrRefS3 = AfterS3.substringBefore(s4);
//-----StartDate
String AfterS4 = emailBody1.substringAfter(s4);
String OrRefS4 = AfterS4.substringBefore(s5);
//-----EndDate
String AfterS5 = emailBody1.substringAfter(s5);
String OrRefS5 = AfterS5.substringBefore(s6);
//-----Start Time
String AfterS6 = emailBody1.substringAfter(s6);
String OrRefS6 = AfterS6.substringBefore(s7);
//-----End Time
String AfterS7 = emailBody1.substringAfter(s7);
String OrRefS7 = AfterS7.substringBefore(s8);
//-----Number Required
String AfterS8 = emailBody1.substringAfter(s8);
String OrRefS8 = AfterS8.substringBefore(s9);
//-----Borough
String AfterS10 = emailBody1.substringAfter(s10);
String OrRefS10 = AfterS10.substringBefore(s9);
//-----Additional Details
String AfterS9 = emailBody1.substringAfter(s9);
//String OrRefS9 = AfterS9.substringBefore(s10);
vacancy.Order_Reference__c = OrRefS1;
vacancy.Job__c = OrRefS2;
vacancy.Job_Location__c = OrRefS3;
vacancy.StartDate__c = OrRefS4;
vacancy.EndDate__c = OrRefS5;
vacancy.Start_Time__c = OrRefS6;
vacancy.End_Time__c = OrRefS7;
vacancy.Number_Required__c = OrRefS8;
vacancy.Borough__c = OrRefS10;
//vacancy.Additional_Details__c = OrRefS9;
insert vacancy ;
// Save attachments, if any Image or text file
If((email.textAttachments) != Null){
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = vacancy.Id;
insert attachment;
}
}
// Save Email as PDF attachments
if(email.htmlBody == Null){
Attachment attachment1 = new Attachment();
attachment1.Name = 'EmailBody';
attachment1.Body = Blob.valueOf(email.plainTextBody);
attachment1.ParentId = vacancy.Id;
insert attachment1;
}
else
{
Attachment attachment1 = new Attachment();
attachment1.Name = 'EmailBody';
attachment1.Body = Blob.valueOf(email.htmlBody);
attachment1.ParentId = vacancy.Id;
insert attachment1;
}
result.success = true;
return result;
}
}
Test Class:
//Test Method for main class
@isTest
private class InboundEmailtoVacancyTestTest{
static testMethod void testEmailServiceHtmlBodyNull()
{
// create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// setup the data for the email
email.subject = 'Test Job Applicant';
email.fromAddress = 'someaddress@email.com';
email.htmlBody = null;
email.plainTextBody = 'Test plainTextBody';
env.fromAddress = 'someaddress@email.com';
Review_Vacancy__c vacancy = new Review_Vacancy__c();
system.debug(' email.htmlBody1 ************************'+email.htmlBody);
vacancy.Email_Body__c = email.plainTextBody;
vacancy.Email_Subject__c = email.subject;
vacancy.From_Address__c = email.fromAddress;
insert vacancy;
system.debug('Insert Vacancy'+vacancy);
// add an Binary attachment
// Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
// attachment.body = blob.valueOf('my attachment text');
// attachment.fileName = 'textfileone.txt';
// attachment.mimeTypeSubType = 'text/plain';
//email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
// add an Text atatchment
Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
Attachment attachment = new Attachment();
attachment.Name = 'textfileone.txt';
attachment.body = blob.valueOf('my attachment text');
attachment.ParentId = vacancy.Id;
insert attachment;
email.textAttachments = new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
// call the email service class and test it with the data in the testMethod
/// inBoundEmail testInbound=new inBoundEmail();
//testInbound.handleInboundEmail(email, env);
// Create Attachmenat data
Attachment attachmnt =new Attachment();
attachmnt.name='textfileone.txt';
attachmnt.body =blob.valueOf('my attachment text');
attachmnt.ParentId =vacancy.Id;
insert attachmnt ;
}
static testMethod void testEmailServiceHtmlBodyNotNull() {
system.debug('testEmailService testEmailServiceHtmlBodyNotNull***************');
// create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
system.debug('Inbound Email testEmailServiceHtmlBodyNotNull**********************');
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
system.debug('Inbound Envelope testEmailServiceHtmlBodyNotNull**********************');
email.subject = 'Test Job Applicant';
email.fromname = 'FirstName LastName';
email.htmlBody = 'Test htmlBody';
email.plainTextBody = 'Test plainTextBody';
env.fromAddress = 'someaddress@email.com';
Review_Vacancy__c vacancy = new Review_Vacancy__c();
vacancy.Email_Subject__c = email.subject;
vacancy.From_Address__c = email.fromAddress;
system.debug(' Review_Vacancy__c Obj testEmailServiceHtmlBodyNotNull************************');
system.debug(' email.htmlBody testEmailServiceHtmlBodyNotNull ************************'+email.htmlBody);
String s1;
String s2;
String s3;
String s4;
vacancy.Email_Body__c = email.htmlBody;
String emailBody1 = email.plainTextBody;
s1 = 'Order Reference:';
s2 = 'Job:';
s3 = 'Job Location:';
s4 = 'StartDate:';
String s5 = 'EndDate:';
String s6 = 'Start Time';
String s7 = 'End Time';
String s8 = 'Number Required:';
String s9 = 'Additional Details';
String s10 = 'Borough:';
//-----Order Num
String AfterS1 = s1;
String OrRefS1 = s2;
String AfterS2 = s2;
String OrRefS2 = s3;
//-----Job Location
String AfterS3 = s3;
String OrRefS3 = s4;
//-----StartDate
String AfterS4 = s4;
String OrRefS4 = s5;
//-----EndDate
String AfterS5 = s5;
String OrRefS5 = s6;
//-----Start Time
String AfterS6 = s6;
String OrRefS6 = s7;
//-----End Time
String AfterS7 = s7;
String OrRefS7 = s8;
//-----Number Required
String AfterS8 = s8;
String OrRefS8 = s9;
//-----Borough
String AfterS10 = s10;
String OrRefS10 = s9;
//-----Additional Details
String AfterS9 = s9;
vacancy.Order_Reference__c = OrRefS1;
vacancy.Job__c = OrRefS2;
vacancy.Job_Location__c = OrRefS3;
vacancy.StartDate__c = OrRefS4;
vacancy.EndDate__c = OrRefS5;
vacancy.Start_Time__c = OrRefS6;
vacancy.End_Time__c = OrRefS7;
vacancy.Number_Required__c = OrRefS8;
vacancy.Borough__c = OrRefS10;
insert vacancy;
system.debug('Insert Vacancy testEmailServiceHtmlBodyNotNull'+vacancy);
}
}
Thanks,
Utz
- SalesforceUser11
- May 14, 2018
- Like
- 0
Code coverage issue for Lightning controller
Please check my code in code sample and suggest me how to improve remaining code coverage.
If i did any mistake correct me.
controller : public class ctssupportform { public static List<Attachment> attachments; public static final Integer DEFAULT_ATTACHMENT_NO=1; public String sobjId {get; set;} public String Appname{get; set;} public static Map<String, BMCServiceDesk__Category__c> catMap ; @AuraEnabled public static id Savesupportform(Case casedata, String fileName, String base64Data, String contentType){ id RcrdTypeid= Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('Agent Helpdesk').getRecordTypeId(); System.debug('Casedata@@@@@@@@@@@@@@'+RcrdTypeid); Casedata.recordtypeid=RcrdTypeid;//'0120U0000000Aju'; System.debug('Casedata@@@@@@@@@@@@@@'+Casedata); insert Casedata; System.debug('Casedata@@@@@@@@@@@@@@'+Casedata); List<BMCServiceDesk__Category__c> lstcat = [Select Id,Name from BMCServiceDesk__Category__c limit 50000]; catMap = new Map<String, BMCServiceDesk__Category__c>(); for (BMCServiceDesk__Category__c c : lstcat ){ catMap.put(c.Name, c); } System.debug('catMap@@@@@@@@@@@@@@'+catMap); List<BMCServiceDesk__Impact__c> lstimp = [Select Id,Name from BMCServiceDesk__Impact__c limit 4]; Map<String, BMCServiceDesk__Impact__c> impmap = new Map<String, BMCServiceDesk__Impact__c>(); for (BMCServiceDesk__Impact__c i : lstimp){ impmap.put(i.Name, i); } System.debug('impmap@@@@@@@@@@@@@@'+impmap); List<BMCServiceDesk__Urgency__c> lsturg = [Select Id,Name from BMCServiceDesk__Urgency__c limit 4]; Map<String, BMCServiceDesk__Urgency__c> urgmap = new Map<String, BMCServiceDesk__Urgency__c>(); for (BMCServiceDesk__Urgency__c u : lsturg){ urgmap.put(u.Name, u); } List<User> lstuser = [Select Id,Name from user limit 50000]; Map<String, User> usermap = new Map<String, User>(); for (User u1 : lstuser){ usermap.put(u1.Name, u1); } System.debug('urgmap@@@@@@@@@@@@@@'+usermap); System.debug('@@@@@@@@@@@@@@@@'+Casedata); base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8'); System.debug('@@@@@@@@@@@@@@@@'+base64Data ); //base64Data = 'Test'; Attachment oAttachment = new Attachment(); oAttachment.parentId = casedata.id; oAttachment.Body = EncodingUtil.base64Decode(base64Data); oAttachment.Name = fileName; oAttachment.ContentType = contentType; insert oAttachment; BMCServiceDesk__Incident__c inc = new BMCServiceDesk__Incident__c(); inc.Cases__c = casedata.id; inc.BMCServiceDesk__incidentDescription__c = casedata.Type_Of_Ticket__c; string newlowerstringcategory = (casedata.Applications__c).trim(); System.debug('newlowerstringcategory@@@'+ newlowerstringcategory); system.debug('catMap.get(newlowerstringcategory) '+catMap.get(newlowerstringcategory)); if(catMap.get(newlowerstringcategory)!= null) { inc.BMCServiceDesk__FKCategory__c = catMap.get(newlowerstringcategory).id; System.debug('1111111111111111'+ catMap.get(newlowerstringcategory)); System.debug('11111111111111111'+ inc.BMCServiceDesk__FKCategory__c); } string newlowerstringuser = casedata.OwnerId; System.debug('11111111111111111'+ newlowerstringuser); if(usermap.get(newlowerstringuser)!= null) { inc.BMCServiceDesk__FKClient__c= usermap.get(newlowerstringuser).id; System.debug('1111111111111111'+ usermap.get(newlowerstringuser)); System.debug('11111111111111111'+ inc.BMCServiceDesk__FKClient__c); } //inc.BMCServiceDesk__FKClient__c = casedata.OwnerId; inc.BMCServiceDesk__Service_Request_Title__c = casedata.Subject; System.debug('11111111111111111'+ inc.BMCServiceDesk__Service_Request_Title__c); string newlowerstringImpact = casedata.Impact__c.touppercase(); System.debug('newlowerstringImpact '+ newlowerstringImpact ); if(impmap.get(newlowerstringImpact) != null) inc.BMCServiceDesk__FKImpact__c = impmap.get(newlowerstringImpact).id; System.debug('impmap_getnewlowerstringImpact_id'+ impmap.get(newlowerstringImpact).id ); System.debug('11111111111111111'+ inc.BMCServiceDesk__FKImpact__c); string newupperstringUrgency = casedata.Urgency__c.touppercase(); System.debug('newupperstringUrgency '+ newupperstringUrgency ); if(urgmap.get(newupperstringUrgency) != null) inc.BMCServiceDesk__FKUrgency__c= urgmap.get(newupperstringUrgency).id; System.debug('11111111111111111'+ inc.BMCServiceDesk__FKUrgency__c); inc.BMCServiceDesk__incidentDescription__c= casedata.Description +' '+casedata.Type_Of_Ticket__c+' '+casedata.Justification__c; //inc.BMCServiceDesk__incidentDescription__c= casedata.Justification__c ; insert inc; System.debug('@@@@@@@@@@@@@@@@@@@@'+inc); Attachment oAttachment1 = new Attachment(); oAttachment1.parentId = inc.id; oAttachment1.Body = EncodingUtil.base64Decode(base64Data); oAttachment1.Name = fileName; oAttachment1.ContentType = contentType; insert oAttachment1; System.debug('@@@@@@@@@@@@@@@@@@@@'+oAttachment1); return casedata.id; } } Test class : @IsTest(SeeAllData=true) Private class Test_ctssupportform { @IsTest static void Savesupportform() { /*Case cs = new Case(); cs.Status = 'open'; cs.Helpdesk_Case_Resolution__c = 'Test 123'; cs.Helpdesk_Case_Status__c = 'Closed'; cs.Incident_Owner__c = 'Naveen'; cs.Incident_Number__c = '12345'; Insert cs; update cs;*/ case cs1 = [Select id,Status,Helpdesk_Case_Resolution__c,Helpdesk_Case_Status__c,Incident_Owner__c,Incident_Number__c from case Limit 1]; BMCServiceDesk__Category__c cat = new BMCServiceDesk__Category__c(); cat.Name='SAR'; cat.BMCServiceDesk__AvailableForIncidents__c=true; cat.BMCServiceDesk__inactive__c=false; insert cat; //update cat; BMCServiceDesk__Incident__c inc = new BMCServiceDesk__Incident__c(); inc.Assigned_Staff__c='005800000045QSjAAM'; inc.Resolution_Summary__c='resolved'; inc.Service_Request_Form_Type__c='SAR'; inc.BMCServiceDesk__incidentDescription__c='FSJ SAR test 123'; inc.Resource_Type__c='New Contractor'; inc.Start_Date__c = Date.Today(); inc.SRF_Location__c='Australia'; inc.Cases__c = cs1.id; inc.BMCServiceDesk__FKCategory__c=cat.Id; try{ insert inc; //Update Inc; }catch(System.LimitException e){ } Attachment attach=new Attachment(); attach.Name='Unit Test Attachment'; Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); attach.body=bodyBlob; attach.parentId=cs1.id; insert attach; // update attach; List<Attachment> attachments=[select id, name from Attachment where parent.id=:cs1.id]; System.assertEquals(1, attachments.size()); string filename = 'Testfile'; string fileEncoded = 'UTF-8 '; string type = 'Test'; try{ ctssupportform.Savesupportform(cs1,filename, fileEncoded, type); }catch(System.DmlException e){ } } }
Thanks in advance
- Kumar G
- May 10, 2018
- Like
- 0
dynamic table in lighning
Like : There have 3 rows. If the user clicks the expand option of the first row then there will open a sub(child) row for the first row. If the user clicks on the expand option of the second row, there will also open a child row. For the third row also it will happen same. Finally, there will be 6 rows in the table.
- Suvankar Chakraborty
- May 10, 2018
- Like
- 0
Show/Hide or aura:if implementation in lightning component
I have one requirement. I have a dataTable with pagination concept.
I have four images on top of my dataTable and I have onclick event for each and every image.
After i checked the record i need to click on any one of image then it navigate to another component.
For that i implemented var evt = $A.get("e.force:navigateToComponent");
But the issue is i need to access my table in sites concept(Public Access).
So at that time var evt = $A.get("e.force:navigateToComponent"); this functionality is not working and static resource images not getting.
So i think need to implement this one in aura:if or Show/Hide concept.
Kindly any one help me on this how to achieve this requirement.
Thanks in advance...
Reference Code:
Component:
<aura:component controller="LP_PageNationController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="ContactList" type="Contact[]"/>
<aura:attribute name="PageNumber" type="integer" default="1"/>
<aura:attribute name="TotalPages" type="integer" default="0"/>
<aura:attribute name="TotalRecords" type="integer" default="0"/>
<aura:attribute name="RecordStart" type="integer" default="0"/>
<aura:attribute name="RecordEnd" type="integer" default="0"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:attribute name="recdId" type="String" />
<aura:attribute name="sortedDirection" type="String" default="asc"/>
<aura:attribute name="sortedBy" type="String" default="Name"/>
<div >
<div class="bgcolor">
<h1 class="dvLogoGreen textpadHeader">Text1</h1>
<h1 class="dvLogoGreen textpad">Text2</h1>
<div class="slds-box slds-m-around_xx-large">
<h1 class="slds-text-heading--medium">Text3</h1>
<br/>
<lightning:layout horizontalAlign="spread" verticalAlign="center" multipleRows="true" >
<div class="dvContent">
<lightning:layout >
<lightning:layoutItem size="3" padding="around-small">
<div class="img " >
<img style="height: 100px;" src="/resource/LP_Images/LP_Images/img1.png" onclick="{!c.clicktile1}"/>
<h1>TEXT1</h1>
</div>
</lightning:layoutItem>
<lightning:layoutItem size="3" padding="around-small">
<div class="img1" >
<img style="height: 100px;" src="/resource/LP_Images/LP_Images/img2.png" onclick="{!c.clicktile2}"/>
<h1>TEXT2</h1>
</div>
</lightning:layoutItem>
<lightning:layoutItem size="3" padding="around-small">
<div class="img2" ><img style="height: 100px;" src="/resource/LP_Images/LP_Images/img3.png" align="middle" onclick="{!c.clicktile3}"/>
<h1>TEXT3</h1>
</div>
</lightning:layoutItem>
<lightning:layoutItem size="3" padding="around-small">
<div class="img3" style="text-align: left">
<img style="height: 100px;" src="/resource/LP_Images/LP_Images/img4.png" onclick="{!c.clicktile4}"/>
<h1>TEXT4</h1>
</div>
</lightning:layoutItem>
</lightning:layout>
<div class="slds-list_horizontal slds-wrap">
</div>
</div>
</lightning:layout>
<div class="wid slds-float_right">
<ui:inputSelect aura:id="pageSize" label="Display Records Per Page: " change="{!c.onSelectChange}">
<ui:inputSelectOption text="10" label="10" value="true"/>
<ui:inputSelectOption text="15" label="15"/>
<ui:inputSelectOption text="20" label="20"/>
</ui:inputSelect>
<br/>
</div>
<p class="slds-p-horizontal_small slds-box">
<lightning:datatable data="{!v.ContactList}" columns="{! v.mycolumns }" keyField="id" maxRowSelection="1" onrowselection="{!c.getSelectedName }" onsort="{!c.updateColumnSorting}" sortedBy="{!v.sortedBy}" sortedDirection="{!v.sortedDirection}" selectedRows="{! v.selectedRows }" />
</p>
<div class="slds-clearfix">
<div class="slds-page-header" role="banner">
<div class="slds-float_right">
<lightning:button disabled="{!v.PageNumber == 1}" variant="brand" aura:id="prevPage" label="Prev" onclick="{!c.handlePrev}" />
<lightning:button disabled="{!v.PageNumber == v.TotalPages}" aura:id="nextPage" variant="brand" label="Next" onclick="{!c.handleNext}"/>
</div>
<p class="slds-page-header__title">{!v.RecordStart}-{!v.RecordEnd} of {!v.contactList} | Page {!v.PageNumber} of {!v.TotalPages}</p>
</div>
</div>
</div>
</div></div>
</aura:component>
=========================================================
Controller.Js
({
doInit: function(component, event, helper) {
var pageNumber = component.get("v.PageNumber");
var pageSize = component.find("pageSize").get("v.value");
helper.getContactList(component, pageNumber, pageSize);
component.set('v.mycolumns', [
{label: 'Contact Name', fieldName: 'Name', type: 'Name',sortable:'true'},
{label: 'Phone Number', fieldName: 'Phone', type: 'Phone',sortable:'true'},
{label: 'Email ID', fieldName: 'Email', type: 'Email',sortable:'true'}
]);
helper.sortData(component, component.get("v.sortedBy"), component.get("v.sortedDirection"));
},
updateColumnSorting: function (cmp, event, helper) {
var fieldName = event.getParam('fieldName');
var sortDirection = event.getParam('sortDirection');
cmp.set("v.sortedBy", fieldName);
cmp.set("v.sortedDirection", sortDirection);
helper.sortData(cmp, fieldName, sortDirection);
},
handleNext: function(component, event, helper) {
debugger;
//var selectedRows = event.getParam('selectedRows');
//component.set('v.selectedRows', false);
component.set("v.selectedRows", " ");
var pageNumber = component.get("v.PageNumber");
var pageSize = component.find("pageSize").get("v.value");
alert(pageSize);
pageNumber++;
helper.getContactList(component, pageNumber, pageSize);
},
handlePrev: function(component, event, helper) {
debugger;
// var selectedRows = event.getParam('selectedRows');
// component.set('v.selectedRows', false);
// var selectedRows = event.getParam('selectedRows');
// selectedRows.length = 0;
// component.set("v.selectedRows", selectedRows);
component.set("v.selectedRows", " ");
var pageNumber = component.get("v.PageNumber");
var pageSize = component.find("pageSize").get("v.value");
pageNumber--;
helper.getContactList(component, pageNumber, pageSize);
},
onSelectChange: function(component, event, helper) {
component.set("v.selectedRows", " ");
var page = 1
var pageSize = component.find("pageSize").get("v.value");
helper.getContactList(component, page, pageSize);
},
getSelectedName: function (cmp, event,helper) {
debugger;
var selectedRows = event.getParam('selectedRows');
for (var i = 0; i < selectedRows.length; i++){
// alert(selectedRows[i].Id);
cmp.set('v.recdId', selectedRows[i].Id);
var RecordID = cmp.get("v.recdId");
alert('RecordID'+RecordID);
}
},
clicktile4:function(component,event,helper){
// var recordTypeLabel = event.target.id
//alert("testssss---"+recordTypeLabel);
// var appEvent = $A.get("e.c:IRIS_CommunicationRecordId");
//appEvent.setParams({"communicationId" : recordTypeLabel });
// appEvent.fire();
//
//var RecordID = component.get("v.recdId");
var evt = $A.get("e.force:navigateToComponent");
evt.setParams({
componentDef : "c:CMP4",
componentAttributes: {
Recid : component.get("v.recdId")
}
});
alert('RecordID'+component.get("v.recdId"));
// var action = component.get("c.getRecordTypeId");
// action.setParams({"getRecordtypeId": recordTypeLabel});
// sessionStorage.setItem("getRecordtypeId", recordTypeLabel);
// alert("sessionVari---"+sessionStorage.getItem("getRecordtypeId"));
// action.setCallback(this,function(response){
// });
// $A.enqueueAction(action);
evt.fire();
},
clicktile1:function(component,event,helper){
var evt = $A.get("e.force:navigateToComponent");
evt.setParams({
componentDef : "c:CMP1",
componentAttributes: {
Recid : component.get("v.recdId")
}
});
alert('RecordID'+component.get("v.recdId"));
evt.fire();
},
clicktile3:function(component,event,helper){
var evt = $A.get("e.force:navigateToComponent");
evt.setParams({
componentDef : "c:CMP3",
componentAttributes: {
Recid : component.get("v.recdId")
}
});
alert('RecordID'+component.get("v.recdId"));
evt.fire();
}
})
====================================================
helper.Js
({
getContactList: function(component, pageNumber, pageSize) {
var action = component.get("c.getContactData");
action.setParams({
"pageNumber": pageNumber,
"pageSize": pageSize
});
action.setCallback(this, function(result) {
var state = result.getState();
if (component.isValid() && state === "SUCCESS"){
var resultData = result.getReturnValue();
component.set("v.ContactList", resultData.contactList);
component.set("v.PageNumber", resultData.pageNumber);
component.set("v.TotalRecords", resultData.totalRecords);
component.set("v.RecordStart", resultData.recordStart);
component.set("v.RecordEnd", resultData.recordEnd);
component.set("v.TotalPages", Math.ceil(resultData.totalRecords / pageSize));
}
});
$A.enqueueAction(action);
},
sortData: function (cmp, fieldName, sortDirection) {
var data = cmp.get("v.ContactList");
var reverse = sortDirection !== 'asc';
data.sort(this.sortBy(fieldName, reverse))
cmp.set("v.ContactList", data);
},
sortBy: function (field, reverse, primer) {
var key = primer ?
function(x) {return primer(x[field])} :
function(x) {return x[field]};
reverse = !reverse ? 1 : -1;
return function (a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
})
=============================================================
style
.THIS .dvLogoWhite{
color: white;
}
.THIS .dvLogoGreen{
color: #86bc25;
font-family: 'OpenSans-Italic';
font-style: italic;
font-size: 60px;
}
.THIS .dvContent {
background-color: #c2c5d8;
width: 100%;
height: 240px;
}
.THIS .img1{
padding-top: 60px;
height: 30%;
width : 100%;
margin: 0px 0px 80px 90px;
}
.THIS .img2{
padding-top: 60px;
height: 30%;
width : 100px;
margin: 0px 0px 80px 90px;
}
.THIS .img3{
padding-top: 60px;
height: 30%;
width : 100px;
margin: 0px 0px 80px 90px;
}
.THIS .img{
padding-top: 60px;
height: 30%;
width : 100px;
margin: 0px 0px 80px 90px;
}
.THIS .bgcolor{
background-color: black;
}
.THIS .textpadHeader{
font-size: 36px;;
padding-left: 82px;
}
.THIS .textpad{
font-size: 24px;
padding-left: 82px;
}
.THIS .wid{
width: 100.5px;
}
===============================================================
- venkat bojja
- May 02, 2018
- Like
- 0
Lightning component refresh from child component to parent component.
I am having 2 Lightning Component.
Lightning Component - A having Button.
If I am clicking on the button in Lightning Component - A. Lightning Component - B should refresh.
Do you have any sample codes please post below.
- Balajee Selvaraj
- April 26, 2018
- Like
- 2
autopopulate
I have a requirement to Auto populate fields(lookup/text) based on selection of another look up,I achieved this using trigger but the fields are autopopulating once record is saved but my requirement is when i Select lookup field the auto populating fields are to be filled before save button is clicked,so that i can cross check before record is saved.I want to acheive this only in lightning standard page,i dont need to use vf page.Any help is greatly appriciated.
Thank you.
- Nagarjuna Reddy.P
- April 25, 2018
- Like
- 0
issue in using base utility helper method
I am trying to understand how to use base utility helper method in lighting component.
Base.cmp -------- <aura:component abstract="true"> {!v.body} </aura:component> BaseHelper.js -------------- ({ callServer : function(component,method,callback,params) { var action = component.get(method); if (params) { action.setParams(params); } action.setCallback(this,function(response) { var state = response.getState(); if (state === "SUCCESS") { // pass returned value to callback function callback.call(this,response.getReturnValue()); } else if (state === "ERROR") { // generic error handler var errors = response.getError(); if (errors) { console.log("Errors", errors); if (errors[0] && errors[0].message) { throw new Error("Error" + errors[0].message); } } else { throw new Error("Unknown Error"); } } }); $A.enqueueAction(action); } }) ApexController.axpc ------------------- public with sharing class ApexController { @AuraEnabled public static List<Contact> getContacts() { List<Contact> contacts = [select Id, Name, MailingStreet, Phone, Email FROM Contact]; return contacts; } } CallApexClassCmpBase.cmp ------------------------ <aura:component controller="ApexController"> <lightning:card title="Bring Contact data"> <aura:set attribute="actions"> <lightning:button label="Contact Data" onclick="{!c.Condata}" /> </aura:set> </lightning:card> </aura:component> In the controller.js of the above component ({ Condata : function(component,event,helper) { helper.callServer( component, "c.getContacts", function(response) { console.log('Contacts data'+JSON.stringify(response)); } ); } }) <aura:application extends="force:slds"> <c:CallApexClassCmpBase/> </aura:application>when I preview this I am getting an error as below:
This page has an error. You might just need to refresh it. Action failed: etaPrime:CallApexclassCmpBase$controller$Condata [helper.callServer is not a function] Failing descriptor: {etaPrime:CallApexclassCmpBase$controller$Condata}
I am not able to figure out what is causing the issue,
Please help.
smita
- smita bhargava
- April 19, 2018
- Like
- 0
How to autopopulate the custom object fields?
i am new to lightning as i am trying to autopopulate custom object fields... i have 2 custom objects those are LEAD and OPPORTUNITY i created an convert to opportunity quick action button in lead object. while coverting to opportunity the related lead fields should autopopulate in the lightning component.
here is my code:
component:
<aura:component controller="createOpp" implements="force:lightningQuickAction,force:hasRecordId" access="global">
<aura:attribute name="opp" type="Opportunity__c[]" default="{ 'sobjectType': 'Opportunity__c'}"/>
<aura:attribute name="lelist" type="Lead__c[]" default="{ 'sobjectType': 'Lead__c'}"/>
<aura:attribute name="er" type="boolean" default="false"/>
<aura:attribute name="op" type="Opportunity__c" default="{ 'sobjectType': 'Opportunity__c',
'Name': '',
'Agent__c': '',
'Account__c': '',
'Agreements__c': '',
'Agent_Commission__c': '',
'Delivery_Terms__c': '',
'Description__c': '',
'End_Customer__c': '',
'End_Market__c': '',
'Expected_Launch__c': '',
'Potential_Price__c': '',
'Potential_Quantity__c': '',
'ProductName__c': '',
'Project_Type__c': '',
'Product_Specifications__c': '',
'UOM__c': '',}"/>
<aura:attribute name="lea" type="Lead__c" />
<aura:attribute name="recordId" type="Id" default="{ 'sobjectType': 'Lead__c' }"/>
<aura:attribute name="dateValidationError" type="boolean" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:handler name="init" value="{!this}" action="{!c.mapOpp}"/>
<div class="slds-box">
<div class="slds-col slds-has-flexi-truncate" align="left">
<table>
<lightning:layout class="slds-page-header slds-page-header--object-home">
<lightning:layoutItem >
<lightning:icon iconName="action:new_opportunity" size="small" alternativeText="Indicates approval"/>
</lightning:layoutItem>
<lightning:layoutItem padding="horizontal-Large">
<h1 class="slds-page-header__title slds-m-right--Large slds-align-middle slds-truncate" title="Create Opportunity"><b>Create Opportunity</b></h1>
<h2 class="slds-text-heading-medium">New Opportunity</h2>
</lightning:layoutItem>
</lightning:layout>
</table>
</div>
<form class="slds-form--inline"> <br/><br/>
<center> <lightning:button variant="brand"
disabled="{!v.dateValidationError}"
label="Save" onclick="{!c.Save}"/>
<lightning:button label="cancel"
iconName="cancel"
iconPosition="centera"
variant="brand" onclick="{!c.cancel}"/></center><br/><br/>
<body>
<p class="slds-text-title--caps slds-line-height--reset" style="color:Blue"><b>Opportunity Information</b></p><br/><br/>
<table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout"><br/>
<div class="slds-p-around_medium">
<!-- <label class="slds-form-element__label" >Opportunity Name</label>-->
<div class="slds-form-element__control">
<ui:inputText value="{!v.opp.Name}" label="Opportunity Name"/>
</div>
</div>
<div class="slds-p-around_medium">
<label class="slds-form-element__label" >Stage</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Stage__c}" />
</div>
</div>
<div class="slds-p-around_medium">
<br/> <label class="slds-form-element__label" for="inputNameSample1">Account:</label>
<div class="slds-form-element__control" style="width:30%;height:20px;">
<force:inputField value="{!v.opp.Account__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Project Type:</label>
<div class="slds-form-element__control" >
<force:inputField value="{!v.opp.Project_Type__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Agreements:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Agreements__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">End Customer:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.End_Customer__c}" />
</div>
</div><br/><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">End Market:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.End_Market__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Sample Required</label>
<div class="slds-form-element__control" >
<force:inputField value="{!v.opp.Sample_Required__c}" />
</div>
</div><br/><br/>
</table><br/><br/>
<p class="slds-text-title--caps slds-line-height--reset" style="color:Blue"><b>Business Potential Information</b></p><br/><br/>
<table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout"><br/>
<div class="slds-p-around_medium">
<label class="slds-form-element__label" for="inputNameSample1">Product Name:</label>
<div class="slds-form-element__control" style="width:30%;">
<force:inputField value="{!v.opp.ProductName__c}" />
</div>
</div><br/><br/>
<div class="slds-p-around_medium">
<label class="slds-form-element__label" for="inputNameSample1">Product Specification:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Product_Specifications__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Potential Quantity:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Potential_Quantity__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Potential Price:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Potential_Price__c}" />
</div>
</div><br/><br/>
<div class="slds-p-around_medium">
<div class="slds-form-element__control">
<lightning:input class="{! v.dateValidationError ? 'slds-has-error' : ''}"
type="date"
label="Expected Launch:"
value="{!v.opp.Expected_Launch__c}"
name="date"
variant="brand"
onchange="{!c.dateUpdate}"/>
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">UOM:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.UOM__c}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<div class="slds-form-element__control" >
<lightning:input class="{! v.dateValidationError ? 'slds-has-error' : ''}"
type="date"
label="Sample Required Date:"
value="{!v.opp.Sample_Required_Date__c}"
name="date"
variant="brand"
onchange="{!c.dateUpdate}" />
</div>
</div><br/>
<div class="slds-p-around_medium">
<br/><label class="slds-form-element__label" for="inputNameSample1">Documents Required:</label>
<div class="slds-form-element__control">
<force:inputField value="{!v.opp.Documents_Required__c}" />
</div>
</div><br/><br/>
<aura:if isTrue="{!v.dateValidationError}">
<div class="slds-text-color_error slds-p-left_x-small">
Date must be in present or in future..
</div>
</aura:if>
</table><br/><br/>
<center> <lightning:button label="save"
iconName="submit"
iconPosition="centera"
variant="brand"
disabled="{!v.dateValidationError}" onclick="{!c.Save}"/>
<lightning:button label="cancel"
iconName="cancel"
iconPosition="centera"
variant="brand" onclick="{!c.cancel}"/></center><br/><br/>
</body>
</form>
</div><br/>
</aura:component>
================
controller:
({
doInit : function(component, event, helper) {
helper.fetchOppRecords(component, event, helper);
},
mapOpp : function(component, event, helper) {
var Leadid = component.get("v.recordId");
var le = component.get("v.lea");
var action= component.get("c.getMapLeadFields")
action.setParams({"op":"v.opp", "leid":"v.recordId"});
action.setCallback(this, function(response){
var state=response.getState();
if(state=="SUCCESS"){
var opps = response.getReturnValue();
var op = component.get("v.op");
var lea=component.get("v.lea.Account__C");
component.set("v.op.Account__c",lea);
component.set("v.opp",opps);
alert('Fields automapped');
console.log("opps"+opps);
}
else{
alert("Failed to fetch records from server");
}
});
$A.enqueueAction(action);
}, dateUpdate : function(component, event, helper) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
// if date is less then 10, then append 0 before date
if(dd < 10){
dd = '0' + dd;
}
// if month is less then 10, then append 0 before date
if(mm < 10){
mm = '0' + mm;
}
var todayFormattedDate = yyyy+'-'+mm+'-'+dd;
if(component.get("v.opp.Expected_Launch__c") != '' && component.get("v.opp.Expected_Launch__c") < todayFormattedDate){
component.set("v.dateValidationError" , true);
}else if(component.get("v.opp.Sample_Required_Date__c") != '' && component.get("v.opp.Sample_Required_Date__c") < todayFormattedDate){
component.set("v.dateValidationError" , true);
}
else{
component.set("v.dateValidationError" , false);
}
},
cancel : function(component, event, helper) {
// Close the action panel
var dismissActionPanel = $A.get("e.force:closeQuickAction");
dismissActionPanel.fire();
},
Save : function(component, event, helper) {
// Validate form fields
// Pass form data to a helper function
var opsrecs = component.get("v.op");
helper.saveOpp (component,opsrecs);
}
})
===========================
Helper:
({
fetchOppRecords : function(component, event, helper) {
var action= component.get("c.getFetchOpp")
action.setCallback(this, function(response){
var state=response.getState();
if(state==="SUCCESS"){
var Opplist = response.getReturnValue();
component.set("v.opp", Opplist);
console.log("opplist"+Opplist);
}else{
alert("Failed to fetch records from server");
}
});
$A.enqueueAction(action);
},
saveOpp: function(component, ops) {
//Save the expense and update the view
this.upsertOpp(component, ops, function(a) {
var urlEvent = $A.get("e.force:navigateToURL");
var state = a.getState();
if (component.isValid() && state === "SUCCESS") {
var Opp = component.get("v.opp");
Opp.push(a.getReturnValue());
component.set("v.opp", Opp);
alert('Lead Converted Successfully');
}
urlEvent.setParams({
"url": "/one/one.app#/sObject/Opportunity__c/list?filterName=00B7F00000AyAh9UAF"
});
urlEvent.fire();
});
},
upsertOpp : function(component, ops, callback) {
var action = component.get("c.getSaveOppRecs");
action.setParams({
"ops": ops
});
if (callback) {
action.setCallback(this, callback);
}
$A.enqueueAction(action);
}
})
=============================
apxc:
public class createOpp {
@AuraEnabled
public Static List<Opportunity__c> getFetchOpp(){
Return [Select id,Name,Account__c,Project_Type__c,Agreements__c,End_Customer__c,
Sample_Required__c,ProductName__c,Product_Specifications__c,Potential_Quantity__c,Potential_Price__c,
Expected_Launch__c,UOM__c,Sample_Required_Date__c,Documents_Required__c from Opportunity__c ];
}
@AuraEnabled
public Static List<Lead__c> getMapLeadFields(List<Lead__c> le){
system.debug('hello');
Return [Select id,Name,Agent__c,Account__c,Agreements__c,AgentCommission__c,
DeliveryTerms__c,Description__c,EndCustomer__c,EndMarket__c,ExpectedLaunch__c,
PotentialPrice__c,PotentialQuantity__c,Product_Name__c,Project_Type__c,Product_Specifications__c,
UOM__c from Lead__c];
}
@AuraEnabled
public static Opportunity__c getSaveOppRecs(Opportunity__c ops){
insert ops;
return ops;
}
}
===========================================
can anybody help me out with autopopulating the fields..
Thanks & Regards,
Veena.
- veena vani
- April 10, 2018
- Like
- 0
Facebook is Hiring Salesforce Developers!
Facebook is seeking a Senior Application Developer to join the Salesforce Developer team and participate in the development, integration and maintenance of Force.com applications. Facebook has a very creative, fast-paced, innovative culture, and we like to have fun developing cool stuff!
Send your resume or contact me at:
Shawn Cook
shawn@fb.com
Facebook is currently building large scalable architecture and using Salesforce as our primary productivity platform. The Salesforce Developer team works with the most state of the art technology. At Facebook, we are passionate about the emerging Salesforce technology and offer first-hand access to the latest features and development tools!
This is a full-time permanent position based in our main office in Palo Alto. Facebook offers full relocation assistance for this role and many other perks.
- Technical design, configuration, development and testing of Force.com custom applications, interfaces and reports
- Model, analyze and develop or extend persistent database structures which are non-intrusive to the base application code and which effectively and efficiently implement business requirements
- Integrate Force.com applications to other Facebook external or internal Business Applications and tools
- Develop UI and ACL tailored to Facebook employees and suppliers
- Apply sound release management and configuration management principles to ensure the stability of production environments
- FacebookWantsU
- March 22, 2011
- Like
- 2