I need to create a new expense card, the input parameters are Amount, Date and Description.
Fields that must be filled in the expense card to create it: Card keeper is contact Months Expenses Applications is a custom object
When creating an expense card, if Months Expenses Applications exists by the date entered in the "Date" field, then a new expense card is created from which Months Expenses Applications is taken from the existing one
if, by the date entered in the "date" field, there is no Months Expenses Applications, you need to create Months Expenses Applications and then create an expense map in which Months Expenses Applications will have a new Months Expenses Applications created
I tried to create an expense map with "Amount" "Date" "Description" equal to the input parameters, but I don't know how to specify MonthExpenseApplication__c
public static void createNewExpenseCard(Integer amount, Date createdDate, String description) {
Month_Expense_Application__c MonthApplication = [
SELECT Name, MonthDate__c
FROM Month_Expense_Application__c
WHERE MonthDate__c =: createdDate
];
if (MonthApplication != null) {
ExpenseCard__c exp = new ExpenseCard__c(
Amount__c = amount,
CardDate__c = createdDate,
Description__c = description,
CardKeeper__c = '0034x00001K7kGCAAZ'
);
exp.MonthExpenseApplication__c = [
SELECT MonthExpenseApplication__c
FROM ExpenseCard__c
WHERE MonthExpenseApplication__c =: MonthApplication.Id
].Id;
insert exp;
} else {
Month_Expense_Application__c monthApp = new Month_Expense_Application__c(
Balance__c = 1000,
MonthDate__c = createdDate,
Keeper__c = '0034x00001K7kGCAAZ'
);
ExpenseCard__c exp2 = new ExpenseCard__c(
Amount__c = amount,
CardDate__c = createdDate,
Description__c = description,
CardKeeper__c = '0034x00001K7kGCAAZ'
);
insert exp2;
}
}
This is dangerous:
Month_Expense_Application__c MonthApplication = [
SELECT Name, MonthDate__c
FROM Month_Expense_Application__c
WHERE MonthDate__c =: createdDate
];
If there are zero results it will throw "list has no rows for assignment". Similar if there's more than 1.
Something like this?
Integer amount = 50;
Date createdDate = System.today();
String description = 'Lorem ipsum...';
Month_Expense_Application__c app;
List<Month_Expense_Application__c> applications = [SELECT Id
FROM Month_Expense_Application__c
WHERE MonthDate__c =: createdDate
LIMIT 1];
if(applications.isEmpty()){
app = new Month_Expense_Application__c(
Balance__c = 1000,
MonthDate__c = createdDate,
Keeper__c = '0034x00001K7kGCAAZ'
);
insert app;
} else {
app = applications[0];
}
// one way or another - the monthly allowance exists now. So just use its id in the lookup
ExpenseCard__c exp = new ExpenseCard__c(
Amount__c = amount,
CardDate__c = createdDate,
Description__c = description,
CardKeeper__c = '0034x00001K7kGCAAZ',
Month_Expense_Application__c = app.Id
);
There are more elegant ways to do it, you'd need to read up about upsert and external ids - but it should be good enough.