• LBK
  • PRO
  • 2604 Points
  • Member since 2015

  • Chatter
    Feed
  • 78
    Best Answers
  • 0
    Likes Received
  • 19
    Likes Given
  • 0
    Questions
  • 558
    Replies
Hello friends
I have a requirement as follows. I am explaining in detail.

I have a URL say https://ap2.salesforce.com?fanID=0032800000gufvJ  in salesforce.
based on this FanID I will get the email of that user.

Now I have a visualforce page with standard controller="fan__c"
<apex:inputText name="email>

In aex controller:
string fanid="Apexpages.currentpage().getparameter('fanID');
               if fanid != NULL
  string emaladdress=[select Email from fan__c where ID=:fanID];

Now value in emailaddress should be stored in <apex:InputText name=Email>

if the email already exists it should be replaced with asterisk as follows.
for example : assume email is  jose@gmail.com and if it exists for that particular ID then the contents of <apex:inputText> should be
j***@g****.com

If email doesnt exist for that  FanID   then contents of <apex:inputText> will contain   mary@yahoo.co.in

I am literaly struggling with this so any will be rewarded with points

thanks
krishna
Error: Compile Error: Variable does not exist: RestDocCallController at line 19 column 13 in ""apex class""
------------------CLASS----------------------

@RestResource(urlMapping='/DocAttachment/v1/*')

global with sharing class RestDocService {
    
    // Post method to decode the file and insert Attachment.
    @HttpPost
    global static String attachdoc(String encodedDoc){
        try {      
            RestRequest req = RestContext.request;
            Id callId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
            Blob pic ;//Blob variable to capture decoded image
            if(encodedDoc != null) {
                pic=EncodingUtil.base64Decode(encodedDoc);//Decode the base64 encoded image
            }
            Attachment attach = new Attachment (ParentId = callId,Body = pic,ContentType = 'text/plain',Name = 'Document Test');
            insert attach;
            return attach.Id;
        }catch(Exception e) {
            RestDocCallController.errorHandler(e);
            return null;
        }
    }



----------------------CONTROLLER---------------------

Error: Compile Error: Invalid type: Logger__c at line 112 column 32 ""Controller""

public class RestDocCallController {
    
    public Blob file{get;set;}
    public String accountId{get;set;}
    public String fileName{get;set;}
    public String result{get;set;}
    
    // Method called from Page
    public PageReference uploadDoc(){
        if(file != null && accountId != null){
            try {
                RestDocCallController restObj = new RestDocCallController();
                String result = restObj.restAuthSetting(accountId,file,fileName);
                if(result != null) {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
                    return null;
                } else {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));    
                }
            }catch(Exception e) {
                errorHandler(e);
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
                return null;
            }
            return null;
        }
        return null;
    }
    
     // Get Authorized and Post call to service class with JSON Body
    
    public String restAuthSetting(String accId,Blob file_body,String fileName) {
        try {
            String loginUrl = Label.Login_Url;
            String consumerKey = Label.App_Cosumer_Key;
            String consumerSecretKey = Label.Consumer_Secret_Key;
            String userName = Label.Org_UserName;
            String password = Label.Org_Password;
            
            
            Map<String, Object> oauth = oauthLogin(loginUrl,consumerKey,consumerSecretKey,userName,password);
            
            System.debug('oauth'+oauth);
                    
            String accessToken = (String)oauth.get('access_token');
            String instanceUrl = (String)oauth.get('instance_url');
            
            System.debug('instanceUrl'+instanceUrl);
            
            
            HttpRequest req = new HttpRequest();
            
            String bodyEncoded = EncodingUtil.base64Encode(file_body);
            
            req.setMethod('POST');
            
            req.setEndpoint(instanceUrl+'/services/apexrest/DocAttachment/v1/'+accId);
            req.setHeader('Authorization', 'Bearer '+accessToken);
            req.setHeader('Content-Type', 'application/json');
            req.setBody('{"encodedDoc":"'+bodyEncoded+'","fileName":"'+fileName+'"}');
            req.setTimeout(120000);
    
            Http http = new Http();
      
            HTTPResponse res = http.send(req);
    
            System.debug('BODY: '+res.getBody());
            System.debug('STATUS:'+res.getStatus());
            System.debug('STATUS_CODE:'+res.getStatusCode());
            
            return res.getBody();
        } catch(Exception e) {
            errorHandler(e);
            return null;
        }
    }
    
    // Method to get authorized using Connected Apps Client ID and Consumer Id.
    
     private static Map<String, Object> oauthLogin(String loginUri, String clientId,
        String clientSecret, String username, String password) {
        
        try {
            HttpRequest req = new HttpRequest();
     
            req.setMethod('POST');
            req.setEndpoint(loginUri+'/services/oauth2/token');
            req.setBody('grant_type=password' +
                '&client_id=' + clientId +
                '&client_secret=' + clientSecret +
                '&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +
                '&password=' + EncodingUtil.urlEncode(password, 'UTF-8'));
        
            Http http = new Http();
      
            HTTPResponse res = http.send(req);
    
            System.debug('BODY: '+res.getBody());
            System.debug('STATUS:'+res.getStatus());
            System.debug('STATUS_CODE:'+res.getStatusCode());
            
            return (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        }catch(Exception e) {
            errorHandler(e);
            return null;
        }
    }
    
     //Method used to log errors
    public static void errorHandler(Exception e) {
        
        Logger__c logger = new Logger__c();
        logger.Error_Line_Number__c = String.valueOf(e.getLineNumber());
        logger.Error_Body__c = e.getStackTraceString();
        logger.Error_Cause__c = e.getMessage();
        try {
            insert logger;
        }catch(Exception exp){
            System.debug(exp);
        }  
    }
}
This is class
-------------------------------------------------------------------------
public class leaddup {

    public List<lead>ac{get;set;}
    public leaddup(){
    ac =[SELECT name,email FROM lead ];
    }
    public void getbyname(){
       ac=[SELECT name,count(Id) FROM lead GROUP BY name HAVING count(Id)>1];
    }
     public void getbyemail(){
       ac=[SELECT email,count(Id) FROM lead GROUP BY email HAVING count(Id)>1];
    }
}
--------------------------------------------------
This is vf
---------------------------------------------------------------------
<apex:page controller="leaddup">
    <apex:form >
        <apex:pageblock title="Duplicate lead">
            <apex:pageBlockButtons >
                <apex:commandButton value="based on name" action="{!getbyname}"/>
                <apex:commandButton value="based on email" action="{!getbyemail}"/>
            </apex:pageBlockButtons>
                    <apex:PageBlockTable value="{!ac}" var="a">
                        <apex:Column value="{!a.Name}"/>
                        <apex:Column value="{!a.email}"/> 
                    </apex:PageBlockTable>
               
        </apex:pageblock>
    </apex:form>
</apex:page>
I have a page layout named "User_ContactLayout" for Contact object.  I want to open this as a tab on my service console on click of a button  on the visual force page.
Hi Everyone,

I need a way determine if the accountNumber field contains -1. I got it work when -1 is the only value in the account number field. The formula needs to identify identify wether -1 is present the string (i.e. 11706-1). Not sure what else I need to do here.
 
IF(  CONTAINS("-1", Site) , BillingCity , 
IF(   NOT( CONTAINS("-1", Site) ), ShippingCity , 
IF(  CONTAINS("", Site)  , ShippingCity , BillingCity) ) )

 
Hello,


User-added image

I am creating a list button like above, 

Below is the thing i put in button
/001/e
&retURL=%2F001%2Fo
&cancelURL={!Opportunity.Id}
&ent=Account
In standard creation wizard for creation of Account:
​
The user has many record types to choose:

so the first URL appearing for record selection is like below:

https://axyz.cs82.my.salesforce.com/setup/ui/recordtypeselect.jsp
?ent=Account
&retURL=%2F001%2Fo
&save_new_url=%2F001%2Fe%3FretURL%3D%252F001%252Fo

Once the first record is selected, the URL is like below:

https://xyz.cs82.my.salesforce.com/
001/e
?retURL=%2F001%2Fo
&RecordType=012D0000000kZUw
&ent=Account

I want to have the same behavior for record selection:

Am i missing something in my button ?
I have a Picklist field on Case called Type with values 'Teacher Related, Policy Feedback, Curriculum Feedback' I have another field called Teacher_Name__c.  I need some help to write a validation rule so that if the user select the either 'Policy Feedback' or 'Curriculum Feedback' The teacher_name__c field should be made non editable and when the user choose 'Teacher Related' the Teacher_Name__c should be allowed to choose the teacher name.
  • April 18, 2017
  • Like
  • 0
I have the fields "Base_Price__c", Discount_Percentage__c, Discount_Amount__c.  I need to calculate the discounted price either by $ or percentage.  I need some help to write a formula to have either one discount or no discount, please help
  • April 18, 2017
  • Like
  • 0
Hi folks,

I put a custom button on Salesforce cases that both Accepts a case and checks whether it the case is owned by a User or Queue, and gives an error when one user tries to take the case from another User, and not from a Queue.

The trouble is this button only works if one user opens the case after another has accepted it.  But if both users open an unaccepted case, the button will unfortunately allow the case to first be taken by the first person and then the second, without alerting.

The code:
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}



if('{!Case.OwnerId}'.substring(0,3)=='005'){
alert("This case is owned by " +'{!Case.Case_Owner_s__c}'+" and is not in a Queue.");
} else 

{

var caseObj = new sforce.SObject("Case");
caseObj.Id = '{!Case.Id}';
caseObj.OwnerId = '{!$User.Id}';
caseObj.One_Stop_Counter__c = "{!TEXT($User.Assigned_Counter__c)}";
caseObj.Display_Screen_Suffix__c = "see " + '{!User.FirstName}'+" at Counter  "+'{!TEXT($User.Assigned_Counter__c)}';
var result = sforce.connection.update([caseObj]);

if (result[0].success=='false'){
alert(result[0].errors.message);
} else {
window.parent.location.href="/{!Case.Id}";
}
}

My original solution to this was to have the code in the Accept button refresh the page before running its User owner check, but this does not seem to be working either.

I was adding location.reload(true); before the User check.

Can anyone tell me why the refresh solution isn't working, or if there is another way to either do the refresh, or to execute my intentions?
I cannot figure out what I am doing wrong here.  This was working before.  

MY VF Page
<apex:page Controller="TestP" showHeader="false">

<apex:pageBlock><apex:pageBlockSection>
    <apex:form>
   Email given: {!cemail} 
   Email Returned: {!IdentifyUser.email} 
   Name: {!IdentifyUser.name}
    </apex:form>
    </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

My Controller
 
public class TestP {
    Public string cemail {get;set;} 
    Public Contact IdentifyUser {get;set;}
    Public Contact x {get;set;}
    
    // IDENTIFY USER BASED ON EMAIL ADDRESS
    Public Contact getIdentifyUser(){       
     cemail='kevin@caberu.be';   
       Contact x = [SELECT Id, firstname, email, name             
              FROM Contact 
              WHERE email = :cemail 
                              LIMIT 1]; 
        Return x;

    }
}

The VF page does not show any of the variables.

Any help is appreciated.  Where is the bug?
Hi,

I need help on the following issue 

I am having a trigger on account object 

When, we trying to upload bulk records  via dataloader or ETL , system is facing 'CPU usage limition'' issue.
For one Account record creation, the trigger is running four times instead of one time.

How to avoid the issue, Kindly help me pls
MY TRIGGER :

trigger AccountTrigger on Account (after insert, before update, after update, after delete) {  
    
    /* Assign & create Account team members based on user department*/
    if(Trigger_Status__c.getValues('AccountTeam').Active__c && Trigger.isUpdate  && Trigger.isBefore ){
        /* Before insert process */
        AccountTriggerHelper.updateAccountTeam(Trigger.newMap, Trigger.oldMap);
    } 
    
    /* Trigger to invoke the AccountIneligibilty Logs Tracking*/
    if(Trigger_Status__c.getValues('AccountEligibilityLogTrigger').Active__c && Trigger.isAfter && Trigger.isUpdate){
        AccountTriggerHelper.createAccountEligiblityLogs(Trigger.newMap, Trigger.oldMap);
    }
    
    /* Trigger to invoke the DiscountCode Calculations on Products*/
    if(Trigger_Status__c.getValues('AccountAirlineLeveltrigger').Active__c && Trigger.isAfter && Trigger.isUpdate) {
        AccountTriggerHelper.calculateDiscountCode(Trigger.newMap,Trigger.oldMap);
    }
    
    /* Trigger to invoke the DeleteAccount Tracking of Records*/
    if(Trigger_Status__c.getValues('AccountDeleteTrigger').Active__c && Trigger.isAfter && Trigger.isDelete) {
        AccountTriggerHelper.createDelAccountLogTracker(Trigger.oldMap); 
    }        
}
MY CLASS:

public class AccountTriggerHelper {
    
    /*--------------------------------------------------------------------------------------      
  Method Name:        updateAccountTeam
  Description:        Method to Assign & create Account team members based on user department
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void updateAccountTeam(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountTeamHandler accHandler = new AccountTeamHandler();
        List<Account> lstNewAccount = newMapAccount.values();
            accHandler.setRevenueManualUpdate(lstNewAccount, oldMapAccount);
            accHandler.createAccountTeamMembers(lstNewAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Account Team - Account Trigger', 'AccountTriggerHelper', 
                                                                      'updateAccountTeam', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createAccountEligiblityLogs
  Description:        Method to Create AccountIneligibilty Logs and Update
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createAccountEligiblityLogs(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountEligibilityLogHandler.createAccountEligiblityLogs(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createAccountEligiblityLogs', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        calculateDiscountCode
  Description:        Method to DiscountCode Calculations on Products
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void calculateDiscountCode(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
    try{
            AccountAirlineLevelHandler.updateDiscountCodeOnProducts(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'calculateDiscountCode', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createDelAccountLogTracker
  Description:        Method to Create Delete Tracker Logs records when any Account is Deleted
  Parameter:          Account Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createDelAccountLogTracker(Map<Id,Account> oldMapAccount){
        try{
            String recTypeName = CustomSettingsUtilities.getConfigDataMap('Del Log SME Account Rec Type');
            List<CreateLogs.DeleteLogWrapper> lstDelLogWrapper = new List<CreateLogs.DeleteLogWrapper>();
            for(Account acc: oldMapAccount.values()){
                String directvalue = CustomSettingsUtilities.getConfigDataMap('AccListner Type Direct Stream');
                if(acc.Listner_Type__c == directvalue){
                    CreateLogs.DeleteLogWrapper delLogWrapper = new CreateLogs.DeleteLogWrapper();
                    delLogWrapper.recType = recTypeName;
                    delLogWrapper.recName =  acc.Name;
                    delLogWrapper.abnNumber = acc.ABN_Tax_Reference__c;
                    delLogWrapper.sobjectId = acc.Id;
                    delLogWrapper.sobjectName = 'Account';
                    lstDelLogWrapper.add(delLogWrapper);
                }
            }
            List<Delete_Tracker_Log__c> lstDelTrackerLog = CreateLogs.createDeleteLog(lstDelLogWrapper);
            insert lstDelTrackerLog;
        }catch(Exception ex){
            String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Direct Stream - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createDelAccountLogTracker', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
        }
    }

}
Kindly help me pls

Thanks in Advance

 
Could someone explain how to process a list within a list in APEX code?

String List Example:

List<String>
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI60856},
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI54960},
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI57656}

There would be three calls within a loop to a service that is expecting the parameters of AgentId and CustomerIds[].


Example:

AgentId = 'AI60856'
CustomerIds[] = '700011326', '507024842', '12345678'

AgentId = 'AI54960'
CustomerIds[] = '700011326', '507024842', '12345678'

AgentId = 'AI57656'
CustomerIds[] = '700011326', '507024842', '12345678'
Hi Everyone,

I could not group by a currency field in SOQL,
Select count(id),currency__c from contact group by currency__c
It shows the following error,

field 'currency__c' can not be grouped in a query call

Kindly provide me a solution,

Thanks 
Vignesh
I have a javascript object that looks like this
this will be used in an ajax called in javascript  data: JSON.stringify(address) and submitted
var address = { location: { 
                                    phoneNumber: "", 
                                    address: {
                                    line1: $( "line1" ).val(),
                                    city: $( "city" ).val(), 
                                    state: $( "state" ).val(), 
                                    postalCode: $( "postalCode" ).val(),
                                    country: "US", 

                                            }
                                  }, 
                        networks: ["1", "2","3","4","5"],  
                        company: "Salesforce"
                      };

what I need to do is samething but in apex code with custom object but not sure how I can format it same way

qualRequest = new prequalAPI.QualificationRequest();   
qualRequest.CustomerId = 0;
            qualRequest.PhoneNumber = 'STANDALONE';
            qualRequest.AddressLine1 = addressLine1;

            if (unitType != null)
            {
                qualRequest.UnitType = unitType;
            }

            if (unitValue != null)
            {
                qualRequest.UnitValue = unitValue;
            }

            qualRequest.City = city;
            qualRequest.State = state;
            qualRequest.ZipCode = zip;
            qualRequest.Country = country;
            qualRequest.UnitType = unitType;
            qualRequest.RequestedNetworkNames = new List<String>();
            qualRequest.RequestedNetworkNames.add('1');
            qualRequest.RequestedNetworkNames.add('2');
            qualRequest.RequestedNetworkNames.add('3');
            qualRequest.RequestedNetworkNames.add('4');
            qualRequest.RequestedNetworkNames.add('5');

JSON.serialize(qualRequest);
my request status fails right now because json is not same format. 
I have written a custom controller and Visualforce page that displays records from a custom object, and related records, in a few HTML tables. I have a checkbox on the page and a Save button to display the refined results. Do I need to write a function that returns a modified list of records, basically copying what is in my controller's main class to a "PageReference save()" class? Ideally, the button would result in the controller running again with the updated value of the checkbox. I've seen examples but having trouble. Please help.
I have users that have sandboxes but the issue is when I refresh the boxs for them the email gets changed to the default @example.com one. How can I setup a user for a sandbox so the email does not change?
Need help with a formula
I need to add a new component to the formula below for a Process Builder step:

DATE(
YEAR([Opportunity].CloseDate)+FLOOR((MONTH([Opportunity].CloseDate) + IF( TEXT([Opportunity].Pre_Paid_Contract__c)="Month to month" || TEXT([Opportunity].Pre_Paid_Contract__c)="One Time Payment", 1, VALUE(TRIM(LEFT(TEXT([Opportunity].Pre_Paid_Contract__c),2))) ))/12) + IF(AND(MONTH([Opportunity].CloseDate)=12,IF( TEXT([Opportunity].Pre_Paid_Contract__c)="Month to month" || TEXT([Opportunity].Pre_Paid_Contract__c)="One Time Payment", 1, VALUE(TRIM(LEFT(TEXT([Opportunity].Pre_Paid_Contract__c),2))) )>=12),-1,0)
,
IF( MOD( MONTH([Opportunity].CloseDate) + IF( TEXT([Opportunity].Pre_Paid_Contract__c)="Month to month" || TEXT([Opportunity].Pre_Paid_Contract__c)="One Time Payment", 1, VALUE(TRIM(LEFT(TEXT([Opportunity].Pre_Paid_Contract__c),2))) ) , 12 ) = 0, 12 , MOD( MONTH([Opportunity].CloseDate) + IF( TEXT([Opportunity].Pre_Paid_Contract__c)="Month to month" || TEXT([Opportunity].Pre_Paid_Contract__c)="One Time Payment", 1, VALUE(TRIM(LEFT(TEXT([Opportunity].Pre_Paid_Contract__c),2))) ) , 12 ))
,
MIN(
DAY([Opportunity].CloseDate),
CASE(
MAX( MOD( MONTH([Opportunity].CloseDate) + IF( TEXT([Opportunity].Pre_Paid_Contract__c)="Month to month" || TEXT([Opportunity].Pre_Paid_Contract__c)="One Time Payment", 1, VALUE(TRIM(LEFT(TEXT([Opportunity].Pre_Paid_Contract__c),2))) ) , 12 ) , 1),
9,30,
4,30,
6,30,
11,30,
2,28,
31
)
)
)

I need this formula to take into account that if the field "[Opportunity].Pre_Paid_Contract__c" is blank, than we want the date to default to what we have setup for the "One Time Payment" scenario. Unfortunately, if it's blank now, it errors out the process.

Been trying to replace all "TEXT([Opportunity].Pre_Paid_Contract__c)" with "BLANKVALUE(TEXT(Opportunity].Pre_Paid_Contract__c), "One Time Payment")" but keep getting syntax errors.

Can someone help me figure out how to make this addition in my complex code?

Thanks!

Erin
Hi,

We have a need to schedule a batch that will perform some action if the user has not logged in in the last 24hours. On the User object, there is a LastLoginDate field which is a DateTime field. 

I want to write a SOQL query that will filter out (not select) users who have logged in with last 24hours. I am having difficulty understanding the correct syntex and need help determining what would be the best approach. What would be the recommended way to do this?
 
/*
 *i tried this but it was giving very weird response.
  *if today = 3/30/2017, when i do the following below i see that in the debug statements that it pulling users with a lastlogindate of 2017-03-30T07:XX:XX values
 * if i print DateTime.Now() i am getting a result of 2017-03-31T01:05:53 (if i were to run it on 3/30/2017 6:05pm PT
  */
List<User> usrs = [Select Id, LastLoginDate, IsActive, Name 
                                  From User
                                  Where LastLoginDate = TODAY];

The goal is to get the set of records where all user.lastlogindate >= 3/29/2017T18:05:53 and user.LastLoginDate <=3/30/2017T18:05:53 (basically within the last 24hours when the logic is ran). Any thoughts?
  • March 31, 2017
  • Like
  • 0
Hi,

In My account object  “total_ amount__c" field is there,and in opportunity "amount" field  is there,
I want to dispaly sum of amount of all child  opportunities in the total _amount__c field in the parent account.
I written below trigger which is working fine,but here i need to fire this trigger when opportunity.stagename is set to closed won,but its not working accordingly.its firing for all the stages.
Can anyone help me to fix this.
 
trigger totalamount on Account (before insert,before update) {
  List<opportunity> Lstopp = [Select id,stagename from opportunity];
     for(Account record: Trigger.new) {
       record.total_Amount__c = null;
     }  
     for(Opportunity opp : Lstopp){
      if(opp.stagename == ‘Closed - won'){
     for(AggregateResult result: [SELECT SUM(Amount) Amt, AccountId Id FROM opportunity WHERE AccountId IN :Trigger.new GROUP BY AccountId]) { 
        Trigger.newMap.get((Id)result.get('Id')).Sum_of_Opportunity_Amount__c = (Decimal)result.get('Amt');
     }
   }
  }

Thanks Everyone!
Hi everyone,

I have two objects: Segment Brief Tracking and Segment Category Mapping. I've created a trigger that is supposed to get the Segment Category Mapping ID that corresponds to the Segment Name from Segment Brief Tracking - mapped to Segment Name field on Segment Category Mapping.

I'm not getting an error but the Segment Category Mapping ID field is not being populated at all.

I've only started dabbling into Apex triggers so it'd be great to have an expert's opinion on how this trigger could be written better/why it's not working.

Thank you!
 
trigger SegmentBriefTracking_AddSegmentID on Segment_Brief_Tracking__c (before insert, before update) {

//Create a Set of all the Segment Names to be Uploaded

Set<String> SegmentNames = new Set<String>();

//Variable declaration

for (Segment_Brief_Tracking__c segbrieftrack : Trigger.new)
if(segbrieftrack.Segment_Name_For_Upload__c!=''){
SegmentNames.add(segbrieftrack.Segment_Name_For_Upload__c);}

//Map Segment Name for Upload to Segment Taxonomy Name

Map<String,Segment_Category_Mapping__c> mastersheet = new Map<String,Segment_Category_Mapping__c>([Select Id, Segment_Name__c FROM Segment_Category_Mapping__c WHERE Segment_Name__c IN :SegmentNames]);

//Add Segment Category Mapping ID to Segment Brief Tracking Record

for (Segment_Brief_Tracking__c segbrieftrack : Trigger.new)
if(segbrieftrack.Segment_Category_Mapping_ID__c!=null && segbrieftrack.Segment_Category_Mapping_ID__c!=''){
segbrieftrack.Segment_Category_Mapping_ID__c=mastersheet.get(segbrieftrack.Segment_Name_For_Upload__c).Id;}
}

 
I have a master detail relationship on a custom object where Account is master object. I have OWD for Account set to private. I also have criteria based sharing rules to share account records to specific users. These users will have Read Only access on Account records. As per master detail relationship child should also be Read only but in my case Child records editable to the user. I am using VF page to edit the child records here. Does VF(VF page controller is 'With Sharing' ) make any difference?
The code coverage for the Trigger below is only 56%, trying to get it to atleast a 75%
 
Trigger GetInitialWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled')
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_Weight__c = IW
            ));
            
        }   
        
        update accountsToUpdate;
        
        }
      }

Here is the testing class that I used:
 
@isTest
Private class InsertWeightToAppointment {

    @isTest static void InsertAppointment() {
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013cLIg';
        appt.status__c = 'Completed';
        
        insert appt;
        
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today();
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        
        insert lb;
               
        
        }
        
    @isTest static void UpdateAppointment() {
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        appt.id = 'a0A6100000UUBeK';
        appt.weight__c = 100;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013bPD9';
        
        update appt;   
        
        lb.value__c = 180;
        lb.Specimen_Received__c = date.today()-30;
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        lb.id = 'a0E61000005Pg21';
        
        update lb;
        
        }
     
}
Hi All,

I am very new to Apex coding and I am trying to learn how to add a custom picklist field to a Visualforce page.

I am trying to work with the below:
  • A customer field called "Type_of_Sales__c" within the standard OpportunityLineItem object
  • The custom field contains the following items
    • Sample
    • Normal Sales
    • Inspection Copy
    • Schools Direct
Using the below code, I'm able to display the Heading but not the list:
<apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Type_of_Sales__c.Label}">
</apex:column>
I have tried using the following code, which again shows the heading but no list:
<apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Type_of_Sales__C.Label}">
<apex:inputField value="{!OpportunityLineItem.Fields.Type_of_Sales__C}"
</apex:column>
All I'm am trying to do is display to customer picklist as you would normally see it on a page.

Any help would be great!
 
I need to track the email change for Standard platform user and do some logic. But This is not happening as email change is not invoking user trigger. Is this a known issue or is there any way to get the changed email in Trigger?
Hello friends
I am appending a contact ID to the browser url, based on the contact ID I will fetch lastname and leadsource into the vf page for that contact ID only.

so I am trying to bind leadsource picklist values into my controller as follows for that particular contact ID only.
public class clsContact {
    public Contact contact {get; set;}
    public String lastname{get; set;}
    public List<Selectoption> leadsourcevalues{get; set;}
    String contactId {get; set;} 
   
    public clsContact(){
        contactId = ApexPages.currentPage().getParameters().get('id');
        if(contactId != null)
        {
           getContact();
        }
        else{
            contact = new Contact();
        }
 }
public void getContact() {
            contact = [SELECT Id, lastname,LeadSourcee FROM Contact WHERE Id = :contactId];
 }

<apex:page controller="clsContact" >
<apex:form >
 <apex:inputField value="{!contact.FirstName}"/>
 //Here how to get the picklist value for that particular ID
  <apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>
I am struggling here so kindly help me out.
Thanks
krishna


 
I have scheduled a scheduler from Installscript class. 
global without sharing class InstallScript implements InstallHandler {
    global void onInstall(InstallContext context){
            List<CronTrigger> ctList8 = [Select Id from CronTrigger where 
                                                  CronJobDetail.Name = 'OverallCompletionUpdate'];
            
            if(ctList8.size()==0){
                String cronStr2 = '0 0 * * * ?';
                
                OverallCompletionUpdateScheduler tl = new 
                                                                           OverallCompletionUpdateScheduler();
                
                String jobID = system.schedule('OverallCompletionUpdate', cronStr2, tl);             
    
            }              
    }
}

My scheduler class is given below
 
global with sharing class OverallCompletionUpdateScheduler implements Schedulable {
   global void execute(SchedulableContext sc) {
      OverallCompletionResultUpdation ovr = new OverallCompletionResultUpdation();
      
      ovr.process();  
   }

}

Given below the OverallCompletionResultUpdation class
 
global with sharing class OverallCompletionResultUpdation{
    global void process(){
        //Initialize variables
        Map<Id,OverallCompletionResult__c> userMap = new 
                 Map<Id,OverallCompletionResult__c>();
        Map<Id,OverallCompletionResult__c> contactMap = new 
                                  Map<Id,OverallCompletionResult__c>(); 
        List<User> userUpdateList = new List<User>();
        List<Contact> contactUpdateList = new List<Contact>();
        Map<Id,User> userIdMap = new Map<Id,User>();
        Map<Id,Contact> contactIdMap = new Map<Id,Contact>();
        
        //Fetch 2000 OverallCompletionResult records with isProcessed = false
        List<OverallCompletionResult__c> ovrList = [Select Id,ContactID__c,UserID__c,TotalCoursesAssigned__c,TotalCoursesCompleted__c,TotalLearningPathAssigned__c,TotalLearningPathsCompleted__c,OverallUserCourseCompletionPercentage__c,OverallUserLearningPathCompletionPercent__c From OverallCompletionResult__c Where isProcessed__c=false and ContactId__r.Deactivate_From_Litmos__c=:false limit 2000];    


//Calculation logic goes here
}
}
After installation when the sceduler runs It gives the above error "sObject type "OverallCompletionResult__c" is not supported" on the below line in the OverallCompletionResultUpdation class.
 
List<OverallCompletionResult__c> ovrList = [Select Id,ContactID__c,UserID__c,TotalCoursesAssigned__c,TotalCoursesCompleted__c,TotalLearningPathAssigned__c,TotalLearningPathsCompleted__c,OverallUserCourseCompletionPercentage__c,OverallUserLearningPathCompletionPercent__c From OverallCompletionResult__c Where isProcessed__c=false and ContactId__r.Deactivate_From_Litmos__c=:false limit 2000];

Please help me on this. Is this because of the sharing rules on scheduler?

Thanks for the help
I have created a formula field to pull value after /
MID(
    BillingStreet ,
    FIND("/", BillingStreet )+1,
    FIND(" ", RIGHT(BillingStreet , LEN(BillingStreet) - FIND(" ", BillingStreet )))-1)

Input: 26/12 IMA way  o/p: by using above formula Iam Getting 12 I
But I need only 12, Some thing number(12) length will maxium 4 characters
 
Hello friends
I have a requirement as follows. I am explaining in detail.

I have a URL say https://ap2.salesforce.com?fanID=0032800000gufvJ  in salesforce.
based on this FanID I will get the email of that user.

Now I have a visualforce page with standard controller="fan__c"
<apex:inputText name="email>

In aex controller:
string fanid="Apexpages.currentpage().getparameter('fanID');
               if fanid != NULL
  string emaladdress=[select Email from fan__c where ID=:fanID];

Now value in emailaddress should be stored in <apex:InputText name=Email>

if the email already exists it should be replaced with asterisk as follows.
for example : assume email is  jose@gmail.com and if it exists for that particular ID then the contents of <apex:inputText> should be
j***@g****.com

If email doesnt exist for that  FanID   then contents of <apex:inputText> will contain   mary@yahoo.co.in

I am literaly struggling with this so any will be rewarded with points

thanks
krishna
 i have a trigger that updates fields on an opportunity when it is created and anytime it is updated anytime after. It adds phone number fields and a few other fields that i can't map over. I need it to also update the opportunity name depending on if the account has a middle name or not. So i am dealing with if and else statements. I had a process builder done and it worked fine for a little bit but now it is not working at all. I will attach what it looks like as well as the trigger that i have so far. SO basically what i need to added to my trigger that i cant seem to figure out how to do is the opportunity name update.
For example-- If the account First Name: Bob --Middle Name: Null -Last Name: Smith  I would want Opportunity name to be updated to Bob Smith 
But if it was --First Name: Bob  - Middle Name: Mary -Last Name: Smith  I would want Opportunity name to be updated to Bob & Mary Smith 

this is the trigger that i have created that updates the opportunity fields 

trigger insertOpportunity on Opportunity(before insert,before update) {

if(trigger.isinsert)
{
for(Opportunity ac : Trigger.new){
try{

List<account> acc=[select id,Water_Source__c,Phone,PersonHomePhone,PersonMobilePhone,Water_Filters__c,PersonMailingStreet,PersonMailingCity,PersonMailingState,PersonMailingPostalCode,Water_Conditions__c,Type_of_Home__c from Account where id=: trigger.new[0].accountid];
trigger.new[0].Water_Source__c=acc[0].Water_Source__c;
trigger.new[0].Home_Phone__c=acc[0].PersonHomePhone;
trigger.new[0].Mobile_Phone__c=acc[0].PersonMobilePhone;
trigger.new[0].Water_Filters__c=acc[0].Water_Filters__c;
trigger.new[0].Street__c=acc[0].PersonMailingStreet;
trigger.new[0].City__c=acc[0].PersonMailingCity;
trigger.new[0].State__c=acc[0].PersonMailingState;
trigger.new[0].Zip_Code__c=acc[0].PersonMailingPostalCode;
trigger.new[0].Water_Condtitions__c=acc[0].Water_Conditions__c;
trigger.new[0].Type_of_Home__c=acc[0].Type_of_Home__c;
trigger.new[0].Phone__c=acc[0].Phone;
}
catch(Exception e ){
}
}
}

}



This is the formula that i had for the process builder that worked but now no longer does and this is what i need the opportunity name to look like 

IF(NOT(ISBLANK([Account].Spouse_Name__c)),
  [Account].FirstName & " " & "&" & " " & [Account].Spouse_Name__c & " " & [Account].LastName,
[Account].FirstName & " " &  [Account].MiddleName & " " &  [Account].LastName
 )

Groundswell Cloud Solutions is seeking superstar Salesforce DevelopersTechnical Architects to join us to work on some large-scale SFDC implementations! This is an excellent opportunity to join a fast-expanding Salesforce consulting firm, and grow with friendly, highly accomplished Salesforce professionals. You'll get to push the boundaries of Wave AnalyticsCommunities, work across SalesService Clouds and now even Einstein!

We offer competitive salary, generous annual bonus, 15 days vacation+ 2 weeks office closure over X’mas/New Year, Extended Health, sponsored SF certifications and endless supply of snacks and drinks.

Interested?
Please visit: www.gscloudsolutions.com/careers 

Thanks and we look forward to hearing from you!

Groundswell Team Intro!
 

I found a bug in the Tooling API, but cannot report it directly to Salesforce.

We are using the Tooling API to assign new picklist values to record types. This is a typical request that we send:

URL: https://SANDBOX.cs80.salesforce.com/services/data/v39.0/tooling/sobjects/RecordType/012250000008wmq
Payload:
{
  "Metadata": {
    "active": true,
    "compactLayoutAssignment": "Master_Product_Compact_Layout",
    "description": "Master Product, managed in MDM.",
    "label": "Master Product",
    "picklistValues": [
      {
        "picklist": "Packaging__c",
        "values": [
          {
            "default": false,
            "valueName": "twinpack, 1 ltr. + 1 ltr."
          }
        ]
      }
    ]
  },
  "FullName": "Product2.Master_Product"
}
Error Message:
{
    "statusCode": 400,
    "headers": {
        "Pragma": "no-cache",
        "Cache-Control": "no-cache",
        "Date": "Wed, 01 Mar 2017 14:27:59 GMT",
        "Server": "Microsoft-IIS/8.0",
        "X-AspNet-Version": "4.0.30319",
        "X-Powered-By": "ASP.NET",
        "Content-Length": "151",
        "Content-Type": "text/plain; charset=utf-8",
        "Expires": "-1"
    },
    "body": "[{\"message\":\"Picklist value: twinpack%2C 1 ltr%2E   1 ltr%2E in picklist: Packaging__c not found\",\"errorCode\":\"FIELD_INTEGRITY_EXCEPTION\",\"fields\":[]}]"
}

This error only occurs for picklist values that have a "+" character in their name. The Tooling API seems to URL decode the request where "+" characters are replaced with a space, as you can see in the error message. Additional URL encoding of the valueName won't help. This seems to be an error of the RecordType Tooling API, as inserting new picklist values with a "+" character does work fine. 

 
Mistake on this page (or it could be clearer)
https://trailhead.salesforce.com/modules/data_modeling/units/schema_builder

'Salesforce populates Field Name using the field label. This name can contain only underscores and alphanumeric characters, and must be unique in your org. '

Surely it should be unique in the object.
Hi,
I have custom lookup field in a account object 
lookup to the user

My question is i have to prepopulate the field with the user name that means owner of the account

please help me to sort out this

Thanks & Regards
Pratyusha.K



Hi all, 

I'm learning triggers in salesforce and want some advice on understanding how to write a trigger for below scenario. what is the approach?
There are two objects Object1_c(Parent) and Object__c(child) having look-up relationship.

Summary:
Object__c has record types namely  "A" and "B".
Object__c has a field (currency) --> Myamount__c
Object__c has 2 picklislts --> Picklist_a__c and Pciklist_b__c
object1__c has a field(curreny_ --> amount__c

Scenario:

when amount__c(on Object1__c) is blank or null, and if record type is either A||B and Picklst_a__c and picklist__b is selected then Myamount__c should be required show be the error.

Thanks in advance.
 
Below is the trigger 
 
trigger TaskBeforeDelete on Task (before delete) {

      Map<Id,Profile> profileMap=new Map<Id,Profile>([SELECT Id,Name FROM Profile WHERE Name  IN ('Standard User')]);
       
    System.debug('profileMap==>'+profileMap);
    
    profile p=profileMap.get(UserInfo.getprofileID());
     try {
        
        for (Task task : Trigger.old)  {    
        
        	  if(task.Activity_LFD_Type__c.equalsIgnoreCase('Test') && task.WhatId.getSObjectType() == account.sObjectType && task.WhatId != null && (p==null) )           
            
            {    
                if(!Test.isRunningTest()){
                
                task.addError('You are not permitted to delete this task');
                
                }
     
            }
        
        }
        
    } Catch(Exception e){
        
            
       throw new RuntimeException('****TaskBeforeDelete:'+':' +e.getMessage());
    }
        
     }

Below is the test class 
 
@istest

    public class TaskBeforeDelete_Test{
    
    public static testMethod void BeforeDelete(){ 
    
           Profile pId = [SELECT Id FROM Profile WHERE Name = 'Test Profile'];
        
         User testUser = new User(Email='test@email.com',Phone='555-555-5555',
                                 FirstName='Test',LastName='User', ProfileId=pId.Id,UserName=uniqueName + '@test' + orgId + '.com',
                                 Alias='tesUse',TimeZoneSidKey='America/New_York',
                                 LocaleSIdKey='en_US',EmailEncodingKey='UTF-8',
                                 LanguageLocaleKey='en_US'); 
                                 
        
        system.runAs(testUser){
        
        account acc= new account();
        acc.name='test';
        acc.Site='testsite';
        insert acc;
        
        
       task task=new task();
       task.Activity_LFD_Type__c='Test';
       task.whatid=acc.id;
       
       insert task;
       
       delete task;
       
       }
        
    
    }


}

For the above trigger the code coverage is below 75 % and i'm not able to cover the catch block.

Can any one suggest on this please.
trigger updateProjectTeammember on opportunityTeamMember(after insert, after update, after delete){
        if(trigger.isInsert || trigger.isUpdate){
        
        Map<String,String> OppOtmfieldMap=new Map<String,String>();
               OppOtmfieldMap.put('Sr. Client Insights Manager','CEM_Assigned__c');
               OppOtmfieldMap.put('Client Insights Manager','CEM_2nd__c');
               OppOtmfieldMap.put('Data Manager','Ops_Owner__c');
               OppOtmfieldMap.put('Lead Consultant','Consultant_assigned__c');
               OppOtmfieldMap.put('Support Consultant','Consultant_2nd__c');
               OppOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               OppOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
        Map<String,String> projOtmfieldMap=new Map<String,String>();
               projOtmfieldMap.put('Sr. Client Insights Manager','Sr_Client_Insights_Manager__c');
               projOtmfieldMap.put('Client Insights Manager','Client_Insights_Manager__c');
               projOtmfieldMap.put('Data Manager','Ops_Manager__c');
               projOtmfieldMap.put('Lead Consultant','Lead_Consultant__c');
               projOtmfieldMap.put('Support Consultant','Support_Consultant__c');
               projOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               projOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
            list<id> oppoIdList = new list<id>();
            map<id, id> oppoOtmMap = new map<id, id>();
            list<id> proMemList = new list<id>();
            map<id, id> oppIdProIdMap = new map<id, id>();
            list<id> proId = new list<id>();
            Map<Id,Opportunity> oppIdMap = new Map<Id,Opportunity>();
            Map<id, id> oppIdAccIdMap = new Map<id, id> ();
            Set<id> accId=new Set<Id>();
            
        for(OpportunityTeamMember otm : trigger.new){
                        OppoIdList.add(otm.OpportunityId);
                        oppoOtmMap.put(otm.Id, otm.OpportunityId);
            }
        
        map<id, list<Project__c>> oppIdProjectListMap = new map<id, list<Project__c>>();
        list<Opportunity> oppoList = [select Id, accountId, Project__c, (Select Id, Name from Project__r) From opportunity Where Id In: oppoIdList];
        system.debug('--oppoIdList--' +oppoIdList);
        for(Opportunity op : oppoList){
            proId.add(op.id);
            oppIdMap.put(op.id,op);
            accId.add(op.accountId);
            oppIdAccIdMap.put(op.id, op.accountId);
           // oppIdProIdMap.put(op.id, op.Project__c);
            oppIdProjectListMap.put(op.id, op.Project__r);
            }
                
        list<Project_Team__c> ptmListForInsert = new list<Project_Team__c>();
        system.debug('--proId--' +proId);
        system.debug('--accId--' +accId);
        system.debug('--oppIdProIdMap--' +oppIdProIdMap);
        system.debug('--oppIdAccIdMap--' +oppIdAccIdMap); 
        
        list<Project_Team__c> ptmList = [Select id, Account__c, Project__c, Member_Role__c, Team_Member__c From Project_Team__c Where Id In: proId];
        map<id, list<Project_Team__c>> proPtmMap = new map<id, list<Project_Team__c>>();
        
        for(project_Team__c ptm : ptmList){
        
            list<project_Team__c> tempList = proPtmMap.get(ptm.Project__c);
            
            if(templist!= null && templist.Size()>0){
                tempList.add(ptm);
                }else{
                        tempList = new list<project_Team__c>();
                        tempList.add(ptm);
                }
                proPtmMap.put(ptm.Project__c, tempList);
            }
        
        for(OpportunityTeamMember otm : trigger.new){
        
            Boolean flag = false;
           
            List<project__c> listOfProj = oppIdProjectListMap.get(otm.OpportunityId);
            
            for(Project__c pro : listOfProj){
            List<project_team__c> listOfPrjTm = proPtmMap.get(pro.id);
            
            
            if(listOfPrjTm!= null){
                for(Project_Team__c ptm : listOfPrjTm){
                    if(otm.userId == ptm.Team_Member__c){
                        flag =true;
                        }
                    }
                }
                if(flag ==true){
                }else{
                    Project_Team__c ptm1 = new Project_Team__c();
                    ptm1.Team_Member__c= otm.userId;
                    ptm1.Member_Role__c = otm.TeamMemberRole;
                    ptm1.Account__c = oppIdAccIdMap.get(otm.OpportunityId);
                    ptm1.Project__c = proPtmMap.get(otm.OpportunityId);
                    ptmListForInsert.add(ptm1);
                    system.debug('--ptm1--' +ptm1);
                    }
            }}
        if(ptmListForInsert.size()>0){

        insert ptmListForInsert;
            }
            
  }
}
Wave Apps Basics - Creating Wave Apps
I'm trying to refresh data for Wave Analytics trail using Trailhead Data Manager
I'm getting STORAGE_LIMIT_EXCEEDED
I have 5 MB limit and Trailhead Data Manager eats up 6MB
I tired to delete all tasks and re-run but it creates all those tasks again and uses all available space.
Is somehow my dev org is too small or Trailhead Data Manager isn't working correctly?
How can I fix it?








 
  • February 13, 2017
  • Like
  • 1
I was trying to solve Data Integration Super badge Challenge #5, I tried to chek the REST Service with Work Bench it was working exactly as Required but My trail head Challenge shows the following Error.

Error.

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Upsert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Project End Date cannot be before Start Date.: []

Here is my code for the challenge. 
@RestResource(UrlMapping='/project/*')
global class ProjectRESTService {
       
    //Implement service logic here
    @HttpPost
    global static String postProjectData(String ProjectRef , String ProjectName, String OpportunityId, 
                                      Date StartDate, Date EndDate, Double Amount, String Status){
        
        list<Project__c> pliup=new list<Project__c>();
      	list<Opportunity> opplist=new list<Opportunity>();
        Project__c p=new Project__c();
        p.ProjectRef__c= ProjectRef; 
        p.Name=ProjectName;
        p.Opportunity__c= OpportunityId;
        p.Start_Date__c=StartDate;
        p.End_Date__c=EndDate;
        p.Billable_Amount__c=Amount;
        p.Status__c=Status;
                                          
        upsert p;
        
        pliup=[Select id,Opportunity__c from Project__c where Opportunity__c!=Null];
        for(Project__c po:pliup){
             
           
            Opportunity o=new Opportunity(id=po.Opportunity__c);
            o.DeliveryInstallationStatus__c='In Progress';
            
                update o;
            }
            

                                              
                                          
               Savepoint sp = Database.setSavepoint();
                                          
               return 'OK';
        
               Database.rollback(sp);
               return 'error';
                                      }
                                          
        
                             
   
        
        
        
          
            
            }

My JSON POST Reques from Work Bench
 
{"ProjectName":"om",
"OpportunityId":"00641000008weos",
"Status":"Being Awesome",
"StartDate":"2017-02-11",
"EndDate":"2018-02-11",
"ProjectRef":"akkill",
"Amount":"1000"}

 
Hi all,

I would need that if a user select a piclist field value, another text field can´t be blank.

Here is my code. Any help, please?

AND (
ISPICKVAL( Status  , "Unqualified"),
 NOT (ISBLANK( ReasonRejectedByCommercialPlanning__c ))

 )
  • February 10, 2017
  • Like
  • 1

I am using two tables. Invoice_Header(Parent) and Invoice_Line(Child) tables. Relationship is Invoice_Line__r(Being seen in Invoice_Line table in Schema Builder).

Fields we are going to Use: 

Invoice_Header:Invoice_no, Amount_minus_tax(we want sum of it), Salesrep__c

Invoice_Line: Invoice_no, prduct_group_id

Query Question: I want sum of all invoices (Amount_minus_tax) where salesrep is equal to Steven, product_group_Id = 'MERCH' 

 

I tried this Query, but it is not working:

select sum(amount_minus_tax__c) from CommercientSF10__EPICOREP21_InvoiceHeader__c where CommercientSF10__Salesrep__c = 'a0d61000004Jcvj' and CommercientSF10__EPICOREP21_Invoice_Lines__r.CommercientSF10__product_group_id__c = 'MERCH'

I can excecute query with left join but this will be having more rows than we need so I want to use Right join as shown in above Query.

Working Query with Left Join:

select CommercientSF10__invoice_no__c, (select CommercientSF10__invoice_no__c from CommercientSF10__EPICOREP21_Invoice_Lines__r where CommercientSF10__product_group_id__c = 'MERCH' ) from CommercientSF10__EPICOREP21_InvoiceHeader__c where CommercientSF10__Salesrep__c = 'a0d61000004Jcvj'

 

 

I've got a strange error. I grabbed the controller code from this blog post, but when I try to save it to my dev org, I get an error: unexpected token: '='. I can't seem to figure out why. Any help would be appreciated!

Here's the controller throwing the error:
Public class ThumnailController {

  public String imageUrl {get; set;}

  ContentVersion[] cvs = [select id from contentversion where contentdocumentid= '0691a0000015c3v' and isLatest=true];

  imageUrl ='/sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId=' + cvs[0].id;

}

The error is being thrown at this line:
imageUrl ='/sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId=' + cvs[0].id;


 
I am looking for help to run a Join Query to find all out Accounts in our Database without Contacts AND Opportuntiy.  I can run the query indepetly, but I would like to join the queries. 

The Query I am runing to find Accounts without Contacts: Select Id, Name From Account Where Id NOT IN (SELECT AccountId FROM Contacts)
Query to find Accounts without Opportunties: Select Id, Name From Account Where Id NOT IN (SELECT AccountId FROM Opportunity)
This rule works however, if the user chooses other value in the Stage name and chooses a required value for Product Support, this value doesn´t save. Any idea??. Thanks. Note: both field are picklist

IF(

 ISPICKVAL( StageName , "5 - Qualification"),

 ISPICKVAL( Product_Support__c, "None"),true)
  • February 10, 2017
  • Like
  • 1
Hi,
i am stuck in this below error can anyone suggest?I already imported contact and account successfully through import wizard.stuck for hobby,contact hobby and opportunity.When i am trying to import hobby data with the(list of contacts to import) CSV file.in mapping section it shows only hobby field.

can anyone guide me on this?

User-added image
Since reading Advanced Apex Programming I've been a propenent of the "one trigger to rule them all" framework.  I then carried that philosophy over to process builder using a single upsert process for each object (Lead Upsert process, Account Upsert process, etc.).  The primary reason was to better control execution context of when flows will run within that object.  Winter 17' release now allows for the building of process builder hierarchies which seems like it eliminates the need to bunch everything up into a single process.

What do you think?  What does your process builder framework look like?
This error can be caused in one of two ways:
  1. ​You've been away for a while and you're now logged out of your DE. This can simply be resolved by logging in again and restoring the connection.
  2. No matter how many times you log out and log in again, having the security setting "Lock sessions to the IP address from which they originated" enabled will prevent you from connecting your Org to Trailhead. For some reason, when trailhead checks challenges, it doesn't use the same IP address throughout the transaction, causing the error because the connector was logged out. As much as I'd like to claim this as my own discovery, @Matt Latto was the one to come up with the solution and posted it on another question, Not able to verify steps of Trailhead project.
Although this isn't officially a question, to my knowledge this information is not anywhere else on the forum, and if it is, it couldn't hurt to post it again.

Thanks for viewing,
Parker

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

 

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