• kdavis
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 19
    Replies

Hi,

 

I'm writing a trigger to prevent duplicate accounts from being created and to do that I am using a SOSL to search across phone fields for accounts. Person Accounts are being used. Its running on update and insert. I have no idea why but it will actually work on some instances but most of the time it allows duplicates. When you enter a value in the phone field in should search across all phone fields in all accounts to see if one exists. Code is below, please lemme know if you notice something becuase I am stumped. I limit the trigger to single updates only.

Thanks.

/*Need to limit the deduping from running for bulk updtes*/
    Integer triggerSize = Trigger.New.size();
    if(triggerSize == 1){ 
        if((Trigger.isUpdate && Trigger.isBefore) ||(Trigger.isInsert && Trigger.isAfter)){
            String phones;
            Account acct = Trigger.New[0];
            Account returnedAccount;
            String home = acct.PersonHomePhone;
            String mobile = acct.PersonMobilePhone;
            String otherPhone = acct.PersonOtherPhone;
            String regPhone = acct.Phone;
            Set<String> currPhones = new Set<String>{home,mobile,otherPhone,regPhone};
            Set<String> cleansedPhones = new Set<String> ();
            
            for(String p : currPhones){
                if(p != null){
                    p = p.replace('(',''); p = p.replace(')','');
                    p = p.replace('-',''); p = p.trim(); //remove characters               
                    p = p.replace(' ','');
                    cleansedPhones.add(p);
                }
            }

            for(String p : cleansedPhones){
                if(phones == null){
                    phones = String.ValueOf(p);
                }else{
                    phones = phones + ' OR '+String.ValueOf(p);
                }
            }


            System.debug('phones  '+phones);
            
            if(phones != null){
                String queryString = 'FIND {FILTER} IN PHONE FIELDS RETURNING Account(Owner.Name, Name,Id WHERE Id != \'currentId\')';      
                queryString = queryString.replace('FILTER',phones);
                queryString = queryString.replace('currentId',acct.Id); 
                System.debug('This is the Query String    '+queryString);           

                List<List <sObject>> query = search.query(queryString);
                System.debug('This is the return    '+query);
                for(sObject s : query[0]){
                    returnedAccount = (Account)s;
                    System.debug('This was returned  '+returnedAccount);
                }

                if(returnedAccount != null){
                    acct.addError('ERROR: This Account belongs to another broker: '+returnedAccount.Owner.Name, false);
                }
            }
        }
    }       

 

Hi all ,

I have controller and I written test class for that . It is covering 60% code but, I am facing following problem

 

 

I am able see how much % code covered , earlier if we click on percentage it used to show what portion code covered and not covered with different colors , but now its not coming So please help me where I can find that  .

Hi,

 

I'm using a static recursive variables for my triggers and I am encountering an issue when testing. I have 2 triggers. One on a custom object called procedure and another on custom object revenue that updates a procedure when inserted.

 

So in my test class I insert a procedure record, the first trigger runs and at the end sets the recursive variable hasRun = True.

 

Now when I go an insert my Revenue record, I want it to run through the procedure trigger again, but hasRun still equals to True? Do you need to reset static variables like that in test cases because test classes are considered a single execution state?

 

Hi,

 

Getting this extremely annoying issue.

 

Here is my query:

 

assets = [SELECT Id, Name, External_Reference__c, Serial_Number__c, UsageEndDate, (SELECT Id, Name, AssetId FROM Entitlements) FROM Asset WHERE Serial_Number__c IN : serialIds ORDER BY UsageEndDate Desc];

 

 

I have a nested page block where I want to iterate through the child Entitlements, but I continously get this error:

 

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Asset.Entitlements

 

I can't find any security that is prohibiting me from viewing this list.

Any ideas?

 

Hi,

 

I'm putting a VF component on Case records. Essentially I return a set of Asset records and provide a checkbox next to each so they can add multiple assets to the case at once. Once they select a checkbox next to the assets, the asset ID is pushed to a JScript variable. 

 

After all the user has selected all their assets, they click a button which pushes the Javascript Var String to my remote method in my controller where I parse the Jscript string into the different ID's.

 

Problem is, everything works fine in the page, when I do it in editor. Once I get on an actual Case detail page I get an error everytime I try to call the remote method that tells me Uncaugh ReferenceError: [My Controller Name] is not defined. 

 

Any Ideas on how to fix this? I know they communicate correctly in the page editor just not in the acutal component. Code Below:

 

 

Page:

<apex:page standardController="Case" extensions="linkAssetExtension">
    <apex:includeScript value="{!$Resource.JqueryUI}"/>
    <apex:includeScript value="{!$Resource.JQueryCustom}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles}"/>
    <apex:stylesheet value="{!$Resource.JqueryStyles2}"/> 

    
<script type="text/javascript">

var j$ = jQuery.noConflict();

var assets = null;

function selectAsset(ele){
    
    console.log(j$(ele).is(':checked'));
    
    if(j$(ele).is(':checked')){
        console.log(j$(ele).attr('Id'));
        id = j$(ele).attr('Id');
        entitlement = j$(ele).attr('entitle');
        
        if(assets === null){
            assets = id+':'+entitlement;
        }else{
            assets += '-'+id+':'+entitlement;
        }
        console.log(assets);
    }
   
}
    
function insertAssets(){
    
        linkAssetExtension.linkAsset( 
        assets,
        function(result, event){
            console.log(result)
        }
    );

}

</script>

<apex:form >
    <apex:PageBlock title="Search Assets">

            Please Enter A Serial Number:&nbsp;&nbsp;&nbsp;
            <apex:inputText value="{!serialId}"/><br/><br/>

            <apex:pageBlockTable value="{!assets}" var="a" columns="4" Width="90%">
                <apex:column id="Select" headerValue="Select">
                    <input type="checkbox" onclick="selectAsset(this)" name="{!a.Name}" serial="{!a.Serial_Number__c}" id="{!a.Id}" entitle="{!a.Entitlement__c}"/>
                </apex:column>
                <apex:column id="Name" headerValue="Name" value="{!a.Name}"/>                

                <apex:column id="Serial" headerValue="Serial #" value="{!a.Serial_Number__c}"/>

                <apex:column id="Entitle" headerValue="Entitlement" value="{!a.Entitlement__c}"/>

            </apex:pageBlockTable>
      
        <apex:PageBlockButtons location="bottom">
            <apex:CommandButton value="Search" action="{!searchAssets}"/>
            <div style="width:45px;height:18px;border:1px solid black;border-radius:5px;text-align:center;display:inline-block;margin-top:-2px;vertical-align:middle;" onclick="insertAssets()">Link</div>
        </apex:PageBlockButtons>
    </apex:PageBlock>
</apex:form>

</apex:page>

 

Controller:

public class linkAssetExtension {
    
    public String serialId {get; set;} 
    public List<Asset> assets {get; set;}   
    private final Case c;
    public static Id caseId {get; set;}
    
    public linkAssetExtension(ApexPages.StandardController controller) {
        this.c = (Case)controller.getRecord();
        caseId = c.Id;
        assets = new List<Asset> ();
    }

    public void searchAssets(){
        if(serialId != null){
            assets = [SELECT Id, Name, Serial_Number__c, Entitlement__c, Asset_Type__c FROM Asset WHERE Serial_Number__c =: serialId];
        }
    }
    
    @RemoteAction
    public static Map<String, List<String>> linkAsset(String assetList){
       
       system.debug(assetList);
       List<Case> upsertCase = new List<Case> ();
       Map<String, List<String>> assetMap = new Map<String, List<String>> ();
       

        List<String> assetFields = new List<String> ();
        assetFields = assetList.split('-');
        
        for(String s : assetFields){
            List<String> fields = new List<String> ();
            fields = s.split(':');
            assetMap.put(fields[0], fields);
        }
            
     
        for(String s : assetMap.keySet()){
            //Add link records
        }

        return assetMap;
    }    
}

 

Hey Guys,

 

I have a requirement where: A contact already exists, they need a custom button that directs to a visual force page where I have a created a form that has a subset of fields on the contac they need to fill out. When they are done they save and need to update the contact.

 

So far I have completed:

1. Directing to the page

2. Querying the subset of contact fields in the controller that will be used in the page since we cannot use a standard controller

3. Built the page

Error 4. Updating the record using a page refrence

 

Here is the controller:

 

public class IntakeController{

public static Contact currentContact {get; set;}
public final Id cId {get; set;}


public IntakeController() {

cId = ApexPages.currentPage().getparameters().get('cid');
currentContact = new Contact();
currentContact = [SELECT
                  //All the fields
FROM Contact
WHERE Id =: cId];

}

public PageReference SaveContact(){
system.debug(currentContact);

if(currentContact != null){
update currentContact;
}

PageReference returnPage = new PageReference('/' + cId);
returnPage.setRedirect(true); 
return returnPage; 
} 
}

 

Problem is everytime I go to save I get a null value for currentContact in that debug. I am updating the values of contact Record in the page using input fields. What am I doing wrong here, and how do I get the updated values from the page? 

 

Thanks

 

Hi,

 

I am running a scheduled batch job where I perform the DML operation inside the finish method. I placed a debug log inside the finish method to print out my records to see if everything is updating the values correctly and it does, and from the test log I see that it performs the update as well.

 

Now the problem is, after I do my Start.Test() and Stop.Test() where I schedule my class to run and set up data, I query the objects I have updated and print them out nothing happens to them....

 

When I look at the execution in the test log, the print outs in my test method are occuring before my debugs in both my execute and finish methods.

 

Am I missing something here? It looks as if my assertions and debugs are occurring before the fact rather than after and I'm not quite sure how to fix it.

 

Any feedback would be appreciated.

Thanks

Hey guys,

 

So I have a trigger that will run on a bulk update or insert. My query will run 5 Aggregate queries, none of these are in for loops I query based on collected ID's. If I run for more that 2000 records and I hit 

System.LimitException: Too many SOQL queries: 101. Any tips on how to work around this and bulkify my trigger more? I was thinking of batch apex but I have very little familiarity. If I use batch apex can I give a specific amount to insert at once and will it reset governor limits on every batch. Any helpful documentation on this?

Thanks.

Hi,

 

I'm recieving this error: 

No more than one executeBatch can be called from within a testmethod.  Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

 

The scope is an iterable list of XML docs returned by the start method:

global Iterable<SyncXmlFeedsUtils.XmlFeed> start(Database.BatchableContext bc) {
return SyncXmlFeedsUtils.feeds;
}

 

the feeds list is formatted as such:

 

static {

feeds = new List<XmlFeed> {
new XmlFeed('URL----', PressReleaseParser.class),
new XmlFeed('URL----', AnalystReportsParser.class),
new XmlFeed('URL----', WebinarsParser.class),
new XmlFeed('URL----', ClientSuccessStoriesParser.class)
};
}

 

for my execute method I have:

global void execute(Database.BatchableContext bc, List<SyncXmlFeedsUtils.XmlFeed> scope) 

 

And then then the test class:

 

global class SyncXmlBatchTest {


@isTest static void testBatch() {


test.startTest();

Test.setMock(HttpCalloutMock.class, new HttpResonseGenerator());


List<RSINews__c> response = SyncXmlFeedsUtils.parseXmlFeeds(SyncXmlFeedsUtils.feeds);

 

SyncXmlFeedsBatchable batchTest = new SyncXmlFeedsBatchable ();


Id batchprocessId = Database.executeBatch(batchTest, 1);

test.stopTest();

}


}

 

 

Any Idea how to get around this error? If I don't set the batch size to 1 I get another error saying "System.CalloutException: . Please commit or rollback before calling out".

 

Any help would be very appreciated.

Thanks.

Hi, 

I'm trying to parse some XML with the following code

 

public class AnalystReportsParser implements XMLParser{

public virtual RSINews__c[] parseXml(XmlStreamReader xml) {
RSINews__c[] news = new RSINews__c[0];
while(xml.hasNext()) {

  if (xml.getEventType() == XmlTag.START_ELEMENT) {

   if ('Page' == xml.getLocalName()){

       if('en-us' == xml.getAttributeValue(null, 'Locale')){
             RSINews__c record = new RSINews__c ();

 

                  ''

                  ''

             news.add(record);
        }
     }

      xml.next();
    }
}
return news;
}
}

 

However I keep recieving the error:

System.LimitException: Too many code statements: 200001

And it indicates that it occurs in my if loop:

 

if (xml.getEventType() == XmlTag.START_ELEMENT) {

 

any ideas why this occurs?

thx

Hi,

 

Can anyone tell me where to find some quality documention on parsing XML with apex. I have no experience in parsing XML, so some detailed walkthrough's would be very helpful.

 

Thanks!

Hello,

 

I have a (before insert, before update) trigger on a custom object called Assignment that reassigns the record ownerID to a user ID based on a custom field in the Assignment object that looks up to another custom object called Requested Employee that looks up to a user record.

 

In addition I have a workflow rule that populates the users email in a custom field on the Assignment object.

 

The trigger works, I am able to reassign the owner, but only when the workflow rule is active. When I deactivate the workflow rule, the record owner will not reassign when I insert a new record, it will only update after I have edited a record TWICE.

 

My question is...why does this occur. I'm relatively new to SF and Apex, and trying to learn what is going on behind the scenes in this situation.

I'm assuming the workflow rule has some effect on the records contained in the Trigger.NEW list but I am having trouble wrapping my head around what is going on.

 

Any help or advice would be greatly appreciated.

 

Thanks!