• Mohit. Lakde
  • NEWBIE
  • 25 Points
  • Member since 2017
  • Lead Salesforce Developer


  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 7
    Replies
I am attempting to add a formula to the "Age" field in the Opportunity object that will calculate the age of the Opportunity based on the date it was created.  i am currently using this formula: 

IF( CONTAINS(TEXT(StageName), 'Closed'),   CloseDate -  DATEVALUE(CreatedDate) , TODAY() -  DATEVALUE(CreatedDate) ).  

When checking the syntax, I receive the following error: Error: Field StageName may not be used in this type of formula

Can anyone help me figure out why i am receiving this error?
 
Hello Experts,

I need help if someone ever faced such issue before. 

Background: Community Users using Visualforce page inputFile upload feature, which is working fine but it limiting to upload more than 10 MB size file(Salesforce Limitations with VF file upload). 
So, as an alternative solution I am trying to write REST API to create attachment. 
Once user selects file on VF Page, I am getting blob which I am using to send in POST Request. But receiving bad request error as below:

System.CalloutException: [{"message":"No such column 'file' on sobject of type Attachment","errorCode":"INVALID_FIELD"}]
basically, when user attaching file it coming as "core.filemanager.FileBlobValue@2354b51c" and after after serialize its coming as Blob[228800].
So I belive I am making some mistake while parsing file and while calling REST API.

Below is Sample Code:
 
Attachment att = new Attachment(parentId = '0011K00002LRfQF', Name=fname, Body = body, OwnerId = UserInfo.getUserId());

String sfdcURL =. URL.getSalesforceBaseUrl().toExternalForm();
String url = sfdcURL +'/services/data/v48.0/sobjects/Attachment';

String jsonBody = JSON.serialize(att);
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json';
req.setMethod('POST');
req.setEndpoint(url);
req.setBody(jsonBody);
req.setTimeout(60000);
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
Http http = new Http();
HTTPResponse res = http.send(req);

Thanks in Advance..
I am attempting to add a formula to the "Age" field in the Opportunity object that will calculate the age of the Opportunity based on the date it was created.  i am currently using this formula: 

IF( CONTAINS(TEXT(StageName), 'Closed'),   CloseDate -  DATEVALUE(CreatedDate) , TODAY() -  DATEVALUE(CreatedDate) ).  

When checking the syntax, I receive the following error: Error: Field StageName may not be used in this type of formula

Can anyone help me figure out why i am receiving this error?
 
Hello all.  I am VERY new to the development side of SF but have been doing admin for over 4 years.  I want to use Apex to edit a checkbox on the product object. for this query (SELECT Id,Name, fw8__QuickBooks_ID__c,Family,fw8_1__QB ) How do I accomplish this, please help.
Create an Apex trigger for Opportunity that adds a task to any opportunity set to 'Closed Won'


trigger ClosedOpportunityTrigger on Opportunity(after insert, after update) {
List<Task> oppList = new List<Task>();
for (Opportunity a : [SELECT Id,StageName,(SELECT WhatId,Subject FROM Tasks) FROM Opportunity
WHERE Id IN :Trigger.New AND StageName LIKE '%Closed Won%']) {
oppList.add(new Task( WhatId=a.Id, Subject='Follow Up Test Task'));
}
if (oppList.size() > 0) {
insert oppList;
}
}
  • March 16, 2023
  • Like
  • 0
when the Account is updated check all opportunities related to the account. Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won


trigger OppoStageUpdate on Account (after update){
Set<Id> accountIds = new Set<Id>();
for(Account a:Trigger.new){
accountIds.add(a.Id);
}
//day30 is the date which is 30 days less than today
DateTime day30=system.now()-30;
List<Opportunity> oppListToUpdate=new List<Opportunity>();
//getting the opportunities whose account has been updated
List<Opportunity> oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where AccountId in :accountIds];
if(oppList.size()>0){
for(Opportunity opp : oppList){
//checking for condition if created date is greater than 30 days from today and stage not equal to close won
if(opp.CreatedDate<day30 && opp.StageName!='Closed Won'){
opp.StageName='Closed Lost';    //This is a mandatory field when we update the CloseDate
opp.CloseDate=system.today();
oppListToUpdate.add(opp);  //putting the changed opportunity to separate list to update later
}
}
}
//checking if the opportunity list which has changed is having records or not
if(oppListToUpdate.size()>0){
update oppListToUpdate;
}
}
  • March 16, 2023
  • Like
  • 0
Hi i have the following task:

Requirements:
    1. Create a batch class that summarizes all Opportunity Amounts for each Account;
    2. An email should be sent to the primary contact of all Accounts,
    containing a table with the Closed Won/Open/Closed Lost summarized Opportunity Amounts;
    3. The schedulable class that calls the batch class should be created;
    4. The class should be scheduled from the Developer Console.
    Please provide the script to schedule the job daily at 10:00 AM, once a week (Friday at 1:00 PM),
    once a month(Last Friday of the Month at 6:00 PM).


My code right now looks like this:

/*
Requirements:
    1. Create a batch class that summarizes all Opportunity Amounts for each Account;
    2. An email should be sent to the primary contact of all Accounts,
    containing a table with the Closed Won/Open/Closed Lost summarized Opportunity Amounts;
    3. The schedulable class that calls the batch class should be created;
    4. The class should be scheduled from the Developer Console.
    Please provide the script to schedule the job daily at 10:00 AM, once a week (Friday at 1:00 PM),
    once a month(Last Friday of the Month at 6:00 PM).
*/
global with sharing class exercise03BatchClass implements Database.Batchable<SObject> {
   
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // Query all accounts and their related opportunities
        return Database.getQueryLocator(
            'SELECT Id, (SELECT Id FROM Opportunities) FROM Account'
        );
    }
    global void execute(Database.BatchableContext BC, List<Account> scope) {
        // Set the same list of accounts as the batch's state
        BC.getJobExecutionContext().put('scope', scope);
        // Create a list of custom object records to store the related opportunities
        List<exercise03Object__c> accountOpps = new List<exercise03Object__c>();
        for (Account acc : scope) {
            // Create a new custom object record for the account
            exercise03Object__c accOpp = new exercise03Object__c();
            accOpp.accId__c = acc.Id;
            // Serialize the opportunities as JSON and store them in a custom field on the record
            accOpp.opps__c = JSON.serialize(acc.Opportunities);
            accountOpps.add(accOpp);
        }
        // Insert the custom object records
        insert accountOpps;
    }
    global void finish(Database.BatchableContext BC, List<Account> scope) {
       
        // Get a list of Account IDs from the scope
        List<Id> accountIds = new List<Id>();
        for (Account acc : (List<Account>)scope) {
            accountIds.add(acc.Id);
        }
   
        // Query the custom object to get the related opportunities for the accounts
        List<exercise03Object__c> accOpps = [SELECT Id, accId__c, opps__c FROM exercise03Object__c WHERE accId__c IN :accountIds];
   
        // Map the account IDs to their corresponding primary contact IDs
        Map<Id, Id> accIdToContactId = new Map<Id, Id>();
        for (Contact con : [SELECT Id, AccountId FROM Contact WHERE IsPrimaryContact__c = true AND AccountId IN :accountIds]) {
            accIdToContactId.put(con.AccountId, con.Id);
        }
   
        // Loop through the accounts and send the email to their primary contacts
        for (exercise03Object__c accOpp : accOpps) {
            Id contactId = accIdToContactId.get(accOpp.accId__c);
            if (contactId != null) {
                // Create the email message and set the recipient
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(new List<String>{Contact.getSobjectType().getDescribe().getKeyPrefix() + contactId});
   
                // Set the email template and merge fields
                email.setTemplateId('00XDn00000136nl');
                email.setTargetObjectId(contactId);
   
                // Set the merge field values for the email template
                email.setTemplateData(new Map<String, Object>{
                    'AccountName' => accOpp.accId__r.Name,
                    'oppList' => (List<Opportunity>)JSON.deserialize(accOpp.opps__c, List<Opportunity>.class)
                });
   
                // Send the email
                Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
            }
        }
    }
   
}

but i'm gettingh the following error and i don't know why:

Class exercise03BatchClass must implement the method: void Database.Batchable<SObject>.finish(Database.BatchableContext) (15:27)
Hello Experts,

I need help if someone ever faced such issue before. 

Background: Community Users using Visualforce page inputFile upload feature, which is working fine but it limiting to upload more than 10 MB size file(Salesforce Limitations with VF file upload). 
So, as an alternative solution I am trying to write REST API to create attachment. 
Once user selects file on VF Page, I am getting blob which I am using to send in POST Request. But receiving bad request error as below:

System.CalloutException: [{"message":"No such column 'file' on sobject of type Attachment","errorCode":"INVALID_FIELD"}]
basically, when user attaching file it coming as "core.filemanager.FileBlobValue@2354b51c" and after after serialize its coming as Blob[228800].
So I belive I am making some mistake while parsing file and while calling REST API.

Below is Sample Code:
 
Attachment att = new Attachment(parentId = '0011K00002LRfQF', Name=fname, Body = body, OwnerId = UserInfo.getUserId());

String sfdcURL =. URL.getSalesforceBaseUrl().toExternalForm();
String url = sfdcURL +'/services/data/v48.0/sobjects/Attachment';

String jsonBody = JSON.serialize(att);
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','application/json';
req.setMethod('POST');
req.setEndpoint(url);
req.setBody(jsonBody);
req.setTimeout(60000);
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
Http http = new Http();
HTTPResponse res = http.send(req);

Thanks in Advance..