-
ChatterFeed
-
33Best Answers
-
0Likes Received
-
3Likes Given
-
0Questions
-
176Replies
System.NullPointerException: Attempt to de-reference a null object
Here is my below code :
/**
@description Class for the Redirect With Variables page.
Function: Handles the controller logic for the RedirectWithVariables page.
*/
public with sharing class RedirectWithVariablesController {
/*
* Method name: redirectUser
* @description Redirects the user to the given object + parameters
* @return PageReference The page the user needs to be redirect to.
*/
public pagereference prePopulateFields(){
//Get object name
String strObject = System.currentPageReference().getParameters().get('object');
string params = '';
Integer a = 0;
map<String,String> fields = getFieldsIdsMap(strObject);
string regName = System.currentPageReference().getParameters().get('Registration__c');
string regId = System.currentPageReference().getParameters().get('ID_Registration__v');
string retURL = System.currentPageReference().getParameters().get('retURL');
string stakeholerName = System.currentPageReference().getParameters().get('Stakeholder__c');
string stakeholerId = System.currentPageReference().getParameters().get('ID_Stakeholder__v');
for(string k: fields.keySet()){
//ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, k+''));
//System.debug('label: ' + a + ': ' + k);
//a++;
if(k == 'Registration'){
params += fields.get(k) + '=' + regName + '&' + fields.get(k) + '_lkid=' + regId + '&';
}
if(k == 'Stakeholder'){
params += fields.get(k) + '=' + stakeholerName + '&' + fields.get(k) + '_lkid=' + stakeholerId+ '&';
}
}
//for(string p:fields.values()){
// params += p+'=Test Value '+a+'&';
// a++;
//}
PageReference p = new PageReference('/' +
Schema.getGlobalDescribe().get(strObject).getDescribe().getKeyPrefix() + '/e?'+
params+'nooverride=1&retURL=' + retURL);
p.setRedirect(true);
return p;
}
public map<String, String> getFieldsIdsMap(String sObjectName) {
map<String, String> label_IdMap = new map<String, String>();
if(null!= sObjectName && sObjectName.trim() != '') {
//if(!isObjectValid(sObjectName)){
// return null;
//}
PageReference p = new PageReference('/' +
Schema.getGlobalDescribe().get(sObjectName).getDescribe().getKeyPrefix()
+ '/e?nooverride=1'); // this one return null in the url
String html = '';
if(!Test.isRunningTest()) {
html = p.getContent().toString();
} else {
//html = '';
html = '<label for="CF00NK0000000Yt1b"><span class="requiredMark">*</span>Name</label>';
}
Matcher m = Pattern.compile('<label for="(.*?)">(<span class="requiredMark">\\*</span>)?(.*?)</label>').
matcher(html);
while(m.find()) {
String label = m.group(3);
String id = m.group(1);
label_IdMap.put(label, id);
}
}
return label_IdMap;
}
}
controller:
public class DisclosureNewOverrideController{
public String retURL {get;set;}
public DisclosureNewOverrideController(ApexPages.standardController sc){
retURL = ApexPages.CurrentPage().GetParameters().Get('retURL');
system.debug('nghiatran retURL ' + retURL + ' ' + retURL.substring(1));
//ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This: ' + retURL));
//string objectName = getObjectName(retURL);
string objectName = CommonUtils.getObjectName(retURL.substring(1));
if(objectName == 'Disclosure_Claim_for_Payment__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Disclosure/Claim for Payment is created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a New Disclosure, please navigate to the Stakeholder record -> Disclosure Obligation record.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a New Claim for Payment, please navigate to the Stakeholder record -> Eligible Claim for Payment record.'));
}else if(objectName == 'Disclosure_Obligation__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Disclosure Obligation is created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a new Disclosure Obligation, please navigate to the Stakeholder record.'));
}else if(objectName == 'HP_Trim_Container__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Donor TRIM Containers are created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create the Donor TRIM Containers, please navigate to the \'All\' list view and click on \'Generate Donor TRIM Containers.\''));
}
}
this is 2 url when create new disclosure :
not ok https://c.cs6.visual.force.com/apex/DisclosureObligationNewOverride?save_new=1&sfdc.override=1
the account name :Mr Madhvi Lata & Visapaa
ok :https://c.cs6.visual.force.com/apex/DisclosureObligationNewOverride?CF00NN0000000MBK7=Aegis+Consulting+Group+Pty+Ltd&CF00NN0000000MBK7_lkid=001N000000M1lpg&scontrolCaching=1&retURL=%2F001N000000M1lpg&sfdc.override=1
the account name :Aegis Consulting Group Pty Ltd
- Huy Nguyen
- December 16, 2014
- Like
- 0
- Continue reading or reply
Need Help for test for this trigger
i need to write test class for this trigger. Please give some idea
trigger accountTestTrggr on Account (before insert,before update) {
List<Account> accountsWithContacts = [select id, name,(select id,firstname, lastname,Description from Contacts) from Account where Id IN :Trigger.newMap.keySet()];
List<Contact> contactsToUpdate = new List<Contact>{};
for(Account a: accountsWithContacts){
for(Contact c: a.Contacts){
c.Description=c.firstname+c.lastname;
contactsToUpdate.add(c);
}
}
update contactsToUpdate;
}
- deepak kumar 13
- December 04, 2014
- Like
- 0
- Continue reading or reply
Email notification when an attachment is added to a case-Urgent
- Praveen Jha
- December 04, 2014
- Like
- 0
- Continue reading or reply
How to get photoURL from FeedItem object?
How to get photoURL from FeedItem object?
i have tried Createdby.smallphotourl but it's not working for FeedItem object...
- kannapapi
- December 04, 2014
- Like
- 0
- Continue reading or reply
Log a call using REST API
I can access the account details using REST - that works.
However I am unable to seach for the existing call logs that I created using the SalesForce UI using any REST query. What am I missing?
I understand I need to create a Task object for logging a call.
Once I create a task for the call, how do I associate it with a particular account so that it would show up in the UI in the Account page?
Thanks and would be great if you could point me in the right direction if something like this already exists. Didnt find it and hence thought of posting.
- Manu Srivastava
- December 04, 2014
- Like
- 0
- Continue reading or reply
Trailhead ApexTrigger unit1/2 Executing the trigger did not work as expected.
Below are the requirements to complete Challenge
The Account object will need a new custom checkbox that should have the Field Label 'Match Billing Address' and Field Name of 'Match_Billing_Address'. The resulting API Name should be 'Match_Billing_Address__c'.
With 'AccountAddressTrigger' active, if an Account has a Billing Postal Code and 'Match_Billing_Address__c' is true, the record should have the Shipping Postal Code set to match on insert or update.
I have created new custom Checkbox(MatchBillingAddress) and Below is my trigger:
trigger AccountAddressTrigger on Account (before update,before insert)
{
List<Account> list1=[SELECT Id,Match_Billing_Address__c,ShippingPostalCode,BillingPostalCode from Account];
for(Integer i=0;i<list1.size();i++)
{
if(list1[i].Match_Billing_Address__c=true && list1[i].BillingPostalCode!=NULL)
{
list1[i].ShippingPostalCode=list1[i].BillingPostalCode;
update list1[i];
}
}
}
I got Error like : Executing the trigger did not work as expected.
Can anyone please help me to achieve this. Thanks
- Anitha J J 2
- December 03, 2014
- Like
- 0
- Continue reading or reply
How Do I enable REST API for organization.
I am trying to use REST API for SalesForce for that I need to Enable REST API.
for that I went through Setup -> Manage Users -> Permission Sets -> Create New, but I am seeing Insufficient Privileges page.
I am using 30 days trial version.
How can I enable REST API ?
Thanks
- Pratik Sathaye 9
- December 03, 2014
- Like
- 0
- Continue reading or reply
Not able to see Login button for all users on user detail page even if i'm an administrator in developer account
- sharathchandra thukkani
- December 03, 2014
- Like
- 0
- Continue reading or reply
System.Limit exception:Apex CPU time limit
trigger LineItemTypeTrigger on Line_Item_Type__c (after update) {
try
{
if (Trigger.isUpdate && Trigger.isAfter)
{
Map<String, Decimal> oldRecAuditAmount = new Map<String, Decimal>();
Map<String, Decimal> oldRecAmount = new Map<String, Decimal>();
Set<String> litTriggerIds = new Set<String>();
for (Line_Item_Type__c oldRec : Trigger.old) {
if (oldRec.Calculated_Amount__c != null)
oldRecAmount.put(oldRec.Id, oldRec.Calculated_Amount__c );
if (oldRec.Calculated_Audit_Amount__c != null)
oldRecAuditAmount.put(oldRec.Id, oldRec.Calculated_Audit_Amount__c );
}
for (Line_Item_Type__c newRec : Trigger.new) {
if (oldRecAmount.containsKey(newRec.Id))
if (oldRecAmount.get(newRec.Id) != newRec.Calculated_Amount__c )
litTriggerIds.add(newRec.Id);
if (oldRecAuditAmount.containsKey(newRec.Id))
if (oldRecAuditAmount.get(newRec.Id) != newRec.Calculated_Audit_Amount__c )
litTriggerIds.add(newRec.Id);
}
if (litTriggerIds.size() > 0)
{
LineItemTypeTriggerHandler handler = new LineItemTypeTriggerHandler();
handler.OnAfterUpdate(litTriggerIds);
}
}
}
catch (Exception e)
{
System.debug('Error Occurred:' + '[' + e.getMessage() +' ]');
}
}
- Huy Nguyen
- December 03, 2014
- Like
- 0
- Continue reading or reply
validation Trigger Please help
I was helped wih this brilliant trigger by a scotty McClung, but correspondence recently died down. He had a brilliant idea, where I used my current business model to create a validation rule. It works, but it is not finished just yet.
Basically I have account, account has a child service__c. A user will add a service to an account, to do so they will select the picklist service_name__c and service_type__c, which will use a trigger that has an soql querry which finds the record from destiny_product_and_services__c and therefore will autofill formula fields on the service record.
I have added another field called macimum records to the destiny_products_and_service__c database. The trigger checks to see if the services attached to the account is greater than the number set in maximum records and if so will error.
This all works properly, except it only runs off service_name__c rather than both service_name__c and service_type__c. I was wondering if someone would give me a hand on either making it so that it will find the exact record through service_name__c and service_type__c or run by the actual record name field.
If it helps, in the database object - the name of the record is basically service_name__c (service_type__c).
E.g. A record with service_name__c = advantage program and service_type__c = new client would be:
Advantage Program (new client).
Thank you in advance for your time
To further explain, Destiny_rpoducts_and_services and service_c have two same fields which is two picklist service_name__c and service_type__c on service__c and the same but texts fields on Destiny_products_and_services. A trigger is used to take the picklist options and autofill the correct lookup.
This is my code:
Trigger ServiceValidation2 on Service__c (before insert) { //Populate a map of the ServiceRules object using the service name as the key Map<String, Destiny_Products_and_Services__c> mapServiceRules = new Map<String, Destiny_Products_and_Services__c>(); for(Destiny_Products_and_Services__c objRule : [SELECT Name, MaximumRecords__c FROM Destiny_Products_and_Services__c]) { mapServiceRules.put(objRule.Name, objRule); } //Populate a set of account_ids to use in your SOQL query Set<Id> setAccountIds = new Set<Id>(); for(Service__c objService : trigger.new) { setAccountIds.add(objService.Account__c); } //Populate a map of the aggregate query results Map<String, Map<String, Decimal>> mapResults = new Map<String, Map<String, Decimal>>(); AggregateResult[] groupedResult = [SELECT Account__c, service_name__c, Service_type__c, Count(Id) countOfRecords FROM Service__c WHERE Account__c IN :setAccountIds GROUP BY Account__c, Service_name__c, Service_type__c]; for(AggregateResult ar : groupedResult) { if(!mapResults.containsKey((String)ar.get('Account__c'))) { mapResults.put((String)ar.get('Account__c'), new Map<String, Decimal>()); } mapResults.get((String)ar.get('Account__c')).put((String)ar.get('Service_Name__c'), (Decimal)ar.get('countOfRecords')); } //Iterate through your list of Service__c records and generate an error for any //that have a matching Account__c in the map for(Service__c objService : trigger.new) { if(mapServiceRules.containsKey(objService.Service_Name__c) && mapServiceRules.get(objService.Service_Name__c).MaximumRecords__c != null) { //If there is no rule set ignore the record if(mapResults.containsKey(objService.Account__c)) { if(mapResults.get(objService.Account__c).containsKey(objService.Service_Name__c)) { if(mapResults.get(objService.Account__c).get(objService.Service_Name__c) >= mapServiceRules.get(objService.Service_Name__c).MaximumRecords__c) { objService.addError('This service has already been added the maximum number of times'); } } } } } }
- Developer.mikie.Apex.Student
- May 16, 2014
- Like
- 0
- Continue reading or reply
Not able to stored previous page selected rows in wrapper class.
Hi,
Below controller is a wrapper class using pagination. Issue I am facing here is I am displaying pages in pagination User can select rows and insert the data.
Problem here is previous selected rows once moved to next page is not getting stored.
Only the currect page which is selected are getting stored not the previous page. Please suggest me how to fix.
Controller
public with sharing class CCW_ContactPaginationController {
//URL Passing Parameters.
String PageContractId = ApexPages.currentPage().getParameters().get('ContractId');
String PageAccountId = ApexPages.currentPage().getParameters().get('AccountId');
public Asset GetAccount{get;set;}
public Asset GetContract{get;set;}
public Asset GetExpireDate{get;set;}
public Asset GetReseller{get;set;}
public Asset GetDistributor{get;set;}
public Boolean IncumbentReseller{get;set;}
public Boolean Education{get;set;}
public Asset GetOpportunity{get;set;}
public Asset GetNewOpportunity{get;set;}
public String ExpireTerms{get;set;}
//Our collection to class/wrapper objects wrapAsset
public List<CCWRowItem> wrapAssetList {get; set;}
public List<Asset> selectedAssets{get;set;}
/*
* item in context from the page
*/
public String contextItem{get;set;}
/*
* set controller
*/
private ApexPages.StandardSetController setCon;
/*
* the contact ids selected by the user
*/
private Set<Id> selectedContactIds;
/*
* constructor
*/
public CCW_ContactPaginationController ()
{
GetAccount = new Asset(); //Get Account Id from Page
GetContract = new Asset(); //Get Contract Name from Page
GetExpireDate = new Asset(); // Date Picker
GetReseller = new Asset();
GetDistributor = new Asset();
GetOpportunity = new Asset(); // Get Opportunity Id
GetNewOpportunity = new Asset(); // Get New Opportunity Name
fetch_data();
}
// public List<Asset> Asset_yourObjList{get;set;}
public void fetch_data ()
{
//init variable
this.selectedContactIds= new Set<Id>();
//gather data set
If ( GetAccount.AccountId == NULL || GetContract.Name == NULL )
{
If ( PageContractId <> NULL )
{
Contract C;
C = [SELECT Name FROM Contract WHERE Id = :PageContractId Limit 1];
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE last_contract_number__c = :C.Name Limit 1000] );
}
else If ( PageAccountId <> NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :PageAccountId Limit 1000] );
}
}
If ( GetAccount.AccountId <> NULL && GetContract.Name == NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :GetAccount.AccountId Limit 1000] );
}
Else If ( GetContract.Name <> NULL && GetAccount.AccountId == NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE last_contract_number__c = :GetContract.Name Limit 1000] );
}
Else If ( GetAccount.AccountId <> NULL && GetContract.Name <> NULL )
{
this.setCon = new ApexPages.StandardSetController( [SELECT AccountId,Product2Id,SerialNumber,last_contract_number__c,Service_Start_Date_Min__c, Service_End_Date_Max__c,InstallDate FROM Asset WHERE AccountId = :GetAccount.AccountId and last_contract_number__c = :GetContract.Name Limit 1000] );
}
this.setCon.setpageNumber(1);
this.setCon.setPageSize(10);
}
/*
* handle item selected
*/
public void doSelectItem(){
this.selectedContactIds.add(this.contextItem);
}
/*
* handle item deselected
*/
public void doDeselectItem(){
this.selectedContactIds.remove(this.contextItem);
}
/*
* return count of selected items
*/
public Integer getSelectedCount(){
return this.selectedContactIds.size();
}
/*
* advance to next page
*/
public void doNext(){
if(this.setCon.getHasNext())
this.setCon.next();
}
/*
* advance to previous page
*/
public void doPrevious(){
if(this.setCon.getHasPrevious())
this.setCon.previous();
}
//public List<CCWRowItem> rows = new List<CCWRowItem>();
public List<CCWRowItem> rows {get; set;}
/*
* return current page of groups
*/
public List<CCWRowItem> getContacts(){
rows = new List<CCWRowItem>();
for(sObject r : this.setCon.getRecords()){
Asset c = (Asset)r;
CCWRowItem row = new CCWRowItem(c);
if(this.selectedContactIds.contains(c.Id)){
row.IsSelected=true;
}
else{
row.IsSelected=false;
}
rows.add(row);
}
return rows;
}
// Store Selected Records to Object/Table
public void processSelected() {
selectedAssets = new List<Asset>();
list<Temp_Assets__c> TempAssetList = new list<Temp_Assets__c>();
for(CCWRowItem wrapAssetObj : rows ) {
if(wrapAssetObj.IsSelected == true) {
selectedAssets.add(wrapAssetObj.tContact);
}
}
Account ResellerAct;
Account DistributorAct;
Opportunity Oppt;
for(Asset Act : selectedAssets)
{
Temp_Assets__c TempAsset = new Temp_Assets__c();
TempAsset.Name = 'Sudhir';
TempAsset.AccountId__c = Act.AccountId;
TempAsset.Product__c = Act.Product2Id;
TempAsset.Serial_Number__c = Act.SerialNumber;
TempAsset.Last_Contract_Number__c = Act.last_contract_number__c;
TempAsset.Service_Start_Date__c = Act.Service_Start_Date_Min__c;
TempAsset.Service_End_Date__c = Act.Service_End_Date_Max__c;
//TempAsset.Service_End_Date__c = maxDate;
TempAsset.Install_Date__c = Act.InstallDate;
If (GetReseller.AccountId <> NULL)
{
ResellerAct = [ SELECT Id FROM Account WHERE ID = :GetReseller.AccountId Limit 1];
TempAsset.Reseller__c = ResellerAct.Id;
}
If (GetDistributor.AccountId <> NULL )
{
DistributorAct = [ SELECT Id FROM Account WHERE ID = :GetDistributor.AccountId Limit 1];
TempAsset.Distributor__c = DistributorAct.Id;
}
If ( GetOpportunity.Opportunity__c <> NULL )
{
Oppt = [SELECT Id FROM Opportunity WHERE ID = :GetOpportunity.Opportunity__c Limit 1];
TempAsset.Existing_Opportunity__c = Oppt.Id;
}
TempAsset.Incumbent_Reseller__c = IncumbentReseller;
TempAsset.Education__c = Education;
TempAsset.Expiry_Date__c = GetExpireDate.Expire_Date__c;
TempAsset.New_Opportunity__c = GetNewOpportunity.New_Opportunity__c;
TempAsset.Expiry_Term__c = ExpireTerms;
//Add the selected Assets to the List
TempAssetList.add(TempAsset);
}
Insert TempAssetList;
}
/*
* return whether previous page exists
*/
public Boolean getHasPrevious(){
return this.setCon.getHasPrevious();
}
/*
* return whether next page exists
*/
public Boolean getHasNext(){
return this.setCon.getHasNext();
}
/*
* return page number
*/
public Integer getPageNumber(){
return this.setCon.getPageNumber();
}
/*
* return total pages
*/
Public Integer getTotalPages(){
Decimal totalSize = this.setCon.getResultSize();
Decimal pageSize = this.setCon.getPageSize();
Decimal pages = totalSize/pageSize;
return (Integer)pages.round(System.RoundingMode.CEILING);
}
/*
* helper class that represents a row
*/
public with sharing class CCWRowItem{
public Asset tContact{get;set;}
public Boolean IsSelected{get;set;}
public CCWRowItem(Asset c){
this.tContact=c;
this.IsSelected=false;
}
}
}
Visual Force
<apex:page controller="CCW_ContactPaginationController" showHeader="false" sidebar="false" readOnly="false" cache="false">
<script type="text/javascript">
/*
* function to handle checkbox selection
*/
function doCheckboxChange(cb,itemId){
if(cb.checked==true){
aSelectItem(itemId);
}
else{
aDeselectItem(itemId);
}
}
</script>
<apex:sectionHeader subtitle="Create Renewal Quote" title="Meru Networks"/>
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Save Records" action="{!processSelected}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Install Base Report" id="mpb" collapsible="true" columns="1">
<!-- handle selected item -->
<apex:actionFunction name="aSelectItem" action="{!doSelectItem}" rerender="mpb">
<apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
</apex:actionFunction>
<!-- handle deselected item -->
<apex:actionFunction name="aDeselectItem" action="{!doDeselectItem}" rerender="mpb">
<apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
</apex:actionFunction>
<!-- table of data -->
<apex:pageBlockTable title="Assets" value="{!Contacts}" var="c">
<apex:column >
<apex:facet name="header">Action</apex:facet>
<apex:inputCheckbox value="{!c.IsSelected}" onchange="doCheckboxChange(this,'{!c.tContact.Id}')"/>
</apex:column>
<apex:column value="{!c.tContact.AccountId}"/>
<apex:column value="{!c.tContact.Product2Id}"/>
<apex:column value="{!c.tContact.SerialNumber}"/>
<apex:column value="{!c.tContact.last_contract_number__c}"/>
<apex:column value="{!c.tContact.Service_Start_Date_Min__c}"/>
<apex:column value="{!c.tContact.Service_End_Date_Max__c}"/>
<apex:column value="{!c.tContact.InstallDate}"/>
</apex:pageBlockTable>
<apex:pageBlockSection collapsible="false" columns="4">
<!-- count of selected items -->
<apex:outputLabel value="[{!selectedCount} records selected]" />
<apex:outputLabel value=" (page {!pageNumber} of {!totalPages}) " />
<!-- next, previous and page info -->
<apex:commandLink action="{!doPrevious}" rendered="{!hasPrevious}" value="Previous" />
<apex:outputLabel rendered="{!NOT(hasPrevious)}" value="Previous" />
<apex:commandLink action="{!doNext}" rendered="{!hasNext}" value="Next" />
<apex:outputLabel rendered="{!NOT(hasNext)}" value="Next" />
</apex:pageBlockSection>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Thanks
Sudhir
- Sudhir_Meru
- May 13, 2014
- Like
- 0
- Continue reading or reply
Call a action function and pass param on 'onclick of output link'
I am trying to call an actionfunction on the onlick event of an output link and pass param values to the contoller is this possible?Currently it is not passing anything to the controller
My ActionFunction
<apex:actionFunction name="olla" action="{!testing}" >
<apex:param value="{!Name}" assignTo="{!accountName}" name="name" />
</apex:actionFunction>
My Link
<apex:outputLink onclick="olla('{!a.name}');return false;">{!a.name}</apex:outputLink>
- anuragsinghns
- May 13, 2014
- Like
- 0
- Continue reading or reply
i need to add two aggregate results with 1 value each into my for loop; but i need both ventasSemanales and ventasMensuales to run just one time per user and add those values into Posiciones Map. Any ideas how can i achieve that??
public class tablaVentas {
public list <Leads__c> puntos = [select ownerid, Puntos__c, Estado__c from leads__c where ownerid IN (select id from user) order by Puntos__c DESC];
public list <User> users= [select name from user];
//I need to get this values per user and insert them into posiociones Map
public AggregateResult[] ventasSemanales = [Select COUNT(Estado__c)Ventas from Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_WEEK group by owner.name ];
public AggregateResult[] = [Select COUNT(Estado__c)Ventas from Leads__c where Estado__c = 'Vendido' and Fecha_Venta__c = THIS_MONTH group by owner.name ];
public List<Posicion> getPositions(){
Map<Id,User> user_map = new Map<Id,User>();
for( User u : users){
user_map.put(u.id,u);
}
Map<Id, Posicion> posiciones = new Map<Id, Posicion>();
for(leads__c c : puntos){
Posicion temp = posiciones.get(c.ownerId);
if(posiciones.get(c.ownerId)==null){ temp = new Posicion() ;}
Integer puntos = integer.valueof(c.puntos__c);
temp.nombre = user_map.get(c.ownerid).name;
temp.puntostotal += puntos;
/*
if (c.Estado__c == 'vendido'){
// i need to insert those values here im pretty new to apex what can i do ??
if (ventasSemanales == null)
temp.VentasSemanales = (integer)ventasSemanales[0].get('Ventas');
else {
temp.VentasSemanales = 0;
}
if (ventasMensuales == null){
temp.VentasMensuales = 0;
}
else{
temp.VentasMensuales = (integer)ventasMensuales[0].get('Ventas');
}
}
*/
posiciones.put(c.ownerid,temp);
}
return posiciones.values();
}
- Cesar Ramirez Vasquez005391619375684564
- May 13, 2014
- Like
- 0
- Continue reading or reply
Drill down from a visual force page to a standard detail page doesn't work
I looked it up on google, and found this examplehttp://stackoverflow.com/questions/11552514/visualforce-page-embedded-in-a-detail-page-that-needs-to-redirect-to-other-page.
I tried, but it doesn't work for me. Here is my controller class, I have omitted other logics.
public with sharing Class FinAccntFilterByTypeController {
private ApexPages.StandardController controller {get; set;}
public String redirectUrl {get; set;}
public FinAccntFilterByTypeController( ApexPages.StandardController controller){
//initialize the stanrdard controller
this.controller = controller;
}
public PageReference doStuffAndRedirect() {
redirectUrl = controller.view().getUrl();
System.debug ('URL '+redirectUrl);
return null;
}
Here is my page, please ignore the variables, basically, I have repeat loop through list and fields, I have a outputLink with onClick to call doStuffAndRedirect, then I have the javascrip part to add
window.top.location.href to redirect. After I added the javascript part, whenever I go to Contact page, without click on outputLink field, it automatically navigates to the redirectUrl. Is there anything wrong with my code?
<apex:page standardController="Contact" id="fapage" extensions="FinAccntFilterByTypeController">
<apex:repeat value="{!availableCategories}" var="category">
<apex:pageBlock title="{!category}" >
<apex:pageBlockTable value="{!finAcctListByCategory[category]}" var="fa" rendered="{!NOT(ISNULL(finAcctListByCategory[category]))}" title="category">
<apex:repeat value="{!fieldListByCategory[category]}" var="field">
<apex:column headerValue="{!fieldLabelMapByCategory[category][field]}" value="{!fa[field]}" rendered="{!field!='Account_Number__c'}"></apex:column>
<apex:column headerValue="{!fieldLabelMapByCategory[category][field]}" rendered="{!(field='Account_Number__c')}">
<apex:outputLink onClick="doStuffAndRedirect">{!fa[field]}
<script type="text/javascript">
window.top.location.href = '{!redirectUrl}';
</script>
</apex:outputLink>
</apex:column>
</apex:repeat>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:repeat>
</apex:page>
- Qin Lu
- May 13, 2014
- Like
- 0
- Continue reading or reply
button to create a new alert, with previous alert info, update one field
So for instance
An Initial Alert is created - Alert 110
I click the Update button on Alert 110 and it clones it (creating Alert 111 and opening an edit of the new alert) I can edit all I want and on save I want Alert 110 to be in the Master Alert field.
So Now if I click Update on Alert 111 (creating Alert 112 and opening an edit of the new alert) I can edit all I want and on Save I want Alert 110 to be in the Master Alert field.
Here is my mess of code Class:
public class CW_alertUpdate{
public final Alerts__c alertID;
public Alerts__c newAlert{get;set;}
public CW_alertUpdate(ApexPages.StandardController controller) {
//gets fields from previous case
alertID = [SELECT Id FROM Alerts__c WHERE Id = :ApexPages.currentPage().getParameters().get('alertID')];
//isDisplayPopUp = true;
//gets fields from pop-up
//this.formFields = (Case)Controller.getRecord();
}
public pageReference autorun(){
//create a new Case
Alerts__c newAlert = new Alerts__c();
// Fill in the values for the new record from previous case
newAlert.Master_Alert_Lookup__c = alertID.Id;
//Insert the new Case record
insert newAlert;
system.debug(newAlert);
PageReference retPage = new PageReference('/' + newAlert.id);
return retPage;
}
}
Functionally it works, BUT it creates one Alert with all the previous alert's info and then creates a 2nd Alert with just the updated Master Alert field. How do I make it work and just create 1 Alert?
Update button:
/a0H/e?retURL={!Alerts__c.Id}&00Ne0000000jigO={!Alerts__c.Incident_Start__c}&00Ne0000000jifu={!Alerts__c.Product__c}&00Ne0000000jigd={!Alerts__c.Team_List__c}&CF00Ne0000000jigi={!Alerts__c.Incident_Manager__c}&CF00Ne0000000jigi_lkid={!Alerts__c.Incident_ManagerId__c}&00Ne0000000jigT={!Alerts__c.Incident_Reported__c}&00Ne0000000jifk={!Alerts__c.Subject__c}&CF00Ne0000000jigs={!Alerts__c.Account_Name__c}&CF00Ne0000000jigs_lkid={!Alerts__c.Account_NameId__c}&
00Ne0000000jifz={!Alerts__c.Customer_Impact__c}&00Ne0000000jig4={!Alerts__c.Completed_Actions__c}&00Ne0000000jig9={!Alerts__c.Next_Actions__c}&CF00Ne0000000jigE={!Alerts__c.Incident_Ticket_Number__c}&CF00Ne0000000jigE_lkid={!Alerts__c.Incident_Ticket_NumberId__c}&00Ne0000000dZZQ={!Alerts__c.CGM_P1_AMERICAS_MANNED__c}&00Ne0000000dZZL={!Alerts__c.CGM_P1_APD_MANNED__c}&00Ne0000000dZZH={!Alerts__c.CGM_P1_Command__c}&00Ne0000000dZZG={!Alerts__c.CGM_P1_EAME_MANNED__c}&saveURL=/apex/CW_AlertUpdate?alertID={!Alerts__c.Id}
- Staci
- May 12, 2014
- Like
- 0
- Continue reading or reply
Dynamic retrieval of fields of any sobject in vf page..
from this we can retrieve all the fields but of account object only but i want retrieve all the fields of any sobject.
I had accessed the sobjects dynamically by this---
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
List<SelectOption> options = new List<SelectOption>();
list<String> fieldlabel=new list<String>();
GlobalDescribeMap.put(fieldlabel,gd);
//Schema.getGlobalDescribe();
for(Schema.SObjectType f : gd)
{
if(f.getDescribe().isCreateable() && (!f.getDescribe().CustomSetting) && (f.getDescribe().keyPrefix!=null ||f.getDescribe().keyPrefix!='') && f.getDescribe().isUpdateable() && f.getDescribe().isQueryable() && f.getDescribe().isAccessible() && f.getDescribe().isUndeletable())
{
options.add(new SelectOption(f.getDescribe().getLabel(),f.getDescribe().getLabel()));
fieldlabel.add(f.getDescribe().getLabel());
// system.debug('@@@'+fieldlabel);
}
}
return options;
but not able to dynamically retrieve the fields of any sobject .. please help
- hemant rana
- May 09, 2014
- Like
- 0
- Continue reading or reply
Send callout onInstall package
Is it possible to send an HTTPrequest at package installation ? Every time an Exception is raised : You have uncommitted work pending. Please commit or rollback before calling. My goal is to notify my server that someone installed the package to setup the application.
Here is a code example :
global void onInstall(InstallContext context) { try { Http h = new Http(); String endpoint = 'myURL'; // Send the request HttpRequest req = new HttpRequest(); req.setEndpoint(endpoint); req.setMethod('POST'); req.setbody('MyData'); HttpResponse res = h.send(req); } catch (Exception ex) { Messaging.SingleEmailMessage emailTobeSent = new Messaging.SingleEmailMessage(); list<String> listEmailMembers = new list<String>(); listEmailMembers.add('myEmail@adress.com'); emailTobeSent.setToAddresses(listEmailMembers); emailTobeSent.setSubject('Post install exception'); emailTobeSent.setHtmlBody('Message : ' + ex.getMessage() + 'Line no : ' + ex.getLineNumber() + ' getStackTraceString ' + ex.getStackTraceString() + '' + ex.getCause()); Messaging.SendEmailResult [] r1 = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {emailTobeSent}); } }
Any Idea ? Thanks !
Pierre-Marie
- Pierre Marie Dartus
- May 04, 2014
- Like
- 0
- Continue reading or reply
How to build map with marker to get geolocation.
I want to place the geolocation marker on map and allow the user to change the location by dragging around the marker (if its mispalced).
- swaarnimdev
- May 02, 2014
- Like
- 0
- Continue reading or reply
Code to reference a standard Object dynamically
I would like to know if there is any mechanism to check if this such an sObject exist and based on that retrieve its fields dynamically. Essentially we would want the same package to work when the sObject ChatterConversationMessage is available or not.
- Pranavaditya Kannojoo
- May 02, 2014
- Like
- 0
- Continue reading or reply
Salesforce Sites - Authorization Required
In order to eliminate this error, I've:
created a "Hello World" page that accesses no controllers or objects to eliminate Object permissions from the problem,
verified that the Site is active,
gone to the site and clicked "Public Access Settings" and configured the User Profile that comes up to be able to access the page from any IP range (000.000.000.000 to 255.255.255.255), given it every System Permission possible, and not assigned any login hours, which I assume allows the site's User Profile to access the page at any time.
I can't think of anything else to do! Thanks in advance for your help.
- Newport
- May 01, 2014
- Like
- 0
- Continue reading or reply
Check 2 field(date time) in object <=1
I have 2 field in SOSL . How we check substract from to_date and from_date <=1 days
- Huy Nguyen
- December 23, 2014
- Like
- 0
- Continue reading or reply
Why Minutes of Business Hours are not Calculated in Apex Trigger?
trigger BusinessHrs on Customer__c (before insert, before update)
{
Long Diff1;
Long Diff2;
for(Customer__c c1: trigger.new)
{
BusinessHours stdBusinessHours = [select id from businesshours where id = '01mi0000000aAVI'];
DateTime d1 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
DateTime d2 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
d1=c1.Startdate__c;
d2=c1.EndDate__c;
Diff1=BusinessHours.diff('01mi0000000aAVI',d1, d2) ;
c1.Business_Hour1__c=(Diff1/(1*60*60*1000));
DateTime d3=DateTime.newInstanceGmt((d1.dateGmt()), (d1.timeGmt()) );
DateTime d4=DateTime.newInstanceGmt((d2.dateGmt() ), (d2.timeGmt() ) );
Diff2=BusinessHours.diff('01mi0000000aAVI',d1, d2) ;
c1.Business_Hour2__c=(Diff2/(1*60*60*1000)); } } }
In Both Business_Hour1__c,Business_Hour2__c the number field(decimal 2 places) have no decimal value... Is something wrong in : Diff2=BusinessHours.diff('01mi0000000aAVI',d1, d2) ;
c1.Business_Hour2__c=(Diff2/(1*60*60*1000));
- Arvind Jain
- December 23, 2014
- Like
- 0
- Continue reading or reply
Please help! First error: Too many query rows: 50001 in my Batch Job
public class ContactCampaignCount implements Database.Batchable<sObject>{ Integer subtotalUpdCst_actual = 0; private string ctc_types; private string cpgn_types; public ContactCampaignCount(String ctc_type, string cpgn_type){ this.ctc_types = ctc_type; this.cpgn_types = cpgn_type; } public Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id,Name,Test1__c, Test2__c, Test3__c, Test4__c, Test5__c FROM Contact WHERE RecordTypeId = \'' + ctc_types +'\''; return Database.getQueryLocator(query); } public void execute(Database.BatchableContext BC, List<Contact> scope) { List <Campaign> ytd_total_cmpgn = new List <Campaign>(); List <Campaign> ytd_email_cmpgn = new List <Campaign>(); List <Campaign> mth_total_cmpgn = new List <Campaign>(); List <Campaign> mth_email_cmpgn = new List <Campaign>(); List <CampaignMember> ytd_total_cpgn_mb = new List<CampaignMember>(); List <CampaignMember> ytd_email_cpgn_mb = new List<CampaignMember>(); List <CampaignMember> mth_total_cpgn_mb = new List<CampaignMember>(); List <CampaignMember> mth_email_cpgn_mb = new List<CampaignMember>(); List<Contact> updateCtcs = new List<Contact>(); ytd_total_cmpgn = [SELECT ID, Campaign_Effective_Start_Date__c, Year__c, Channel__c FROM Campaign WHERE Year__c =: String.valueOf(System.today().year()) and RecordTypeId =: cpgn_types]; ytd_email_cmpgn = [SELECT ID, Campaign_Effective_Start_Date__c, Year__c, Channel__c FROM Campaign WHERE Year__c =: String.valueOf(System.today().year()) and Channel__c = 'Email' and RecordTypeId =: cpgn_types]; mth_total_cmpgn = [SELECT ID, Campaign_Effective_Start_Date__c, Year__c, Channel__c FROM Campaign WHERE Campaign_Effective_Start_Date__c >=: System.today().addMonths(-12) and Campaign_Effective_Start_Date__c <=: System.today() and RecordTypeId =: cpgn_types]; mth_email_cmpgn = [SELECT ID, Campaign_Effective_Start_Date__c, Year__c, Channel__c FROM Campaign WHERE Campaign_Effective_Start_Date__c >=: System.today().addMonths(-12) and Campaign_Effective_Start_Date__c <=: System.today() and Channel__c = 'Email' and RecordTypeId =: cpgn_types]; ytd_total_cpgn_mb = [SELECT Id, ContactId, CampaignId From CampaignMember where CampaignId in :ytd_total_cmpgn]; ytd_email_cpgn_mb = [SELECT Id, ContactId, CampaignId From CampaignMember where CampaignId in :ytd_email_cmpgn]; mth_total_cpgn_mb = [SELECT Id, ContactId, CampaignId From CampaignMember where CampaignId in :mth_total_cmpgn]; mth_email_cpgn_mb = [SELECT Id, ContactId, CampaignId From CampaignMember where CampaignId in :mth_email_cmpgn]; for(Contact ctc : scope){ Integer ytd_total_Campaign = 0; Integer ytd_total_emailCampaign = 0; Integer mth_total_Campaign = 0; Integer mth_emailCampaign = 0; Date last_campaign_date; for(CampaignMember ytd_total_cmb : ytd_total_cpgn_mb){ if(ytd_total_cmb.ContactId == ctc.Id){ ytd_total_Campaign += 1; } } for(CampaignMember ytd_total_eml_cmb : ytd_email_cpgn_mb){ if(ytd_total_eml_cmb.ContactId == ctc.Id){ ytd_total_emailCampaign += 1; } } for(CampaignMember mth_total_cmb : mth_total_cpgn_mb){ if(mth_total_cmb.ContactId == ctc.Id){ mth_total_Campaign += 1; for(Campaign cm: mth_total_cmpgn){ if(cm.Id == mth_total_cmb.CampaignId){ if(last_campaign_date == null || last_campaign_date < cm.Campaign_Effective_Start_Date__c){ last_campaign_date = cm.Campaign_Effective_Start_Date__c; } } } } } for(CampaignMember mth_total_eml_cmb : mth_email_cpgn_mb){ if(mth_total_eml_cmb.ContactId == ctc.Id){ mth_emailCampaign += 1; } } if(ctc.Test5__c == null || ctc.Test5__c < last_campaign_date){ ctc.Test5__c = last_campaign_date; } ctc.Test1__c = ytd_total_Campaign; ctc.Test2__c = ytd_total_emailCampaign; ctc.Test3__c = mth_total_Campaign; ctc.Test4__c = mth_emailCampaign; updateCtcs.add(ctc); } statics.enableContactTrigger = false; List<Database.SaveResult> r1 = Database.update(updateCtcs, false); for( Database.Saveresult r : r1 ){ if ( r.isSuccess()){ subtotalUpdCst_actual = subtotalUpdCst_actual + 1; System.debug('Database.Saveresult >> ' + r); }else{ for ( Database.Error e : r.getErrors() ){ System.debug ( updateCtcs + '\n' + e.getStatusCode() + ': ' + e.getMessage()); } } } } public void finish(Database.BatchableContext BC) { } }
thanks
- hylim1215
- December 16, 2014
- Like
- 0
- Continue reading or reply
VF component as Related List in a standard Page Layout
Can I add a VF component as Related List in a standard Page Layout?
Thanks in Advance,
Pramitha
- Pramitha Nair 4
- December 16, 2014
- Like
- 0
- Continue reading or reply
System.NullPointerException: Attempt to de-reference a null object
Here is my below code :
/**
@description Class for the Redirect With Variables page.
Function: Handles the controller logic for the RedirectWithVariables page.
*/
public with sharing class RedirectWithVariablesController {
/*
* Method name: redirectUser
* @description Redirects the user to the given object + parameters
* @return PageReference The page the user needs to be redirect to.
*/
public pagereference prePopulateFields(){
//Get object name
String strObject = System.currentPageReference().getParameters().get('object');
string params = '';
Integer a = 0;
map<String,String> fields = getFieldsIdsMap(strObject);
string regName = System.currentPageReference().getParameters().get('Registration__c');
string regId = System.currentPageReference().getParameters().get('ID_Registration__v');
string retURL = System.currentPageReference().getParameters().get('retURL');
string stakeholerName = System.currentPageReference().getParameters().get('Stakeholder__c');
string stakeholerId = System.currentPageReference().getParameters().get('ID_Stakeholder__v');
for(string k: fields.keySet()){
//ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, k+''));
//System.debug('label: ' + a + ': ' + k);
//a++;
if(k == 'Registration'){
params += fields.get(k) + '=' + regName + '&' + fields.get(k) + '_lkid=' + regId + '&';
}
if(k == 'Stakeholder'){
params += fields.get(k) + '=' + stakeholerName + '&' + fields.get(k) + '_lkid=' + stakeholerId+ '&';
}
}
//for(string p:fields.values()){
// params += p+'=Test Value '+a+'&';
// a++;
//}
PageReference p = new PageReference('/' +
Schema.getGlobalDescribe().get(strObject).getDescribe().getKeyPrefix() + '/e?'+
params+'nooverride=1&retURL=' + retURL);
p.setRedirect(true);
return p;
}
public map<String, String> getFieldsIdsMap(String sObjectName) {
map<String, String> label_IdMap = new map<String, String>();
if(null!= sObjectName && sObjectName.trim() != '') {
//if(!isObjectValid(sObjectName)){
// return null;
//}
PageReference p = new PageReference('/' +
Schema.getGlobalDescribe().get(sObjectName).getDescribe().getKeyPrefix()
+ '/e?nooverride=1'); // this one return null in the url
String html = '';
if(!Test.isRunningTest()) {
html = p.getContent().toString();
} else {
//html = '';
html = '<label for="CF00NK0000000Yt1b"><span class="requiredMark">*</span>Name</label>';
}
Matcher m = Pattern.compile('<label for="(.*?)">(<span class="requiredMark">\\*</span>)?(.*?)</label>').
matcher(html);
while(m.find()) {
String label = m.group(3);
String id = m.group(1);
label_IdMap.put(label, id);
}
}
return label_IdMap;
}
}
controller:
public class DisclosureNewOverrideController{
public String retURL {get;set;}
public DisclosureNewOverrideController(ApexPages.standardController sc){
retURL = ApexPages.CurrentPage().GetParameters().Get('retURL');
system.debug('nghiatran retURL ' + retURL + ' ' + retURL.substring(1));
//ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This: ' + retURL));
//string objectName = getObjectName(retURL);
string objectName = CommonUtils.getObjectName(retURL.substring(1));
if(objectName == 'Disclosure_Claim_for_Payment__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Disclosure/Claim for Payment is created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a New Disclosure, please navigate to the Stakeholder record -> Disclosure Obligation record.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a New Claim for Payment, please navigate to the Stakeholder record -> Eligible Claim for Payment record.'));
}else if(objectName == 'Disclosure_Obligation__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Disclosure Obligation is created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create a new Disclosure Obligation, please navigate to the Stakeholder record.'));
}else if(objectName == 'HP_Trim_Container__c'){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This button has been disabled to help ensure the correct Donor TRIM Containers are created.'));
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'To create the Donor TRIM Containers, please navigate to the \'All\' list view and click on \'Generate Donor TRIM Containers.\''));
}
}
this is 2 url when create new disclosure :
not ok https://c.cs6.visual.force.com/apex/DisclosureObligationNewOverride?save_new=1&sfdc.override=1
the account name :Mr Madhvi Lata & Visapaa
ok :https://c.cs6.visual.force.com/apex/DisclosureObligationNewOverride?CF00NN0000000MBK7=Aegis+Consulting+Group+Pty+Ltd&CF00NN0000000MBK7_lkid=001N000000M1lpg&scontrolCaching=1&retURL=%2F001N000000M1lpg&sfdc.override=1
the account name :Aegis Consulting Group Pty Ltd
- Huy Nguyen
- December 16, 2014
- Like
- 0
- Continue reading or reply
Can I traverse multiple levels of lookup relationships to get values in a pageBlockTable column?
<apex:column headerValue="{!$Label.ContractManagementColumnCustName}" value="{!waitlistItem.Contract__r.Contact__r.Name}"/>Error: Invalid field Contact__r for SObject Contract
I'm sure that my setup of objects is correct, so the relationship on object Contract__c exists. What am I doing wrong?
- Mario Hammer
- December 05, 2014
- Like
- 0
- Continue reading or reply
In how many ways can we schedule a batch apex?
Thanks in advance
- naresh
- December 05, 2014
- Like
- 0
- Continue reading or reply
Trigger to create parent and child records from set of one object records
I want to separate the data into two records one is parent object "order" and child object "order item"
order consists of fields : customer po,account name, customer id
order item consists of fields : nicomatic pin,quantity ordered
Trigger:
trigger orderitem on order_batch__c (after insert , after update) { Set<Id> Ids= new Set<Id>(); for (order_batch__c member : Trigger.new){ Ids.add(member.Id); } List<order_batch__c> memberList = new List<order_batch__c>([Select Id,Or_customer_PO_Number__c,Or_Nicomatic_p_n__c, Or_clientpn__c,Quantity_Ordered__c,Requested_Date__c,Discount__c,Unit_price__c From order_batch__c where Id in :Ids]); for(order_batch__c temp : memberList ) { order__c o= new order__c(); o.Customer_Po__c=o=temp.Or_customer_PO_Number__c; insert o; Order_Item__c member2 = new Order_Item__c(); // mermber2.Order__c=temp.Or_customer_PO_Number__c; member2.Name = temp.Or_Nicomatic_p_n__c; member2.Client_PN__c = temp.Or_clientpn__c; member2.Quantity__c = temp.Quantity_Ordered__c; member2.Request_Date__c = temp.Requested_Date__c; member2.Discount__c = temp.Discount__c; member2.Price__c = temp.Unit_price__c; insert member2; } }My requirement is to separate records in parent and child records .when ever there is an update in order batch records it has to update accordingly parent or child.
I am getting error in the above trigger .can any body help me regarding this
- d.tejdeep@nicomatic.in
- December 04, 2014
- Like
- 0
- Continue reading or reply
Getting Error in Test Class
I'm getting Error in Test Class like below :
System.DmlException: Upsert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Auto_generated: execution of AfterInsert
caused by: System.NullPointerException: Attempt to de-reference a null object
Test Class:
@isTest
private class Emailtocase_TestClass
{
static TestMethod void Emailtocase_TestClass()
{
Test.StartTest();
Case c= new Case();
c.Subject = 'Testing';
//insert c;
Contact con = new Contact();
con.LastName = 'Testing Contact';
con.Email = 'test1@gmail.com';
insert con;
Contact c1 = [Select id,LastName,Email from Contact where Email = 'test1@gmail.com'];
Case ca = new Case();
ca.Id = c.Id;
ca.Subject='Welcome';
ca.Status = 'email';
ca.Origin='New';
ca.ContactId = c1.Id;
ca.SuppliedEmail= 'test1@gmail.com';
ca.Task_Taken__c=false;
ca.OwnerId = '00G90000002Gb76';
upsert ca;
Account a = new Account();
a.Domain_Name__c = 'gmail.com';
a.Name='Testing Account';
insert a;
Account a1 = [Select id,Domain_Name__c,Name,Phone from Account where Domain_Name__c = 'gmail.com'];
Case cas1= new Case();
cas1.Subject = 'Testing';
cas1.SuppliedEmail= 'test@gmail.com';
List<contact> lstcon =new List<contact>();
contact con1=new contact(lastname='sas',Email = cas1.SuppliedEmail,AccountId=a1.Id);
lstcon.add(con1);
insert lstcon;
Case ca1 = new Case();
ca1.Id = cas1.Id;
ca1.Subject='Welcome';
ca1.Status = 'email';
ca1.Origin='New';
ca1.AccountId=a1.Id;
ca1.Task_Taken__c=false;
ca1.OwnerId = '00G90000002Gb76';
ca.ContactId = lstcon[0].Id;
Upsert ca1;// Here I'm getting error line is -Class.Emailtocase_TestClass.Emailtocase_TestClass: line 57, column 1
Test.StopTest();
}
}
The above covers 54% so how to solve this error.
Thanks
- dev_sfdc1
- December 04, 2014
- Like
- 0
- Continue reading or reply
Need Help for test for this trigger
i need to write test class for this trigger. Please give some idea
trigger accountTestTrggr on Account (before insert,before update) {
List<Account> accountsWithContacts = [select id, name,(select id,firstname, lastname,Description from Contacts) from Account where Id IN :Trigger.newMap.keySet()];
List<Contact> contactsToUpdate = new List<Contact>{};
for(Account a: accountsWithContacts){
for(Contact c: a.Contacts){
c.Description=c.firstname+c.lastname;
contactsToUpdate.add(c);
}
}
update contactsToUpdate;
}
- deepak kumar 13
- December 04, 2014
- Like
- 0
- Continue reading or reply
Email notification when an attachment is added to a case-Urgent
- Praveen Jha
- December 04, 2014
- Like
- 0
- Continue reading or reply
How to get photoURL from FeedItem object?
How to get photoURL from FeedItem object?
i have tried Createdby.smallphotourl but it's not working for FeedItem object...
- kannapapi
- December 04, 2014
- Like
- 0
- Continue reading or reply
How Do I enable REST API for organization.
I am trying to use REST API for SalesForce for that I need to Enable REST API.
for that I went through Setup -> Manage Users -> Permission Sets -> Create New, but I am seeing Insufficient Privileges page.
I am using 30 days trial version.
How can I enable REST API ?
Thanks
- Pratik Sathaye 9
- December 03, 2014
- Like
- 0
- Continue reading or reply
Ideas Regarding Trigger
for (feeditem F : Trigger.new)
{
if(Trigger.isInsert)
{
feeditem EE = [Select body,parentid from feeditem where Id = :F.Id];
opportunity op=[select id,ownerid from opportunity where id=:EE.parentid] ;
User U= [select id,Email,Name from user where id =:op.ownerid ];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {U.email};
mail.setToAddresses(toAddresses);
mail.setSubject('Record Feed Notification to record owner' );
mail.setPlainTextBody('Hello,' + '\n\n' +'Please consider the following feed'+' '+'\n\n'+'Subject :'+F.body );
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
In this parentid will of any thing like accound id ,opportunity id,quote id,userid--- i need to send email to the record owner when feed is posted .how i can write the code as global way (or) we need to write it seperately (if account id,if oppid,if quoteid).it woud be great it would have some sample code.
- d.tejdeep@nicomatic.in
- April 30, 2014
- Like
- 1
- Continue reading or reply
Why Schema.getGlobalDescribe().get(ObjectName) not returning SObjectType?
I am working on Metadata API to develop Webservices for Custom Object management.
Here is part of the code, which accepts a string of object name and gets all the fileds. The line-2 of the code is not working.
So I had to get all the objects in Schema, looping through them and get matching object type of what I require.
But is there an efficient way of doing the same? Please help me.
==================
String sObjectName='MyCustomObject__c';
//Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjectName); //This is returning null
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
Schema.SObjectType objToken;
for(Schema.SObjectType obj: gd){
if(Obj.getDescribe().getName().toLowerCase()==sObjectName.toLowerCase()){
objToken=obj;
break;
}
}
Schema.DescribeSObjectResult typedescription = objToken.getDescribe();
//...Now I can continue working with my object field changes
- Bhaskar2013
- April 01, 2013
- Like
- 2
- Continue reading or reply
Why you might get OP_WITH_INVALID_USER_TYPE_EXCEPTION from a trigger
Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.
We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status. This was done to fulfill a client's requirement to audit all Chatter activity.
The trigger worked fine, until one day the client signed up some Chatter Free users. When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.
We scratched our collective heads for awhile. After all, Apex triggers run in "system mode," right? That is supposed to mean that "object and field-level permissions of the current user are ignored." And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.
The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner. We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.
So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.
- Glenn Weinstein
- April 05, 2012
- Like
- 36
- Continue reading or reply