• David81
  • NEWBIE
  • 470 Points
  • Member since 2010

  • Chatter
    Feed
  • 18
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 181
    Replies

Hi Guys...!

Hpoe all are doing well...

 

I have small Problem, 

I'm updateing the Object record in Class.

like below, I'm using sObject Instance to Update the record.

I'm assigning like below but Error was throwing.

sObj.Phone_No__c = '9999999999'; 

so i used like this, but same result.......... Error

sObj.get('Phone_No__c') = '9999999999';

update sObj;

 

And I'm getting Error like

" Field expression not allowed for generic SObject ".

 

 

 

 Now How can i update that perticular Record Phone No using sObject instance. 

 

and when I'm using Id then  no Error was throwing,

sObj.Id 



then No error

Hey all.

I feel like I've asked this question before, but I cannot find the answer anywhere :P

So I'm writting a service that can take a block of XML to update objects. Each XML element has a string that contains type type of object it represends and the ID of the already existing object. For example

<Object type="Contact" id="a0FU00000008h9G">
    <field id="phone">5555555555</field>
</Object>

 

 While iterating over this list of XML items, how can I create a sObject of the type specified in the type field, and set the id as well? I can get most of the way there, doing something like this...

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SobjectType oType;

//reader.getAttributeValueAt(0) will evaluate to the object type in the XML
oType = gd.get(reader.getAttributeValueAt(0));

//If the Id is specified I need to create that type of sObject and set the ID, so I can perform an update.
//If not, I just need to create a new instance of that type of object.

if(reader.getAttributeLocalName(1) == 'id')
{
	//this fails because it says id is an unknown attribute.
	//reader.getAttributeValueAt(1) will evaluate to the id of the existing object
	thisObject= oType.newSObject(id=reader.getAttributeValueAt(1));
}
else
{
	thisObject = oType.newSObject();
}

 


 I can create a NEW instance of the type of sObject i want, but create one with the Id set so I can update it explodes. It says 

'Variable does not exist: id'

Any thoughts? Any kind of help would be much appreciated. Thanks!
 

Hi,

 

I have a controlling picklist and it is setup when I select 'ABC' the other picklist that is controlled goes blank and when you view the data the field is blank.  But if you select 'EFG' the controlled field allows users to choose values, lets say 'xyz' for this example.

 

Now I want to change certain records that contain 'EFG' and update the value to 'ABC' with the DataLoader.  I did this in test but the controlled picklist still contained the value 'xyz'.

 

I tried setting the controlled field in the CSV file to NULL, Blank, None and one space and none of thease values work when I upload the data via the DataLoader.  In fact if upload NULL the value becomes null in the field or if I upload None the value is None!


How can I get the controlled field to be blank?  What value to I have to pu in the CVS file to make this work.

 

Thanks in advanced for your support.

 

Hi there,

 

I'm trying to compare a field in an object which relates to another object which has the same API name.

This results in a FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object.

 

I can print the information successfully, the probelm arrises when I do string1.equals(string2); (where String 2 is the field name in an object AND an object API name.) For some reason Apex decides I want the object name instead of the field name, which is weird since I'm defining "object.field" in my .equals()

 

Is there a way to select by alias in SOQL or set up a new instance of String (String myString = new String();) ?

Hi, I'm having a similar issue with using a Map<id,Product2>

 

The weird thing is that it works perfectly in sandbox but not in development... wtf apex?

 

I'm not going to post the entire trigger code here, as it's not necessary, I have narrowed the issue down to the Map .get() method:

 

24 System.Debug('Keyset: '+pMap.keyset());
25 System.Debug('Product: '+pMap.get('01t50000001LcjyAAC').name);
26 Product2 testp;
27 if (Trigger.isInsert){
28 for (Product_Lot__c pl: Trigger.new){
29           System.Debug('Product__c: '+pl.Product__c);
30           testp = pMap.get(pl.Product__c); <--- Always Returns Null
31           testp.Inventory_on_Hand__c += pl.Quantity__c;    <--- Causes a null pointer exception
32      }

 

 

Results of Execute Anonymous:

 

11:33:25.101|USER_DEBUG|[24]|DEBUG|Keyset: {01t50000001LcjyAAC}

11:33:25.101|METHOD_EXIT|[24]|System.debug(ANY)

11:33:25.101|METHOD_ENTRY|[25]|System.debug(ANY)

11:33:25.101|METHOD_ENTRY|[25]|MAP.values()

11:33:25.101|METHOD_EXIT|[25]|MAP.values()

11:33:25.102|USER_DEBUG|[25]|DEBUG|Product: 2-Mercaptoethanol

11:33:25.102|METHOD_EXIT|[25]|System.debug(ANY)

11:33:25.102|METHOD_ENTRY|[29]|System.debug(ANY)

11:33:25.102|USER_DEBUG|[29]|DEBUG|Product__c: 01t50000001LcjyAAC

11:33:25.102|METHOD_EXIT|[29]|System.debug(ANY)

11:33:25.102|METHOD_ENTRY|[30]|MAP.get(ANY)

11:33:25.102|METHOD_EXIT|[30]|MAP.get(ANY)

11:33:25.102|EXCEPTION_THROWN|[31]|System.NullPointerException: Attempt to de-reference a null object

11:33:25.102|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

Trigger.Product_Lot_Trigger: line 31, column 4

 

So if you look at the highlighted lines (DEBUG outputs), you can plainly see that the map contains a valid ID, and the

hard-coded get() on line 25 returns the correct object and displays the correct name, so the Value is correct too.

Also you can see that the field Product__c (on line 29) exactly matches the key that is in the Map.

But line 30 is still returning NULL!!!!

 

I'm just starting to get angry at this point, because this works 100% correctly in the Sandbox.  Can anyone help?

Hello, I have a data table I've created on a Visual Force page. This table lists out all my records I've created for a custom Sales object. I was asked to gather the total amount cummulated for each record and display it on the top row (not counting the Header Values). I have come up with the total amount, but I am having trouble getting it to display the way I want.  

 

Here's an example of the layout I need.  I want the Total amount to display directly underneath the header row.

Total   Employee   Amount

$350    Mike            $50

           Steve           $100

           Perry           $150

           Johnson      $50

 

However, here is what I am getting using the following code:

 <apex:column headerValue="Total" width="50">
        <apex:facet name="header"><apex:outputPanel >
        <apex:outputText value="${!Total['sum']}" /></apex:outputPanel></apex:facet>
</apex:column>

 This code takes my header value "Total" and replaces it with the numeric total, so I am seeing:

 

$350    Employee   Amount

            Mike            $50

            Steve          $100

            Perry           $150

           Johnson       $50

 

I also decided to create my Headers using standard <TH> tags, rather than the <column headerValue="">, and then setup my dataTable without column headers.  However, this resulted in the following layout:

 

Total   Employee   Amount

$350

           Mike              $50     

           Steve            $100

           Perry            $150

           Johnson       $50

 

While the total amount is directly underneath the "Total" header, the other records have jumped down a line. Is there a way to get this total amount to display in my first layout?

 

Thanks!

Mike

Hi,

 

I'm creating a VF page that should be displayed in the case object.

 

I would like to retrieve information about the account  in which that case resides and pass it on to the apex controller in that page.

 

For instance let's say my controller looks like this

 

public class MyController {

      private final Account account;

      public MyController() {
            account = [select id, name, site from Account where id =
                       :ApexPages.currentPage().getParameters().get('id')];
      }

      public Account getAccount() {
            return account;
      }

      public PageReference save() {
            update account;
            return null;
      }
}

Becaus of the page being diplayed in the case, I can't querry for the Account ID this way

:ApexPages.currentPage().getParameters().get('id')

Since the id is not present in the case's url.

 

How can I pass the account ID from the case to the apex controller?

 

Any help will be much appreciated.

 

Thanks

 

Tzuvy

 

  • March 09, 2011
  • Like
  • 0

Is it possible to have an email service apex that will update an existing record in a custom object? I'm not a coder but would really appreciate it if someone can guide me to a similar code I can use to develop this functionality. Thanks!

  • January 11, 2011
  • Like
  • 0

 

trigger case1 on Case (after insert)

 {

List<message__c> l=new list<message__c>();

if(trigger.isinsert)

{

for(case c:trigger.new)

{
system.debug('The value in the case variable c is'+c);if(c.fine__c)

{
Message__c a=new Message__c();

//a.accountid__c=c.accountid;

a.name__c=c.casenumber;

System.debug('The value in the variable a.name__c is'+a.name__c);

//a.name__c=c.contact;

a.Name='Sweet and Sour';

System.debug('The value in the variable a.name explixitly has been assigned is'+a.name);

l.add(a);

}

System.debug('The value in the List l is explicitly has been assigned is'+L);

}

}

insert(l);

}


Guys, I am new to salesforce and to this community.I am working on the problem.I have a trigger on the case object and a check boxfield on the case .If somebody checks that box then another object by the name of message should be created and some value from the case object should be passed on to the fields on the message object. For example,this value a.Name='Sweet and Sour'; has been harcoded becasue I was getting some error.a.name__c=c.casenumber;
Above I have assigned values from casenumber field on the case to the field name__c on the message field.
Firstly,Can I do this without having any relationship between the case and the message object.?Secondly,It is adding all the values to the message list as I can see in the debug log.However,it is not not inserting record with the values in the message custome object.Thirdly,Help me in correcting it so that it can insert record in the message object.


Please help

Thanks,

Trick

 

  • January 10, 2011
  • Like
  • 0

I've been searching the sfdc help pages and these boards for a few days now, and I cant seem to find a discussion on it.

 

I want to create a Date field that can only be editable one time, after that one edit I want it to become read only. Is this possible?

  • May 19, 2010
  • Like
  • 0
Hi, I'm making a test Apex class that checks against the current user profile. The problem is that there won't be enough code coverage if the user running the test is a system administrator. Is it possible to write apex code in the test class that logs in as a different user for the test, and it's still possible to run the test as a system administrator? Please help, thanks.

Hello. I am working on setting up a web-to-lead form & working in some basic JavaScript validation into the form so we can make sure we're getting the right data into Salesforce. The issue I'm facing is the ID/variable name of my one custom field begins w/ a numeral & JavaScript only accepts variables that begin w/ letters. Is there any way to change the ID of my custom field so my JavaScript validation can work? Or is there a JavaScript work-around someone can recommend?

 

Thanks!

Hi all,

 

I'm attempting to call a class from a trigger that crabs the name of an object based on an Id:

 

Trigger:

 

trigger woJctUpdate on woJct__c (before insert, before update) {
	
	List<woJct__c> newj = (Trigger.old != null) ? Trigger.old : Trigger.new;
	workOrderUtils.theWoJct(newj);
}

 Class:

 

public with sharing class workOrderUtils {

public static List <woJct__c> woJcts = new List<woJct__c>();

public static string getNameById(string id) {

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Map<String,String> keyPrefixMap = new Map<String,String>{};
Set<String> keyPrefixSet = gd.keySet();
for(String sObj : keyPrefixSet){
Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe();
String tempName = r.getName();
String tempPrefix = r.getKeyPrefix();
keyPrefixMap.put(tempPrefix,tempName);
}

string tPrefix = id.subString(0,3);
string objectName = keyPrefixMap.get(tPrefix);
System.debug('objectName:::::' + objectName);

sObject retObject = Database.query(
' SELECT id, name' +
' FROM ' + objectName +
' WHERE id=\'' + id + '\'');


return (string)retObject.get('name');
}

public static void theWoJct(List<woJct__c> objs) {
for (woJct__c woJct : objs) {
if (woJct.relatedToId__c != null) {
woJct.relatedToName__c = getNameById(woJct.relatedToId__c); /<----- This is 33, 8
woJcts.add(woJct);
}
}
if (woJcts.size() > 0) {
update woJcts;
}
}
}

 But when a save a woJct__c it throws me an error:

 

Error:Apex trigger woJctUpdate caused an unexpected exception, contact your administrator: woJctUpdate: execution of BeforeUpdate caused by: System.Exception: Record is read-only: Class.workOrderUtils.theWoJct: line 33, column 8

 

I've tried all kinds of stuff... I can't figure it out... Any help would be great!

 

Thanks.

JNH

 

 

  • April 29, 2010
  • Like
  • 0

Hi,

I am very new to salesforce.I installed the Salesforce International Mapping using Google maps
It works fine for accounts and contacts.I want to reuse this for a custom object Sites.

I understand that using the Component GoogleMapsInternational,the pages for account and contact are created.
I tried to reuse this component and create a page for Sites as shown below:

 

 

<apex:page standardController="Sites__c">

 

<c:GoogleMapsInternational iconColour="#8370C2"

        address="{!Sites.Address__c} "

 />

 

</apex:page>

                                                                    

 

 

 

But i get the error

Error: Unknown property 'Sites__cStandardController.Sites'


Please help.

  • April 29, 2010
  • Like
  • 0

I'm working on a replacement for a home page dashboard that does not require a refresh every time one of our managers wants a picture of open cases in our org.  One of the issues I always hit, with Apex, and also with validation, workflow rules, etc, is properly detecting if a case is queue owned.  Is there a way to globally determine if a case is queue owned without having to rely on a formula that you need to update for every time a queue is added to the org?

Still learning the ropes here and probably have some very ill formed code - so, any help/advice is greatly appreciated.

 

Here is the scenario of what I am trying to accomplish:

 

We have two custom objects (related via lookup field on Essay object):  Applications & Essays.  I have created a custom field on the Applications object called XEssays_On_File.  When an Essay record is added/updated, I would like the XEssays_On_File field to get updated with the number of related Essay Records. (Can't use rollup fields as this is not a master-detail relationship)

 

I have drafted the following code - which works for single situations - but fails mercilessly in bulk update:

 

trigger CountRelatedEssays on TargetX_SRMb__Essay__c (after insert, after update) {

        TargetX_SRMb__Essay__c [] ess = Trigger.new;
        String appid = null;
        appid = ess[0].TargetX_SRMb__Application__c;
       
        Integer i = [select count() from TargetX_SRMb__Essay__c where TargetX_SRMb__Application__c =     :appid];
       
        TargetX_SRMb__Application__c [] app =[select id, XEssays_On_File__c from TargetX_SRMb__Application__c where id = :appid];

        app[0].XEssays_On_File__c = i;   
       
        update app[0];
       

}

 

I would also like this to fire and update on Delete as well.

 

Thanks in advance for any help you can provide!

For example, using today, can I find the number of days in the month prior to today.

 

I can find the previous month MONTH(Today()) -1, but what is the last day of that month?

 

Ideas on how I can do this?

Hello folks,

 

I'm just about to pull my hair out on this one and I'm hoping someone out there can help me out. I have a few queries being used to populate a VF table that just aren't adding up, although I think they should be.

 

The two variables you will see are repIds (a List of User Ids) and firstOfMonth (a Date that corresponds to the 1st day of the current month.

 

This query gives me a grand total of 332 and is my total group in question.

 

List<AggregateResult> mtdAcctsARList = [SELECT Opened_by__c,count(Id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth GROUP BY Opened_By__c];

 The next three, I think, should all total up to 332, but they do not. They return 7, 53 and 152 respectively.

 

//Count any Accounts linked to Cross Sell Opptys
List<AggregateResult> crossSellARList =[SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND Opportunity__r.RecordType.Name = 'ETC Cross Sell Opportunity' GROUP BY Opened_by__c];


//Count any Account not linked to Cross Sell Opptys that have a Referrer		
List<AggregateResult> referralARList = [SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND (Opportunity__r.RecordType.Name != 'ETC Cross Sell Opportunity' OR Opportunity__c = null) AND Account_Holder__r.Referred_by__c != null GROUP BY Opened_by__c];


//Count any Account not linked to Cross Sell Opptys that DON'T have a Referrer
List<AggregateResult> outboundARList = [SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND (Opportunity__r.RecordType.Name != 'ETC Cross Sell Opportunity' OR Opportunity__c = null) AND Account_Holder__r.Referred_by__c = null GROUP BY Opened_by__c];
	

 I'm sure it has something to do with the Opportunity relationship, but for the life of me I can't figure out why it isn't working.

 

Thanks in advance.

 

David

Hello folks,

 

I've run into a bit of a challenge. I have this nice page and controller built that allows ours sales management to reassign leads that are owned by inactive reps (recently left the company).

 

My problem is with test coverage. I wrote up the test method for the controller and everything showed 100% coverage in sandboxes. When I deployed though, the test fails due to the dreaded MIXED_DML_OPERATION exception.

 

The setup for the test involves:

 

  1. Find an active user with the proper Role.
  2. Create a few leads with different criteria and assign them to that user.
  3. Insert the Leads.
  4. Deactivate the User so that the controller finds the new Leads in the query.

It's that last line, of course, that causes an issue. I'm well aware of the MIXED_DML problem, but I was hoping I could get around it in a test method. When the tests all passed in the Sandbox, I thought I was OK.

 

Any thoughts on how to get code coverage if I have to have Leads owned by a User that is inactive?

I'm hoping some genius out there can help me figure this one out.

 

We just implementing some geocoding code to get tie into the Yahoo Placefinder API. The code is designed to run on record inserts and updates if the data used for geocoding has changed. Currently I have a workflow run and field update in place to set a field called "GeoCode Status" to "Needs Update" when the criteria changes and the apex trigger only calls for geocoding when the "GeoCode Status" field has changed to this value.

 

This works great and fails gracefully if info cannot be retrieved.

 

One problem has arisen, though, due to an AppExchange app called DupeBlocker from CRMFusion. For those that are unfamiliar, this is a duplicate management/prevention app. It has one feature that auto-merges records based on criteria we define. Enter the issue....

 

  1. The dupe checks are all done in @future annotated methods.
  2. The auto-merges can potentially update address fields.
  3. Updates to address fields trigger geocoding.
  4. Geocoding, being doing through a callout, must be in an @future annotated method.
  5. @future methods cannot trigger other @future methods.

This only comes up when an auto-merge happens, but I'd like to figure out some what of getting around this if possible.

 

Thanks in advance,

 

David

 

Maybe I'm missing something here, but I can't seem to get a Trigger or Workflow to kick on when looking at the Status field on EmailMessages, specifically looking for "Replied". We'd like to tag the cases with a "First Response" DateTime.

 

The workflow I set up is a "When created or when edited and didn't previously meet..." and the criteria are Status = Replied AND Case.First Response = null. Apparently when replying, only the newly created EmaiMessage triggers workflow or Apex. Am I missing something here? Is there no way to use system initiated changes to Status on EmailMessages?

 

*I know could probably just trigger it on the new message creation, but "technically" it really should be on the Replied status, not the Sent in my mind.

Hello all,

 

I'm currently working on developing a photo uploader to show photos on the Contact or Lead page. I know there are a couple implementation on the AppExchange, but neither one does all that I want, so I'm rolling my own.

 

Ideally, the page used to do the uploading will be as versatile as possible. (e.g. It could be launched from a Lead or Contact page or be launched by itself and allow the user to lookup the Lead or Contact to associate the photo with).

 

To accomplish this I'm using a "proxy" Task in my controller to get my hands on that handy "Lead/Contact" lookup field. What I'm having a hard time figuring out is how to get the full standard behaviour out of it. Most situations work great.

 

  • Select Lead or Contact and click the lookup icon to search for and select the proper record - Works
  • Select Lead or Contact, type in part or all of the name, click on the lookup icon to get results and select proper record - Works
  • Select Lead or Contact, type in part or all of the name and execute save method in controller which uses the WhoId from the proxy as the parentID of the attachment. Work when there is only one match in the database but breaks when there are multiple matches.

Is there a simple way to get the page to give me the nice dropdown to select the proper record before continuing? I'm not actually commiting this proxy Task to the database.

 

Thanks in advance.

 

David

 

So I've got this great little VF page that perfectly meets the needs of our users when embedded in the standard Account page layout. The problem is, it doesnt work for non-admin users.

 

It's basically just a data table generated from:

 

<apex:dataTable value="{!Account.ActivityHistories}" var="a" rows="5" columns="5" columnswidth="10%,10%,10%,10%,60%"  rules="rows" width="100%" bgcolor="#F3F3EC" cellpadding="3px" cellspacing="2px">

 

 

When the Account page is viewed by a non-admin user though, the page returns:

 

Content cannot be displayed: MALFORMED_QUERY: Implementation restriction: activity aggregate relationships only allow security evaluation for non-admin users when LIMIT is specified and at most 500

 Ok, seems pretty self explanatory, just need to limit the query. But how? I'm only asking for the 5 most recent. I'm really hoping I don't have to write an extension just for this.

 

Any thoughts?

 

Ok, so the driving force this this piece of code was to reassign leads for Users that are made inactive to a Queue to reassigned to other sales reps. Seems like a relatively common situation, right?

 

Seemed like a pretty simple trigger to right as well, even for a beginner like myself.  Unfortunately I appear to be wrong in that assumption.

 

From my reading it seems that we cannot update other records (Leads, Contacts, Accouts, etc.) when a User's profile is updated. Is that really the case or am I missing something terribly obvious here?

 

 

trigger ReassignSalesLeadstoSupervisorforInactive on User (after update) { //Get Id for Sales Supervisors Queue Group sup = [SELECT Id FROM Group WHERE Name='Sales Supervisors' AND Type='Queue']; Set<Id> inactive = new Set<Id>(); List<Lead> reassign = new List<Lead>(); //Determine if user is a Sales User that has just been made Inactive for(user u : trigger.new){ if(u.Department == 'Sales' && Trigger.oldMap.get(u.id).IsActive == True && u.IsActive == False){ inactive.add(u.id); } } System.debug('****Users****'+inactive); //Find the inactive user's leads and reassign them to the Sales Supervisors Queue for(Lead l : [SELECT Id,OwnerId FROM Lead WHERE OwnerId IN :inactive]){ l.OwnerId = sup.id; reassign.add(l); } System.debug('****Leads****'+reassign); update reassign; }

 

 

 

I'm afraid the answer is a big fat "No", but maybe I'm wrong.

 

Can I really do anything when a Contact is marked as Primary in the Contact Roles list on the Account?

 

e.g. - I want to pull a field from said Contact into the Account record. Obviously, a formula field would be ideal, but a trigger would probably get the job done if need be. It seems I can't create a trigger on the AccountContactRole object and I don't have the nice lookup option in a formula field on the Account object to get data from the designated Primary Contact.

 

It would make sense that I should be able to do something with that relationship, but I'm just drawing a blank here.

So now I'm diving head first into Visualforce and custom controllers. The driving force behind this new project is an issue that is causing Account records to be created with duplicate values in a custom field. At this point it is not an option to make this field "unique".

 

To identify these duplicates, I'm currently exporting a list of Accounts with this field populated, importing this table into Access and running a Find Duplicates query on the data.

 

Well, I thought VF might offer a more elegant solution to this problem so I tried whipping up a quick page and custom controller to display these duplicate records. I'm sure there is a more elegant way of doing this, but it was a good learning exercise for me.

 

The problem comes in the Test method. I  really only interested in Accounts created in the last 30 days, so I've limited by query by CreatedDate, but the Test method still hits a governor limit in production. Is there a quick and easy way for me to fix this?

 

 

VF Page:

 

<apex:page controller="DupeAcctNumbers"> <apex:pageBlock > <apex:pageBlockTable value="{!dupes}" var="d"> <apex:column headerValue="Account Number"> <apex:OutputLabel value="{!d.AccountNumber__c}" id="txtAccountNumber__c" /> </apex:column> <apex:column headerValue="Name"> <apex:OutputLink value="../{!d}" id="txtName" >{!d.name}</apex:OutputLink> </apex:column> <apex:column headerValue="Created Date"> <apex:OutputLabel value="{!d.CreatedDate}" id="txtCreatedDate" /> </apex:column> <apex:column headerValue="Created by"> <apex:OutputLabel value="{!d.Createdby.Name}" id="txtCreatedby" /> </apex:column> <apex:column headerValue="Owner"> <apex:OutputLabel value="{!d.Owner.Name}" id="txtOwner" /> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:page>

 

 

 

 

Custom Controller:

 

public class DupeAcctNumbers { private datetime tminus30 = datetime.now().addDays(-30); private Set<String> acctsLast30 = new Set<String>(); private Integer counttmp = 0; private Map<string,integer> acctnumcount = new Map<string,integer>(); private Set<String> dupenums = new Set<String>(); public List<Account> dupes = new List<Account>(); public List<Account> getdupes() { for(Account a30 : [SELECT AccountNumber__c,CreatedDate FROM Account WHERE AccountNumber__c != null AND CreatedDate > :tminus30] ) { acctsLast30.add(a30.AccountNumber__c); } for(Account a : [SELECT AccountNumber__c,Id FROM Account WHERE AccountNumber__c IN :acctsLast30]){ if(acctnumcount.containsKey(a.AccountNumber__c)) { counttmp = acctnumcount.get(a.AccountNumber__c) + 1; acctnumcount.put(a.AccountNumber__c,counttmp); } else { acctnumcount.put(a.AccountNumber__c,1); } } for(String c : acctnumcount.keyset()) { if(acctnumcount.get(c) > 1) { dupenums.add(c); } } for(Account dupe : [SELECT AccountNumber__c,Name,Id,CreatedDate,Createdby.Name,Owner.Name FROM Account WHERE AccountNumber__c in :dupenums ORDER BY AccountNumber__c]) { dupes.add(dupe); } return dupes; } //test method static testMethod void runPositiveTestCases() { Account test1 = new Account(FirstName='Test1',LastName='Test1',AccountNumber__c='12345678'); insert test1; Account test2 = new Account(FirstName='Test2',LastName='Test2',AccountNumber__c='12345678'); insert test2; DupeAcctNumbers dTest = new DupeAcctNumbers(); dTest.getdupes(); } }

 

 

 

Alright. So I've started writing my own triggers (instead of just editing the ones written by others for us) and I've run into a bit of a quandry. 


UpdateSFDCData: execution of BeforeInsert
caused by: System.Exception: Too many SOQL queries: 21
Trigger.UpdateSFDCData: line 9, column 16

 

I know this has to do with the limit on queries being exceeded in the trigger and the fix somehow involves a list, but I'm not sure how to go about implementing it.

 

Is my code way off base or is it a simple fix?

 

 

trigger UpdateSFDCData on GScore_Live__c (before insert, before update) {

for(GScore_Live__c gs: trigger.new){
String pcode = gs.Name;
String own = gs.Sales_User__c;
Integer mnth = System.Today().Month();
Integer yr = System.Today().Year();
Date today = System.Today();

gs.AcctOpen__c = [select count() from Account where CALENDAR_MONTH(Account_Established__c) = :mnth AND CALENDAR_YEAR(Account_Established__c) = :yr AND Account_Status__c = 'Open' AND Producer_Code__c = :pcode ];
gs.AcctPndg__c = [select count() from Account where Status__c IN ('Waiting Original','Open','In Process','Pending Admin Review','Waiting Internal','App Received','Callbacks') AND Producer_Code__c = :pcode ];
gs.ODTasks__c = [select count() from Task where ActivityDate < :today AND Owner.name = :own];
gs.SFDC_Interactions__c = [select count() from Task where Call_Result__c = 'Significant Interaction' AND CALENDAR_MONTH(ActivityDate) = :mnth AND CALENDAR_YEAR(ActivityDate) = :yr AND Owner.name = :own];


if(gs.Total_Points__c >= 85){
gs.Grade__c = 'A'; }
else if(gs.Total_Points__c >= 65){
gs.Grade__c = 'B'; }
else {
gs.Grade__c = 'C'; }
}
}

 

 

 

Hello all,

 

Beginner Apex developer here again. Nearly complete with a project and now I need to write a class that I can run monthly with new apex  scheduler.

 

All it needs to do is take data from records in a custom object (all records) and create new records in a second custom object with all that data.

 

Custom Object 1 = Updates of MTD live data from our phone system for each sales rep.

Custom Object 2 = Month end snapshots for historical tracking puposes.

 

I'm sure there is an easy way to do this, but with my limited knowledge I'm not sure where to start. If some kindly developer could point me in the right direction, I'm sure I can put the pieces together.

I'm writing a trigger and need to count records that match a few criteria.

 

The current query is:

 

 

Integer i = [select count() from Account where Account_Status__c = 'Open' AND Producer_Code__c = :pcode ];

 I need to add another criteria that will match records with "Account_Established__c" within the current month?

 

Any quick and easy way to do this?

 

Thanks in advance.

 

 

 

Hello all, 

 

I'm just a beginner when it comes to Apex, so go easy on me. We have a trigger created by a third party consultant that creates a new case on for an account when a picklist value equals a certain value. The problem with the trigger they created is, every time the account is edited/updated it creates another identical case (assuming that it is still in that stage).

 

Is there an easy way to edit the trigger that will prevent this?

 

 



//creating case for waiting rollover
trigger CreateCaseonAccount on Account (After insert,After update) {
Case objCase = new Case();
list lstCase = new list();
list lstCase1 = new list();

for(Account objAccount1 : trigger.new){
if(objAccount1.Status__c == 'Waiting Rollover'){
objCase.Notes_Status__c = 'Completed Notes';
objCase.Status = 'New';
objCase.Subject = 'Waiting Rollover';
objCase.Origin = 'Web';
objCase.Priority = 'Medium';
objCase.Type = 'Outbound Call';
objCase.Sub_Type__c = 'Welcome Call';
objCase.Reason = 'Account Overview';
objCase.Case_Reason_Type__c = 'Rollover';
if(objAccount1.Client__c != null)
objCase.Client__c = objAccount1.Client__c;
if(objAccount1.id != null)
objCase.AccountId = objAccount1.id;
if(objAccount1.Contact__c != null)
objCase.ContactId = objAccount1.Contact__c;
lstCase.add(objCase);
}
if(lstCase.size()>0){
insert lstCase;
}
//creating case for closed status
if(objAccount1.Status__c == 'Closed'){
objCase.Notes_Status__c = 'Completed Notes';
objCase.Status = 'New';
objCase.Subject = 'Welcome Call';
objCase.Origin = 'Web';
objCase.Priority = 'Medium';
objCase.Type = 'Outbound Call';
objCase.Sub_Type__c = 'Welcome Call';
objCase.Reason = 'Activity Status Request';
objCase.Case_Reason_Type__c = 'Account Open';
if(objAccount1.Client__c != null)
objCase.Client__c = objAccount1.Client__c;
if(objAccount1.id != null)
objCase.AccountId = objAccount1.id;
if(objAccount1.Contact__c != null)
objCase.ContactId = objAccount1.Contact__c;
lstCase1.add(objCase);
}
if(lstCase1.size()>0){
insert lstCase1;
}
}//end of for
//end
}//end of trigger

Message Edited by David81 on 02-01-2010 06:03 AM

I'm just starting my journey into VF so please excuse me if this is a rudimentary question.

 

Our sales dept. has requested a different layout for the "Tasks" area on the home page. Seeing as how we can't customize the columns in this area, I've looked into replacing it with a VF page in an iframe. So far so good.

 

The code I'm using is pretty simple but accomplishes the basic goal except for one glaring problem, any links that are clicked stay within the iframe.  

 

Here's the page that's currently being embedded-

 

________

 

<apex:page StandardController="Task" sidebar="false">

 

<div style="position:absolute; top:-95px; left:0; width:100%;">

<apex:enhancedList type="Activity" height="300" />

</div>

 

</apex:page>

 

________

 

Is there any way I can redirect those links to the parent window? My normal javascript tricks just don't seem to work.

 

Thanks in advance. 

Hi Guys...!

Hpoe all are doing well...

 

I have small Problem, 

I'm updateing the Object record in Class.

like below, I'm using sObject Instance to Update the record.

I'm assigning like below but Error was throwing.

sObj.Phone_No__c = '9999999999'; 

so i used like this, but same result.......... Error

sObj.get('Phone_No__c') = '9999999999';

update sObj;

 

And I'm getting Error like

" Field expression not allowed for generic SObject ".

 

 

 

 Now How can i update that perticular Record Phone No using sObject instance. 

 

and when I'm using Id then  no Error was throwing,

sObj.Id 



then No error

Hey all.

I feel like I've asked this question before, but I cannot find the answer anywhere :P

So I'm writting a service that can take a block of XML to update objects. Each XML element has a string that contains type type of object it represends and the ID of the already existing object. For example

<Object type="Contact" id="a0FU00000008h9G">
    <field id="phone">5555555555</field>
</Object>

 

 While iterating over this list of XML items, how can I create a sObject of the type specified in the type field, and set the id as well? I can get most of the way there, doing something like this...

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SobjectType oType;

//reader.getAttributeValueAt(0) will evaluate to the object type in the XML
oType = gd.get(reader.getAttributeValueAt(0));

//If the Id is specified I need to create that type of sObject and set the ID, so I can perform an update.
//If not, I just need to create a new instance of that type of object.

if(reader.getAttributeLocalName(1) == 'id')
{
	//this fails because it says id is an unknown attribute.
	//reader.getAttributeValueAt(1) will evaluate to the id of the existing object
	thisObject= oType.newSObject(id=reader.getAttributeValueAt(1));
}
else
{
	thisObject = oType.newSObject();
}

 


 I can create a NEW instance of the type of sObject i want, but create one with the Id set so I can update it explodes. It says 

'Variable does not exist: id'

Any thoughts? Any kind of help would be much appreciated. Thanks!
 

I am trying to create a trigger that will fire off a email to a user when the assign to person completes their activity.

 

how do i add a email template to this trigger below?

 

trigger Trigger_Request_CompletedAfterInsertAfterUpdate on Task (after insert, after update)
 {
    
 
   Task[] completedTasks = Trigger.new;
   for(Task t : completedTasks){
      if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
      }
   }
}

 

  • July 22, 2011
  • Like
  • 0

Hello folks,

 

I'm just about to pull my hair out on this one and I'm hoping someone out there can help me out. I have a few queries being used to populate a VF table that just aren't adding up, although I think they should be.

 

The two variables you will see are repIds (a List of User Ids) and firstOfMonth (a Date that corresponds to the 1st day of the current month.

 

This query gives me a grand total of 332 and is my total group in question.

 

List<AggregateResult> mtdAcctsARList = [SELECT Opened_by__c,count(Id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth GROUP BY Opened_By__c];

 The next three, I think, should all total up to 332, but they do not. They return 7, 53 and 152 respectively.

 

//Count any Accounts linked to Cross Sell Opptys
List<AggregateResult> crossSellARList =[SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND Opportunity__r.RecordType.Name = 'ETC Cross Sell Opportunity' GROUP BY Opened_by__c];


//Count any Account not linked to Cross Sell Opptys that have a Referrer		
List<AggregateResult> referralARList = [SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND (Opportunity__r.RecordType.Name != 'ETC Cross Sell Opportunity' OR Opportunity__c = null) AND Account_Holder__r.Referred_by__c != null GROUP BY Opened_by__c];


//Count any Account not linked to Cross Sell Opptys that DON'T have a Referrer
List<AggregateResult> outboundARList = [SELECT Opened_by__c,count(id)num FROM Account__c WHERE Opened_by__c IN :repIds AND Account_Established__c >= :firstOfMonth AND (Opportunity__r.RecordType.Name != 'ETC Cross Sell Opportunity' OR Opportunity__c = null) AND Account_Holder__r.Referred_by__c = null GROUP BY Opened_by__c];
	

 I'm sure it has something to do with the Opportunity relationship, but for the life of me I can't figure out why it isn't working.

 

Thanks in advance.

 

David

Hi All,

 

I was having a hard time figuring out what is the format that the Date/Time field should acccept. The format I am generating to another source code is 5/17/2011 11:00 or dd/mm/yyyy hh:mm. and Salesforce does not accept when I tried to insert. I also tried using the datetime.valueOf but it still does not work, it says invalid date.

 

Please advise.

When you write an application that logs in through the API, is there something in the API that allows you to control what shows up in a user's login history? So instead of it saying Other API in the login history it could put in the name of your application that logged into Salesforce?

So I've got this great little VF page that perfectly meets the needs of our users when embedded in the standard Account page layout. The problem is, it doesnt work for non-admin users.

 

It's basically just a data table generated from:

 

<apex:dataTable value="{!Account.ActivityHistories}" var="a" rows="5" columns="5" columnswidth="10%,10%,10%,10%,60%"  rules="rows" width="100%" bgcolor="#F3F3EC" cellpadding="3px" cellspacing="2px">

 

 

When the Account page is viewed by a non-admin user though, the page returns:

 

Content cannot be displayed: MALFORMED_QUERY: Implementation restriction: activity aggregate relationships only allow security evaluation for non-admin users when LIMIT is specified and at most 500

 Ok, seems pretty self explanatory, just need to limit the query. But how? I'm only asking for the 5 most recent. I'm really hoping I don't have to write an extension just for this.

 

Any thoughts?

 

Hi All,

 

I have a requirement to show # of open Task on Lead Detailpage. Below is the logic that we are planning to implement. I would like tocheck with you if any one has implemented similar functionality handling BULK insert/update.If so could you please share the code?

 

Trigger on Task <after insert after update>

 

{

    for (Task thistask : Trigger.new)

      {

    // Get all leads assosited to Tasks

    if (WhoId.startsWith('00Q'))               

      leadIdToUpdateList.add(taskWhoId.WhoId);

     }

 

FOR each Lead

           SelectCount() from Task where whoId=LeadId and Status=Completed

           Updatecustom field “ Open Task” on  Lead object

End Loop   

 

}

 

Thank You .