• logontokartik
  • PRO
  • 3492 Points
  • Member since 2011
  • Salesforce Architect/Developer


Badges

  • Chatter
    Feed
  • 111
    Best Answers
  • 1
    Likes Received
  • 6
    Likes Given
  • 20
    Questions
  • 806
    Replies
Regarding using SOQL to assign and retrieve attributes, I need identify the Postal Code of the Contact and I do not know how to name it?

Imagine I am having the following code:

Contact[] cts = [SELECT Contact.LastName, Contact.Postal_Code FROM Contact WHERE LastName =: sName OR PostalCode =: sPostalCode]; 
  
        System.debug('Last Name forund + cts[0].LastName);
        System.debug('PostalCode found' + cts[0].PostalCode);

The problem is that Contact.PostalCode can't be found and I do not know how to name it. 

Anyone can help me?

Thanks!

Bea
 
I am working on force.com site. i have a method which insert a record. user have all the permission CRUD and all fields are visible. when this method is called by commandlink it work. when call by any other method with in the class. site give autorisation error.
How can i Fix this. when i do this.
<!-- Visual force active site home page-->

<apex:page controller="tempcontroller">
<apex:commandbutton value ="insert" action="{!ins}">
</apex:page>


<!-- visual force controller--->

public with sharing tempcontroller{

tempcontroller(){

}
public void ins(){
 position__C pos = new postion__C(name'test');
inser pos;

}

}
the above code works fine but if i do following
 
<!-- Visual force active site home page-->

<apex:page controller="tempcontroller">
<p> this is a page</p>
</apex:page>


<!-- visual force controller--->

public with sharing tempcontroller{

tempcontroller(){

}
public void check(){
ins();

}
public void ins(){
 position__C pos = new postion__C(name'test');
inser pos;

}

}

this gives autorisation error . 
how can i solve this please help

 
<apex:page controller="Testctrl">
    <apex:form >
        <apex:repeat value="{!attdmap}" var="attdkey" >
            <apex:OutputText value="{!attdkey}"/>
            <apex:OutputText value="{!attdmap[attdkey]}"/>
       </apex:repeat>
    </apex:form>
</apex:page>



public class Testctrl {
    public list<Student__c> acctlist {get;set;}
    public Map<Student__c, Boolean> attdmap{get;set;}
     
    public Testctrl(){
        Map<Student__c, Boolean> attdmap = new Map<Student__c, Boolean>();
        acctlist = [SELECT Id, Name FROM Student__c];
        for(Student__c atu23 : acctlist){
        attdmap.put(atu23,false);
        }        
    }

}

Hi Guys,
I am facing problem in soql injection, I have written a query to fetch Account data with condtion Name like bellow.
string queryString='select id,name,billingstreet from account'
if (AccountName != null && !AccountName.equals(''))    {
              AccountName= '%' + AccountName + '%';  
              queryString += ' Where Name LIKE :AccountName ';
     }
I have passed parameter % it's return all the account even I used String.escapeSingleQuotes(AccountName) as below
if (AccountName != null && !AccountName.equals(''))    {
              AccountName= '%' + String.escapeSingleQuotes(AccountName) + '%';  
              queryString += ' Where Name LIKE :AccountName ';
     }
Even it's return all account,

How can we resolve this Injection problem..
Thanks.

Hello Everyone,
I am stuck here...Please tell me how to create a validation rule for this and can anyone explain this question.

To complete this challenge, add a validation rule which will block the insertion of a contact if the contact is related to an account and has a mailing postal code (which has the API Name MailingPostalCode) different from the account's shipping postal code (which has the API Name ShippingPostalCode).
1. Name the validation rule 'Contact must be in Account ZIP Code'.
2. A contact with a MailingPostalCode that has an account and does not match the associated Account ShippingPostalCode should return with a validation error and not be inserted.
3. The validation rule should ONLY apply to contact records with an associated account. Contact records with no associated parent account can be added with any MailingPostalCode value. (Hint: you can use the ISBLANK function for this check)
I have a Command button in my VisualForce page, clicking on it would popup a new page. After entering the details and clicking on Save, popup window will close and refresh the parent page. I found some code and tried to replicate the same in my page. Below is my code to popup the new window:


<apex:pageBlockSection title="Create New Account" columns="3">
<apex:commandButton value="Create New Account" onclick="popupNew();" reRender="accTable"/>
</apex:pageBlockSection>

function popupNew(){
var newwindow = window.open('/apex/AddAccount','Add account', target='_blank');
newwindow.focus();
return false;
}


When I click on Save in the popup window, I'm doing this:


<apex:commandButton action="{!quicksave}" value="Save" status="closer" reRender="qId,accTable" timeout="1000" rendered="true" /> <apex:actionStatus id="closer" startText="Saving.." stopText="" onstop="refreshPage();" rendered="true"></apex:actionStatus>

function refreshPage(){
window.top.close();
window.opener.location.href="/apex/Account_Contact_Layout";
window.opener.location.reload(true);
}

The problem here is refreshPage() function is not getting called at all. If I use onstart="refreshPage()" instead of onstop="" it is getting called. What am I missing here?

P.S: The problem with onstart="" is that the window closes as soon as I click on Save button and immediately refreshes the parent page. Save happens in the background when the page has started refreshing already. So, I will have to refresh the page manually again to see my results, which makes no sense.

Hi All, 

I have an old email address that I want to use for me DE but cannot remember the password. When I get sent change your password link it is asking for the answer to my secret question. I have tried few combination that I can think of, nothing works. It says to contact your admin, well I'm the only admin in my org. How can I have this password reset? I would really like to use that account again. 

Thanks guys! :) 

 

I am new to writing Apex Triggers. I eventually want to count notes and attachments and update Event object. I am able to get the list of Event objects from the trigger attachment objects. I am able to get the count of attachments for each event. I can iterate through the Event items, and then the update doesn't seem to work.

I have a feeling this is something stupid.
I get this back when I run the test:
FATAL_ERROR System.AssertException: Assertion Failed: Expected: 1, Actual: null

Here is my trigger:
trigger Update_events_for_attachments on Attachment (after insert, after update) {

    List<Id> parentIDs = new List<Id>();
    
    for(Attachment att:Trigger.New){
		if(att.Parentid.getSObjectType().getDescribe().getName() == 'Event'){
            parentIDs.add(att.Parentid);
            System.debug('parent ID:' + att.Parentid);
        }
    }
    
    List<Event> evs = new List<Event>([select id, Note_Count__c from Event where id in :parentIDs]);
    System.debug('evs size:' + evs.size() + '    parentidsize:' + parentIDs.size());
    
    if(parentIDs.isEmpty()){
        System.debug('we didn\'t find any events');
        //if empty, we have no events to update
        return;
    }
    
    Map<ID, Integer> mymap = new Map<ID, Integer>();
    AggregateResult[] ARs = [select count(id) mycount, parentid  from attachment where parentid in :parentIDs group by parentID];
        
    for (AggregateResult ar : ARs){
        Integer thisCount = (Integer) ar.get('mycount');
        ID thidID = (ID) ar.get('parentid');
        mymap.put(thidID, thisCount);
    }
    
    
    for (Event thisEvent : evs){
        System.debug('looping thorugh evs');
        ThisEvent.Note_Count__c = mymap.get(thisEvent.ID);
        System.debug('ThisEvent.id:' + thisEvent.Id + '    ThisEvent.Note_Count__c: '+ ThisEvent.Note_Count__c);
    }
    
    update evs;
    
}

and here is the test class I'm trying to use:
@isTest
private class test_Update_events_for_attachments {

    @isTest static void TestAddingSingleAttachment(){
        Event newEvent = new Event();
        newEvent.Subject ='Test';
        newEvent.DurationInMinutes =1440;
        newEvent.ActivityDate = System.today();
        newEvent.ActivityDateTime = System.today();
        insert newEvent;
        
        Test.startTest();
        Attachment attach=new Attachment();   	
    	attach.Name='Unit Test Attachment';
    	Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    	attach.body=bodyBlob;
        attach.parentId=newEvent.id;
        insert attach;
 
        System.debug('newEvent.Id:' + newEvent.Id + '    attach.parentID: ' + attach.parentID + '       newEvent.Note_Count__c: ' + newEvent.Note_Count__c);
        System.assertEquals(newEvent.Id, attach.parentID);
        System.assertEquals(1, newEvent.Note_Count__c);
        Test.stopTest();
    }
    
    
}


 
Hi Guys,
I write one time apex:image it will show in all pages. So i used static resource but it didn't come and often i had to write apex:image. I tried whatever examples in google. So please try in your org and help me out this problem.

Static Resource:
<style type="text/css" media="print">
div.header {
position: running(header);
}
@page
{
margin-top: -0.2in;
margin-left:-0.1in;
margin-right:-0.1in;
@top-center
{ content: element(header);
background-image: url('{!$Resource.Con_Header}');
}
}
</style>
 
Hi,

I have a vf page form that has an inputfile tag for uploading a file, and I use commandButton with status and reRender to show  progress text while file loading and then display file's content.
It's working without rerender but when does not show waiting text and when I added <apex:actionRegion>  to my code doesnot pass parametesrs to apex class.

How can I have progress text with inputfile and commandButton to dislpay info from file at same page?

Thank you.

/Ahmad

below is my vf code snippet

<apex:commandButton value="Save" action="{!ReadFile}" status="theStatus" reRender="testblock"/>
        </apex:actionRegion>
     <apex:actionStatus id="theStatus">
                <apex:facet name="start">
                    <apex:outputPanel >
                        
                        Please wait...
                    </apex:outputPanel>
                </apex:facet>
    </apex:actionStatus>
      <apex:pageBlock id="testblock">
          <apex:pageBlockSection title="My Content Section" columns="2">   
           <apex:outputText >Namn:</apex:outputText>
                <apex:outputLabel value="{!nameFile}"/>
                   <apex:outputText >Namn1:</apex:outputText>
                <apex:outputLabel value="{!nameFile1}"/>
              <apex:outputText >Namn2:</apex:outputText>
                <apex:outputLabel value="{!nameFile2}"/>
            </apex:pageBlockSection>  

Apex:

 public void ReadFile()
    {
        
        if(nameFile == null)
            nameFile2 = 'File name is null ';
        else
            nameFile2 = 'Yohoooo ' + nameFile;
        
        if(contentFile == null)
            nameFile1 = ' content is null ';
        else
            nameFile1 = ' Yohoooo';
Hi,

I'm trying to use dymamic binding of maps to loop through a map and thus my page blocks.  But I'm getting a wierd error 

"Value 'core.apexpages.el.adapters.RuntimeTypeMetadataELAdapter@6149c49c' cannot be converted from core.apexpages.el.adapters.RuntimeTypeMetadataELAdapter to com.force.swag.soap.DateOnlyWrapper."

The looping part of the visualforce
<apex:repeat value="{!opp90Map}" var="category" >     
        <td width="25%" valign="top">
    	<apex:pageBlock title="Top 90 Opp for {!category}">
     <apex:pageBlockTable value="{!opp90Map[category]}" var="opp">

and the map 
public Map<String, List<OppWrapper>> opp90Map {get; set; }  
        repNameList = new List<String>{'Brit', 'Emma', 'Jeanette', 'Kara'};
        opp90Map = new Map<String, List<oppWrapper>>();

the whole thing is a bit too big, but I include for completion sake

Thanks,
public class GoalsOverView_Class {
    
    List<Opportunity> oppListStart;
    List<OppWrapper> opp90RepList;
    public List<OppWrapper> opp90AllList  { get; set; }
	public List<OppWrapper> opp90BritList  { get; set; }
    public List<OppWrapper> opp90EmmaList  { get; set; } 
	public List<OppWrapper> opp90JeanetteList  { get; set; } 
	public List<OppWrapper> opp90KaraList  { get; set; }     
    public List<String> repNameList {get; set; }
    public Map<String, List<OppWrapper>> opp90Map {get; set; }  
    OppWrapper newOpp;
    
    public aggregateResult aggOppTotal {get; set;}
    decimal closedTotal;
    public decimal variance {get; set;}
    Rep_Goal__c goal;
    Decimal goalTotal;
    public Decimal oppTotal {get; set;}
    String UserId;
    public String userName {get; set;}    
    
    public GoalsOverView_Class() {
        repNameList = new List<String>{'Brit', 'Emma', 'Jeanette', 'Kara'};
        opp90Map = new Map<String, List<oppWrapper>>();
        UserId = UserInfo.getUserId();
        oppTotal = 0;
        closedTotal = 0;
        goalTotal = 0;
        Variance = 0;
               
            // top 10 all
                oppListStart = [SELECT Name, StageName, Owner.firstname, Id, Amount, account.id, account.name, type, closedate FROM Opportunity 
                                                  WHERE StageName = 'A. Pending Sale' AND Amount != 0 AND Amount != NULL AND OwnerID=:userID
                                                  ORDER BY Amount DESC LIMIT 10]; 
                aggOppTotal = [SELECT Sum(Amount) TotalAmount FROM Opportunity WHERE StageName = 'W. Win' AND CloseDate = THIS_QUARTER];
                goal = [SELECT Total_Revenue__c, Total_Margin__c, User__R.firstname FROM Rep_goal__c WHERE User__c = :userID AND Goals__r.Start_Date_of_new_Quarter__c = THIS_QUARTER]; 
                goalTotal = goal.Total_Revenue__c;
                closedTotal = (Decimal)aggOppTotal.get('TotalAmount');
 				opp90AllList = generateOppList(oppListStart, goalTotal, closedTotal);

    
        
          
        for(String repName:repNameList) {
               oppListStart = [SELECT Name, StageName, Owner.firstname, Id, Amount, account.id, account.name, type, closedate FROM Opportunity 
                                                  WHERE  Owner.firstname =:repName
                                                  ORDER BY Amount DESC LIMIT 10]; 
                aggOppTotal = [SELECT Sum(Amount) TotalAmount FROM Opportunity WHERE StageName = 'W. Win' AND CloseDate = THIS_QUARTER];
                goal = [SELECT Total_Revenue__c, Total_Margin__c, User__R.firstname FROM Rep_goal__c WHERE User__c = :userID AND Goals__r.Start_Date_of_new_Quarter__c = THIS_QUARTER]; 
                goalTotal = goal.Total_Revenue__c;
                closedTotal = (Decimal)aggOppTotal.get('TotalAmount');
 				opp90RepList = generateOppList(oppListStart, goalTotal, closedTotal); 
            opp90Map.put(repName, opp90RepList);
            
        }
        
        // Brit
        opp90BritList = opp90Map.get('Brit');
        opp90EmmaList = opp90Map.get('Emma');
        opp90JeanetteList = opp90Map.get('Jeanette');
        opp90KaraList = opp90Map.get('Kara');

       			

    }
    
    public List<OppWrapper> generateOppList(List<Opportunity> oppListStart, Decimal goalTotal, Decimal closedTotal) {
        	List<OppWrapper> oppList = new List<OppWrapper>();
            for (Opportunity opp:oppListStart) {
                system.debug('username=' + opp.owner.firstname);
                oppList.add(new OppWrapper(opp.owner.firstname, opp.account.name, opp.name,   opp.CloseDate, opp.Amount,  opp.id) );
                oppTotal = oppTotal + opp.amount;
            }
			if (goalTotal == NULL) {goalTotal = 0; } 
            if (closedTotal == NULL) {closedTotal = 0; }
        	oppList.add(new OppWrapper(NULL, NULL, 'Total Open Opp', NULL, OppTotal, NULL));
       		oppList.add(new OppWrapper(NULL, NULL, NULL, NULL, NULL, NULL));
       	    oppList.add(new OppWrapper(NULL, NULL, 'Total Closed Opp', NULL, closedTotal, NULL));
            oppList.add(new OppWrapper(NULL, NULL, 'Total Goal', NULL, goalTotal, NULL));
 
      	    return oppList;
    }
    

    
    public class OppWrapper {
        public String oppName {get; set; }
        public String acctName {get; set; }
        public String repName {get; set; }
        public Date closeDate {get; set; }
        public Decimal amount {get; set; }
        public String Id {get; set; }
        
        public  OppWrapper(String repName, String acctName, String oppName,  Date closedate, Decimal amount, String id) {
            this.oppName = oppName;
            this.closeDate = closeDate;
            this.amount = amount;
            this.id = id;
            this.acctname = acctName;
            this.repName = repName;
            

            
        }
    }  
    

}

 
Hello,

How to send a request in XML format.
 
<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>

I want to add the above XML in the request i send
<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>

HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('GET');
HTTPResponse resp = req.send(req);
Hi all,

I want to display the JSON response values in VF page. I tried the below code. But it simply displaying the columns not the values. Please anyone suggest me some idea how to display the response in VF page.

Here is my controller
global class CanvasController{

public Integer ItemId{get;set;}
public String name{get;set;}
public List<Items> dr{get;set;}

public CanvasController(){

}

public void requestM(){

    String url = 'http://api.walmartlabs.com/v1/feeds/specialbuy?apikey=5amzkrmy235zddjwmu785hf8&categoryId=3944';

    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('GET');

    Http http = new Http();
    HttpResponse res = http.send(req);
    String responseBody = res.getBody();
    
    ResCls resItem = (ResCls)JSON.deserialize(responseBody, ResCls.class);
    List<Items> rl = resItem.items;
    List<Items> dr = new List<Items>();
    for(Items it:rl){
        system.debug('Item Name: ' + it);
        ItemId = it.ItemId;
        name = it.Name;
        system.debug('ItemId: ' + it.ItemId);
        system.debug('Name: ' + it.Name);
        dr.add(it);
    }   
   system.debug('List: ' + dr);
}

public class ResCls{
    List<Items> items;
}
    
public class Items{

public Integer ItemId{get;set;}
public Integer ParentItemId{get;set;}
public String Name{get;set;}
public Double SalePrice{get;set;}
public String Upc{get;set;}
public String CategoryPath{get;set;}
public Boolean AvailableOnline{get;set;}
public String ShortDescription{get;set;}
public String LongDescription{get;set;}
public String BrandName{get;set;}
public String ThumbnailImage{get;set;}
public String LargeImage{get;set;}
public String ProductTrackingUrl{get;set;}
public Boolean FreeShipping{get;set;}
public Boolean NinetySevenCentShipping{get;set;}
public Double StandardShipRate{get;set;}
public Double TwoThreeDayShippingRate{get;set;}
public Double OvernightShippingRate{get;set;}
public String Size{get;set;}
public String Color{get;set;}
public Boolean Marketplace{get;set;}
public Boolean ShipToStore{get;set;}
public Boolean FreeShipToStore{get;set;}
public String ModelNumber{get;set;}
public String SellerInfo{get;set;}
public String ProductUrl{get;set;}
public List<Integer> Variants{get;set;}
public List<String> Shelves{get;set;}
public String CustomerRating{get;set;}
public String CustomerRatingImage{get;set;}
public Integer NumReviews{get;set;}
public String CategoryNode{get;set;}
public Boolean isRollBack{get;set;}
public Boolean isSpecialBuy{get;set;}
public String Isbn{get;set;}
public Boolean Bundle{get;set;}
public Boolean Clearance{get;set;}
public Boolean PreOrder{get;set;}
public String PreOrderShipsOn{get;set;}
public String Stoc{get;set;}
public Boolean Freight{get;set;}
public Long DealEndTime{get;set;}
public Long DealStartTime{get;set;}
public String Gender{get;set;}
public String Age{get;set;}
}


}
Here is my VF page
 
<apex:page Controller="CanvasController" action="{!requestM}" sidebar="false">
<apex:pageBlock>
<apex:pageblockSection >
<apex:pageblockTable value="{!dr}" var="dd">
        <apex:column headerValue="Item id"><apex:outputText value="{!dd.ItemId}"/></apex:column>
        <apex:column headerValue="Name"><apex:outputText value="{!dd.name}"/></apex:column>
        <apex:column headerValue="upc"><apex:outputText value="{!dd.Upc}"/></apex:column>
</apex:pageblockTable>
    </apex:pageblockSection>
</apex:pageBlock>
</apex:page>

Thanks.
 
Hi,

I want to display values on vf page which is stored in list. I have used <apex:datatable> to display those values. But it is not displaying any values on vf page.In that list contains json deserialized response.I am getting the response, i'm able get the individual values also. It shows in the debug logs, but not displaying in the vf page. 
<apex:page Controller="CanvasController" action="{!requestM}" sidebar="false">
<!--{!response}-->    

<apex:pageBlock>
<apex:pageblockSection >
    <apex:dataTable value="{!dr}" var="d">
        <apex:column headerValue="Item id"><apex:outputText value="{!d.ItemId}"/></apex:column>
        <apex:column headerValue="Name"><apex:outputText value="{!d.name}"/></apex:column>
        <apex:column headerValue="upc"><apex:outputText value="{!d.Upc}"/></apex:column>
     </apex:dataTable>
    </apex:pageblockSection>
</apex:pageBlock>
  
</apex:page>
 
global class CanvasController{

public Integer ItemId{get;set;}
public String name{get;set;}
public List<Items> dr{get;set;}

public CanvasController(){

}

public void requestM(){

    String url = 'http://api.walmartlabs.com/v1/feeds/specialbuy?apikey=5amzkrmy235zddjwmu785hf8&categoryId=3944';

    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('GET');

    Http http = new Http();
    HttpResponse res = http.send(req);
    String responseBody = res.getBody();
    system.debug('statuscode: ' + res.getStatusCode());
    
    //system.debug('Response : ' + responseBody);
    ResCls resItem = (ResCls)JSON.deserialize(responseBody, ResCls.class);
    system.debug('Response after deserialization: ' + resItem);
    system.debug('Response Items: ' + resItem.items);
    List<Items> rl = resItem.items;
    List<Items> dr = new List<Items>();
    for(Items it:rl){
        system.debug('Item Name: ' + it);
        ItemId = it.ItemId;
        name = it.Name;
        system.debug('ItemId: ' + it.ItemId);
        system.debug('Name: ' + it.Name);
        dr.add(it);
    }   
   system.debug('List: ' + dr);
}

public class ResCls{
    List<Items> items;
}
    
public class Items{

public Integer ItemId{get;set;}
public Integer ParentItemId{get;set;}
public String Name{get;set;}
public Double SalePrice{get;set;}
public String Upc{get;set;}
public String CategoryPath{get;set;}
public Boolean AvailableOnline{get;set;}
public String ShortDescription{get;set;}
public String LongDescription{get;set;}
public String BrandName{get;set;}
public String ThumbnailImage{get;set;}
public String LargeImage{get;set;}
public String ProductTrackingUrl{get;set;}
public Boolean FreeShipping{get;set;}
public Boolean NinetySevenCentShipping{get;set;}
public Double StandardShipRate{get;set;}
public Double TwoThreeDayShippingRate{get;set;}
public Double OvernightShippingRate{get;set;}
public String Size{get;set;}
public String Color{get;set;}
public Boolean Marketplace{get;set;}
public Boolean ShipToStore{get;set;}
public Boolean FreeShipToStore{get;set;}
public String ModelNumber{get;set;}
public String SellerInfo{get;set;}
public String ProductUrl{get;set;}
public List<Integer> Variants{get;set;}
public List<String> Shelves{get;set;}
public String CustomerRating{get;set;}
public String CustomerRatingImage{get;set;}
public Integer NumReviews{get;set;}
//public Item.BestMarketPlacePrice BestMarketplacePrice{get;set;}
public String CategoryNode{get;set;}
public Boolean isRollBack{get;set;}
public Boolean isSpecialBuy{get;set;}
public String Isbn{get;set;}
public Boolean Bundle{get;set;}
public Boolean Clearance{get;set;}
public Boolean PreOrder{get;set;}
public String PreOrderShipsOn{get;set;}
public String Stoc{get;set;}
public Boolean Freight{get;set;}
public Long DealEndTime{get;set;}
public Long DealStartTime{get;set;}
//public Item.Attributes Attributes{get;set;}
public String Gender{get;set;}
public String Age{get;set;}
}


}

  
Ok so this is my first deploy from Full sandbox to Production and I received no error messages on the components, but i received the following 2 APEX test failures

ChangeLeadOwnerController_ExtTest testChangeOwner System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, City is Required: [City]
Stack Trace: Class.ChangeLeadOwnerController_ExtTest.testChangeOwner: line 9, column 1

ChangeLeadOwnerController_ExtTest testLeadIdGetterSetter System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, City is Required: [City]
Stack Trace: Class.ChangeLeadOwnerController_ExtTest.testLeadIdGetterSetter: line 42, column 1

I have NO idea what this is or what this means becuse I did NOTHING on the Lead or pulled anything into the Change set from the lead.  Help!
Hi,

I have a tasting object that when saved automatically generates an event.  If that tasting object is updated, it also updates the dates of the event.  Of course if someone deletes the event, that would cause an error on update.  I'm handling the error in the trigger function with an alert about the event.

But I'm not quite sure how to properly test that in my testing class.  I saw in the trailhead example they did something like Database.xxx but I'm not sure how that applies with update, if it even does.

My complete code if it helps
 
trigger TastingEvent on Tasting__c (after insert, after update) {
List<Event> myEvent = new List<Event>();
    User u = [Select id, FirstName from User where id =: UserInfo.getUserId() LIMIT 1];
    
    //Integer size = Trigger.Size;
    if(Trigger.isAfter && Trigger.isInsert && Trigger.size <2)  {
        for(Tasting__c taste:Trigger.New) {
            Event e = new Event();
            String mySubject = (taste.Name + ' - ' + taste.Location__c); // required and default value
            e.Subject = mySubject;
            e.StartDateTime = taste.Date_of_Tasting_Start__c; // required
            e.EndDateTime = taste.Date_of_Tasting_End__c;  // required
            e.WhatId = taste.Id;
            e.OwnerId = u.Id;
            myEvent.add(e);
        }
        insert(myEvent);
        
        
    }
    
    
    if(Trigger.IsAfter && Trigger.isUpdate && Trigger.Size <2) {
        for(Tasting__c taste :Trigger.New) {
            try {
           Event eve = [SELECT Id, StartDateTime, EndDateTime, WhatId FROM Event WHERE WhatID = :taste.Id LIMIT 1];
            eve.StartDateTime = taste.Date_of_Tasting_Start__c;
            eve.EndDateTime = taste.Date_of_Tasting_End__c;
            update(eve);
            } catch(Exception e) {
               Trigger.newMap.get(taste.Id).addError('No matching event to update');
            }
     	}
     }
    
    
}

and the testing class
 
@isTest
Private class TestTastingTrigger {
    @isTest static void TestTasting() {
        // insert feature
      Account newAccount = new Account (Name = 'test Account');
        insert (newAccount);
        String acctId = newAccount.Id;
        
        Test.startTest();
        
       User u = [Select id, FirstName from User where id =: UserInfo.getUserId() LIMIT 1];
       Tasting__c taste = new Tasting__c (Name='Test', 
       	Date_of_Tasting_Start__c = System.Now(),
        Date_of_Tasting_End__c = System.Now(),
        Account__C = acctId );
        insert(taste);

        
        //Perform test
        
        
        Event myEvent = [SELECT Id, WhatId FROM Event WHERE WhatId =:taste.Id];
       	System.assertEquals(taste.Id, myEvent.WhatId);
       
        
        /////////////////////////////////////////////
        // test update feature
        
        DateTime newStart = taste.Date_of_Tasting_Start__c;
        newStart = newStart.addDays(1);
        DateTime newEnd = taste.Date_of_Tasting_End__c;
         newEnd = newEnd.addDays(1);
        taste.Date_of_Tasting_Start__c = newStart;
        taste.Date_of_Tasting_End__c = newEnd;
        
        
       
        update(taste);
        myEvent = [SELECT Id, WhatId, StartDateTime, EndDateTime FROM Event WHERE WhatId =:taste.Id];
        System.assertEquals(taste.Date_of_Tasting_Start__c, myEvent.StartDateTime);
         System.assertEquals(taste.Date_of_Tasting_End__c, myEvent.EndDateTime);
        
        
        delete (myEvent);
        
        // I'm sure this is cheating
        try { update(taste); }
        catch (exception e) {}
                        
    }
    
  
}

Thanks,
Hello Everyone,

I need to disable checkbox when check box is false on  visualforce page I am using wrapper class.
Below is the code

Visualforce page code

<apex:pageBlockSection collapsible="false" title="Rep Downline" rendered="{!initialStep}" columns="1">
             <apex:pageblockTable value="{!contactWrapperList}" var="cont" >
             <apex:column >
              <apex:facet name="header">
              <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
              </apex:facet>
              <apex:inputCheckbox value="{!cont.Oppflagvalue}" id="inputId" immediate="true" >
               <apex:actionSupport event="onclick" reRender="ButtonId" />
               </apex:inputCheckbox>
               </apex:column>
               <apex:column headerValue="CRD#">
               <apex:outputText value="{!cont.cnt.CRD__c}" />    
               </apex:column>
               <apex:column headerValue="Rep Name">
               <apex:outputText value="{!cont.cnt.Name}" />  
               </apex:column>
                <apex:column headerValue="Downline" id="dsp" >
                <apex:outputField value="{!cont.cnt.Downline__c}" />  
                </apex:column>
                 </apex:pageblockTable>

Apex command button
<apex:commandButton value="Next>>>" action="{!submitInitial}" rendered="{!initialStep}" rerender="fid"/>

Wrapper class code
 public class wrapperContact{
          public contact cnt {get; set;}
          public Boolean Oppflagvalue{get; set;}
           public  boolean submitInitial{get; set;}
          public wrapperContact (contact cnt) {
              this.cnt = cnt;
              if(cnt.Id != ApexPages.currentPage().getParameters().get('id'))
              {
                   Oppflagvalue= false;
                   if(Oppflagvalue==false)
                   {
                   submitInitial=true;
                   }
                   
               }
                        else
                        {
                                Oppflagvalue= true;
                                submitInitial=true;
                         }
                }
                    
        }

Can anyone please help me out

Thanks for the help in advance

Regards,
Jyo
Hello - I have researched and researched and researched some more on how to do the following:  Pull the Google geolocation latitude and longitude coordinates into a field that I can report on.

I used the code here (http://blog.elieperez.net/geocode-your-record-salesforce/) and I was able to come up with the Visualforce page and find the coordinates that will populate if the user manually pushes a button in the account:
User-added image

All I want to do is pull the coordinates into a field that I can report on.  Is this possible and can someone please help out with the code?  I am new to the code.

Thank you!
 
Hi, I need some help writing a trigger.
I have two objects I'll be dealing with, Case (standard object) and Injury__c (custom object).  Injury is set up as a related list on the Case record.  On Injury__c records I have a picklist with multiple injury types.  Two of these values are "Head" and "Face".  Also, there can be multiple Injuries, so could have just one, could have one of those and another injury (e.g., arm) or I could have both.
I have a Page Layout on Case specific to Head Injuries.
I need to write a trigger that looks through the Injury__c related list to see if any of the records have injury type records (value in the picklist) of "Head" or "Face".  If it does, then I need the Case Record Type changed to "Head Injury" Record Type.
I can't get my trigger attempts to work.

Thanks!
Hi all,

I have developed an apex trigger to create a custom object record same like an event when an event is created and used workflow rule on that custom object to send an email alert. because events doesn't support workflow emails.
This trigger is getting an error while creating a recurring event.
I am posting my apex trigger and screen shot of my error message. Please have alook and let me know what could be wrong.
trigger createtask on Event (after insert) {     
List<Task1__c> t1 = new List<Task1__c>();
    for (Event newEvent: Trigger.New)
         {
            
                 t1.add (new Task1__c(
                     Name = 'New PD',
                    Record_Id__c = newEvent.Id,
                    Record_Type__c = NewEvent.RecordTypeId,
                    Start__c = newEvent.StartDateTime,
                    Assigned_to__c = newEvent.OwnerId,
                  
                    Created_by__c = newEvent.CreatedById,
                    Opportunity_Link__c = 'https://superannuationproperty.my.salesforce.com/' + newEvent.WhatId, 
                    Appointment_Successful__c = newEvent.Appointment_Successful__c,
                    Appointment_Unsuccessful__c = newEvent.Appointment_Unsuccessful__c,
                    Related_to__c = newEvent.WhatId,
                    
                    Location__c = newEvent.Location,
                    End__c = newEvent.EndDateTime,
                    Description__c = newEvent.Description,
                  
                    Subject__c = newEvent.Subject,
                    Detail_link__c = 'https://superannuationproperty.my.salesforce.com/' + newEvent.Id ));   
         
         
   insert t1;
 }
 }
User-added image
What I understand is that becuase I haven't selected any opportunity or contact it is giving me error. Is there any way to avoid this for recurring events or any other ideas welcome.

Thanks 
  • January 30, 2015
  • Like
  • 0

Hi,

 

I am getting the below error when trying to persist data. Not sure what this is. Has anyone faced this kind of issue?

 

 java.sql.SQLException: ORA-20000: 
ORA-06512: at "DOC.SIMPORTLOOKUP", line 850
ORA-06512: at "DOC.SIMPORTLOOKUP", line 823
ORA-06512: at line 1


SQLException while executing plsql statement: {call sImportLookup.get_by_ext_id_text

Hi,

We have built a .NET to Salesforce Integration, and .NET Client keeps sending Data to Salesforce via Custom Webservice written in Apex. (Endpoint is dynamically generated after Login call). 

 

We use the Partner WSDL to authenticate and dynamically generate the Endpoint URL. We store the Session ID and re-use it until it expires and then again relogin with credentials to get the New Session ID. 

 

The Integration was working fine for 3 months and all of sudden Salesforce Starting Rejecting the Sessions since last 1 week.

 

Not sure what has changed but this issue broke our integration and we are getting lot of complaints from users. 

 

Can you please shed some light on what might be the Issue?  I also have validated if "lock sessions to originating IP" is turned on and it is NOT. 

 

So we are now out of options. 

 

Thanks

Kartik.

Hello All,

 

Did anyone try to execute a batch Apex job immediately after a managed package is installed. 

 

Here is the requirement :

I have added the Timezones to the Custom Settings, It has more than 100 records. I want it to be pre-populated as soon as Managed Package is Installed, w/o the intervention of ISV Partner.

Hi,

I am builing a Integration with Salesforce and .NET application. I have created a WebService in Salesforce with a Wrapper of 4 List of Custom Objects, shown as Below - 

 

global class notificationService {
	
	global class errorOutput {
      webservice String errorMessage; 
      webservice boolean Success;    
     }
     
/* Global wrapper that contains list of locations, iservers, notifications, subscriptions
*/
    global class objectWrapper {
    	webservice List<Notification__c> notifications;
    	webservice List<Location__c> locations;
    	webservice List<IServer__c> iservers; 
    	webservice List<Subscription__c> subscriptions;
    } 

 

The Obejct Wrapper is populated at the .NET side and they can actually include 1000 of records in each custom object.

After they generate the Object Wrapper, they do a call to the 

 

webservice static errorOutput insertDataObjects(objectWrapper iObject) {

 I wanted to confirm that this is a single API Call to the Salesforce.

 

Any help in knowing the API Counts programatically is appreciated. 

 

Thanks

Kartik

Did anyone try to implement Generics in Apex Code?

Similar to java <T> type?

Can anyone please transform the below line in Apex? 

public static <T> NamedValue<T> create(String name, T value)

I might be stupid asking this question instead of using SObjectType but I wanted to confirm if this funtionality is totally present or if any limitations.

 

Thanks.

Kartik

 

Hello All,

 

I am kind of a stuck here. I am doing integration with an external System which have their REST Services defined. So in order to GET,POST to their services I am using the single EndPoint URL, building Http BODY through DOM classes and posting data.

 

But if I want to send multiple POSTS at a time, I need to send a Batch Http POST (content-type : multipart/mixed) to the external Service. I am not sure how to do it via APEX. 

 

If anyone out there did it, any direction is helpful. Appreciate it.

 

Thanks.

Kartik.

Hi,

I am trying to dynamically display the fields of a custom object in a list. for that I am using the concept of VF Dynamic Bindings.

<apex:repeat value="{!columnFieldsList}" var="flds">                 
 <apex:column > 
  <apex:facet name="header">   
 <apex:outputField value="{!l.loc[flds]}" style="width:30%;"/>                	
 </apex:column> 
</apex:repeat>

 This works fine for me, 

But now I want to extend this functionality by adding a command link on the reference fields. for that I have created a Wrapper class with a boolean value isReference and checking in the controller if the field is a Reference and setting boolean to true.

 

But in VF, I am not sure how to use the wrapper in the apex repeat statement for a dyamic binding.. Below is what I did and I am getting error

 

 

<apex:repeat value="{!columnFields}" var="flds">                 
 <apex:column > 
  <apex:commandLink value="{!l.loc[flds.ColumnFieldName]}" id="fieldname" action="{!navigatefield}" target="_blank" rendered="{!flds.isReference}">
               <apex:param name="FieldId" value="{!!l.loc[flds.ColumnFieldName]}" assignTo="{!fieldName}"/>  
   </apex:commandLink> 
<apex:outputField value="{!l.loc[flds.ColumnFieldName]}" style="width:30%;" rendered="{!NOT(flds.isReference}/>                	
 </apex:column> 
</apex:repeat>

 

 

Can anyone tell me or confirm if VF Bindings can be done using wrapper classes? or if there is roundabout for this problem?

 

Thanks

Kartik

 

 

 

Hi,

 

I have a situation here where the setter method is getting called after the action method is called in Visualforce when using actionsupport tag.

 

Here is the snippet of my VF code

 

 

<apex:column width="20%" >
                    <apex:facet name="header" >Field</apex:facet>
                      <apex:selectList value="{!mf.savedsearchfield.Label__c}" size="1" id="fieldslist" style="width:250px;border:{!savedfieldErr};">
                             <apex:selectOptions value="{!items}" id="fieldsOptions" ></apex:selectOptions>                                                    
                        <apex:actionSupport event="onchange" action="{!getchkLookup}" rerender="addfieldsBlock"> 
                        	<apex:param name="fieldLabel" value="{!mf.savedsearchfield.Label__c}" assignTo="{!fieldLabel}" />                                                                                     
                        </apex:actionSupport>                           
                      </apex:selectList>                                  
                                                 
                    <apex:outputPanel rendered="{!LEN(mf.errMessageFld)!=0}">                      
                     <div class="errorMsg"><strong>Error:</strong>&nbsp;{!mf.errMessageFld}</div>
                     </apex:outputPanel>
                  </apex:column> 
                 
                 <apex:column width="12%" >                
                    <apex:facet name="header">Operator</apex:facet>
                    <apex:inputField value="{!mf.savedsearchfield.Operator__c}" style="width:100px;"/>
                    <apex:outputPanel rendered="{!LEN(mf.errMessageOp)!=0}">                      
                     <div class="errorMsg"><strong>Error:</strong>&nbsp;{!mf.errMessageOp}</div>
                     </apex:outputPanel>
                 </apex:column>                 
                 
                 <apex:column width="20%" id="valuecolumn">                                     
                    <apex:facet name="header">Value</apex:facet>
                    <apex:inputField value="{!mf.savedsearchfield.DefaultValue__c}"  rendered="{!LEN(mf.errMessageVal)==0}"/>                    
                    <apex:commandButton value=".." action="{!getisLookup}" rendered="{!mf.isLookup}" id="lookupButton">
   <apex:actionSupport event="onclick" rerender="popup" immediate="true">                            
        <apex:param name="fieldLabel" value="{!mf.savedsearchfield.Label__c}" assignTo="{!fieldLabel}" /> 
  </apex:actionSupport>  

 Here are my action and setter methods - 

 

 

public String fieldLabel {
  	get {
  		return fieldLabel;  		
  	}
  	set {  		
  		fieldLabel = value;
  		system.debug('fieldLabel' + fieldLabel);
  	}
  }
  
  public PageReference getisLookup(){
  	
  	String fieldLabelName = Apexpages.currentPage().getParameters().get('fieldLabel');
  	system.debug('fieldLabelName ' + fieldLabelName);
  	if(fieldLabel != '' && fieldLabel != null){
  		system.debug('inside if islookup');
  		getchkLookup();
  		for(Integer i=0;i<wsavedsearchfields.size();i++){
  		if(fieldLabel == wsavedsearchfields[i].savedsearchfield.Label__c ){
  			if (wsavedsearchfields[i].isLookup)
  				isLookupfld = true;
  		}
  	 }
  	}
  	else {
  		system.debug('inside else islookup');  		
  		getchkLookup();
  		Integer lsize = wsavedsearchfields.size();
  		isLookupfld = false;
  		if(wsavedsearchfields[lsize-1].isLookup == true){
  				isLookupfld = true;
  		 }    	
  	}
   	return null;
  }

 

 

I am not sure if I need to do something else on actionSupport to invoke setter first and then action method. i am stuck on this for 2 days now, I am trying to get a parameter passed back to controller so that I can perform my login in controller.

 

Any help is appreciated. Thanks.

 

Here is my situation, 

 

I am writing a VF page which is very much similar to NEW EDIT Views.  Here a user can select a Field, and if field is a Picklist, a button shows up. When user clicks on that button, a picklist is displayed as checkboxes, which user can select.

 

I figured out how to display check boxes as popup and other stuff (thanks to TehNrD). I am now stuck figuring out how to find which row user is clicking, since I am using pageblock table to generate the search fields. 

 

IS there a way I can pass the parameter user selects from VF back to controller?? 

 

Here is my VF Code:

 

 

 <apex:PageBlockSection id="addfieldsBlock" title="Search Fields" columns="1" rendered="{!NOT(isReadonly)}" showheader="{!isAdvanced}">     
          <apex:outputPanel rendered="{!isAdvanced}">                         
          <apex:pageBlockTable id="fieldtable" value="{!wsavedsearchfields}" var="mf">
           <apex:facet name="footer">
               <apex:outputPanel >               
                    <apex:commandLink style="color:#015BA7;padding:3px 3px 3px 3px;" styleClass="listActionLink" value="Add Row" action="{!addrow}">
                    </apex:commandLink>|
                    <apex:commandLink style="color:#015BA7;padding:3px 3px 3px 3px;" styleClass="listActionLink" value="Remove Row"   action="{!removeRow}" >
                    </apex:commandLink>
             </apex:outputPanel>
             </apex:facet>
                 <apex:column width="20%" >
                    <apex:facet name="header" >Field</apex:facet>
                      <apex:selectList value="{!mf.savedsearchfield.Label__c}" size="1" id="fieldslist" style="width:250px;border:{!savedfieldErr};">
                             <apex:selectOptions value="{!items}" ></apex:selectOptions>                           
                        <apex:actionSupport event="onchange" action="{!getchkLookup}" rerender="addfieldsBlock">
                      		<apex:param name="fieldLabel" value="{!mf.savedsearchfield.Label__c}" assignTo="{!fieldLabel}"/>
                      	</apex:actionSupport>                       
                      </apex:selectList>
                                             
                    <apex:outputPanel rendered="{!LEN(mf.errMessageFld)!=0}">                      
                     <div class="errorMsg"><strong>Error:</strong>&nbsp;{!mf.errMessageFld}</div>
                     </apex:outputPanel>
                  </apex:column> 
                 
                 <apex:column width="12%" >                
                    <apex:facet name="header">Operator</apex:facet>
                    <apex:inputField value="{!mf.savedsearchfield.Operator__c}" style="width:100px;"/>
                    <apex:outputPanel rendered="{!LEN(mf.errMessageOp)!=0}">                      
                     <div class="errorMsg"><strong>Error:</strong>&nbsp;{!mf.errMessageOp}</div>
                     </apex:outputPanel>
                 </apex:column>                 
                 
                 <apex:column width="20%" id="valuecolumn">                 	                
                    <apex:facet name="header">Value</apex:facet>
                    <apex:inputField value="{!mf.savedsearchfield.DefaultValue__c}"  rendered="{!LEN(mf.errMessageVal)==0}"/>                    
                    <apex:commandButton value=".." action="{!getisLookup}" rendered="{!mf.isLookup}" id="lookupButton">
                    	<apex:actionSupport event="onclick" rerender="popup">
                    		<apex:param name="fieldLabel" value="{!mf.savedsearchfield.Label__c}" assignTo="{!fieldLabel}"/>
                    	</apex:actionSupport>	 
                   </apex:commandButton>
                    <apex:outputPanel rendered="{!LEN(mf.errMessageVal)!=0}">                      
                     <div class="errorMsg"><strong>Error:</strong>&nbsp;{!mf.errMessageVal}</div>
                     </apex:outputPanel>                                                  
                 </apex:column>                                                                  
              </apex:pageBlockTable>  
              </apex:outputPanel>           
       </apex:PageBlocksection> 
       
       <apex:pageblockSection showheader="false">
       <apex:outputPanel rendered="{!isLookupfld}" id="popup" styleClass="customPopup" layout="block">
            <apex:outputPanel >            
            	<div class="heading"><strong>Please select a value:</strong></div>
                <apex:selectCheckboxes value="{!selPicklist}" layout="pageDirection">
					<apex:selectOptions value="{!picklistoptions}"/>									        	
        		</apex:selectCheckboxes>  
        		<apex:commandButton action="{!addList}" value="Insert"/>
        		<apex:commandButton action="{!returnList}" value="Cancel"/>        		      		                	        					             
            </apex:outputPanel>       				             
      </apex:outputPanel>           
      </apex:pageblockSection> 

Controller is :

 

Here is my Controller :
public PageReference getchkLookup() {
  	 		
  		String objectname = selobjectname;
        String locationfield;
        Map<String, String> picklists = new Map<String, String>();        
        picklistoptions = new List<SelectOption>();
        Set<String> picklistlabels = new Set<String>();
        Integer lsize = wsavedsearchfields.size();
        system.debug('field name' + fieldlabel);
        
        locationfield = Apexpages.CurrentPage().getParameters().get('fieldLabel');
        
        system.debug('field name' + locationfield);
        
        for(Integer i=0;i<wsavedsearchfields.size();i++){
          locationfield = fieldValueLabels.get(fieldLabel);
          if(fieldpicklists.containsKey(locationfield)) {
        	if(fieldLabel == wsavedsearchfields[i].savedsearchfield.Label__c) {
        			wsavedsearchfields[i].isLookup = true;        			
        			picklists = fieldpicklists.get(locationfield);        			
        			picklistlabels = picklists.keyset();        			
        			for(String s: picklistlabels){
        				picklistoptions.add(new Selectoption(s,picklists.get(s)));
        				
        			}        			
        		}else {
        			wsavedsearchfields[i].isLookup = true;        			
        			picklists = fieldpicklists.get(locationfield);        			
        			picklistlabels = picklists.keyset();        			
        			for(String s: picklistlabels){
        				picklistoptions.add(new Selectoption(s,picklists.get(s)));
        				wsavedsearchfields[i].lookupvalues.add(picklists.get(s));
        			}
        	 }
        	} else
        		wsavedsearchfields[i].isLookup = false;
        }
        
  	return null;	
  }
    
  
  public List<SelectOption> getpicklistoptions(){
  	return picklistoptions;
  }
  
  public String[] selPicklist{ 
  	get {
  		List<String> selPicklist = new List<String>();
  		List<SelectOption> sos = this.picklistoptions;
  		for(Selectoption s:sos){
  			if(selcheckboxString.contains(s.getValue()))
  			selPicklist.add(s.getValue());
  		}
  		return selPicklist;
  	}  	
  	set {
  		system.debug('Inside String');
  		String listValueconcat = '';
  		for(String s : value){
  			if(listValueconcat=='')
  			listValueconcat += s;
  			else
  			listValueconcat += ';' + s;
  		}
  		selcheckboxString = listValueconcat;   		
  	}
  	
  }
  
  public void getisLookup(){
  	
  	Integer lsize = wsavedsearchfields.size();
  	isLookupfld = false;
  	
  	
  	for(Integer i=0;i<wsavedsearchfields.size();i++){
  		if(fieldLabel == wsavedsearchfields[i].savedsearchfield.Label__c ){
  			if (wsavedsearchfields[i].isLookup)
  				isLookupfld = true;
  		}
  	}
  	
  }

 

 


 

 

 

Any help is appreciated.

 

Thanks

Kartik 

Is there a way to get the API field name via Dynamic Bindings in Visualforce? I am able to get the Label, but its not allowing me to get the actual API Name. 

 

I need this to dynamically list columns on VF Page and allow them to toggle a Sort.

 

Below is code snippet: One in red is giving me error. 

 

 

 <apex:repeat value="{!columnFieldsList}" var="flds">                 
<apex:column > 
   <apex:facet name="header">
<apex:commandLink action="{!toggleSort}" value="{!$ObjectType.Location__c.Fields[flds].Label}" rerender="locationdata">
<apex:param name="sortField" value="{!$ObjectType.Location__c.Fields[flds]}" assignTo="{!sortField}"/>
</apex:commandLink>
</apex:facet> 
<apex:outputField value="{!l.loc[flds]}" style="width:30%;"/>
</apex:column> 
</apex:repeat>

Does anyone know how to search all fields in an Object for a given String using SOQL? I know we can do it in SOSL using IN ALL FIELDS, but since I am doing a search only on one object, was wondering if there is a way to do it via SOQL?

 

Appreciate your response.

 

Thanks.

Kartik

Hi.

 

I am trying to save a record into a custom object from a picklist that I generated for a list of fields. When i try to click the save action, the picklist is resetting and I am not able to get the value from selected picklist. Please let me know what is that I am doing wrong with the code. 

<apex:page controller="testobjfields">
   <apex:form>
   <apex:pageBlock>
   <apex:commandButton value="Save" action="{!save}" />
   <apex:PageBlockSection columns="3" >     
               
            <apex:pageBlockSectionItem >                  
                <apex:outputPanel layout="block" styleClass="requiredInput" >
                <apex:outputPanel layout="block" styleClass="requiredBlock" />  
                  <apex:SelectList value="{!savedsearchFields.Fieldname__c}" size="1" >
                     <apex:selectOptions value="{!objfields}"></apex:selectOptions>

                  </apex:SelectList>
                </apex:outputPanel>            
             </apex:pageBlockSectionItem>
     
         <apex:pageBlockSectionItem >
            <apex:outputPanel layout="block" styleClass="requiredInput" >
            <apex:outputPanel layout="block" styleClass="requiredBlock" />  
               <apex:inputField value="{!savedsearchFields.Operator__c}" style="border:{!nameErr};"/>
            </apex:outputPanel>
         </apex:pageBlockSectionItem>
       
         <apex:pageBlockSectionItem >
           <apex:outputPanel layout="block" styleClass="requiredInput" >
            <apex:outputPanel layout="block" styleClass="requiredBlock" />  
               <apex:inputField value="{!savedsearchFields.DefaultValue__c}" style="border:{!nameErr};"/>
            </apex:outputPanel>
          </apex:pageBlockSectionItem>
           
                
       </apex:PageBlocksection> 
       </apex:pageBlock>
       </apex:form>
</apex:page>

 My controller is 

 

public with sharing class testobjfields{

    public SavedSearchField__c savedsearchfields{get;set;} 
    
    public List<SavedSearchField__c> multisavedfields{get;set;} 
    
    public String listObject{get;set;}
    public String fieldname{get;set;}
    
    //CSS error formatting vars
    
     public string nameErr{get;set{this.nameErr=value;}}
    public string visibilityErr{get;set{this.visibilityErr=value;}}
    
    public testObjfields() {   
     
   // initialize the objects for inserts

        savedsearchFields = new SavedSearchField__c();
     
        multisavedfields = new List<SavedSearchField__c>();
        multisavedfields.add(new SavedSearchField__c());        
        
          }
    
        
        
   
    public void addrow(){
        system.debug('Fieldname: ' + savedsearchFields.name);
        multisavedfields.add(savedsearchFields);
        
       }
        
    public PageReference save() { 

        try {
       insert savedSearchFields;
       system.debug('fieldname' + savedsearchfields.fieldname__c);
       system.debug('operator' + savedsearchfields.operator__c);
       /*  for (Integer i = 0 ; i<multisavedfields.size(); i++) {
        multisavedfields[i].SavedSearch__c = selectedsearch.Id;
        system.debug('Field Name' + multisavedfields[i].Name);
         }
         insert multisavedfields;
      
      /*   selectedList.addAll(selectedNames);
         for (Integer i = 0 ; i<selectedList.size(); i++) {
           system.debug('selected' + selectedList[i]);  
           SavedSearchColumn__c savedColumn = new SavedSearchColumn__c();
           savedColumn.name = selectedList[i];
           savedColumn.SequenceNumber__c = i;
           savedColumn.SavedSearch__c = selectedsearch.Id;
           multisavedcolumns.add(savedColumn);       
         }
        insert multisavedcolumns; */
       
        }
        catch(Exception e){
        system.debug('No record inserted');
        
        return null;
        }
        return null;}
    
     
    public List<SelectOption> getObjfields() { 
   
      List<SelectOption>  options = new List<SelectOption>();
       options.add(new SelectOption('','--Select Field --'));
        Map<String, Schema.SobjectField> fields =
        Schema.SobjectType.Location__c.fields.getMap();
        for (String s : fields.keySet()) {
            Schema.SobjectField so = fields.get(s);
            DescribeFieldResult f = so.getDescribe();
            if (s != 'Name') { // name is always displayed       
            options.add(new SelectOption('',f.getlabel())); 
        }
    }
            return options;
 }  
         
 }

 Any help is appreciated. 

 

Thanks.

Kartik

 

 

 

Hi,

I am trying to create a visualforce page that is pretty much similar to the List View Edit / New page.  Are there any examples for the Visualforce View Pages that I can refer to.?

 

Appreciate the responses

 

Thanks.

kartik

Hello,

 

I have a requirement where I need to display the columns seleted / defined for a particular listview in a custom visualforce page. 

I know that there is a property ListView. Columns in Metadata API for Salesforce, but I am not sure on how to use it in APEX Code.

Can anyone please help me with regard to this ?? Any examples on how to use this are appreciated.

 

Thanks.

Kartik

Hello,

 

I am calling APEX Webservice from .NET to do some updates to the Custom Objects. I am trying to do some API count reports and I see that the client id is blank on the WS calls from .NET. 

Is there a way I can set the client ID to some meaningful value so that I know for fact that the WS i am invoking is causing the API count.

 

Appreciate your response.

Hello,

I wrote a Http class to test the callout to the REST WS written .NET. I tried to run in different ways but I am not able to get the proper response back. Now I am getting a Media type error. Can anyone pls help if they had the similar issue in the past. 

Below is my Http Class.

 

public String getLocationStatus() { 
   String result = ' ';
   HttpRequest httpreq = new HttpRequest();
   httpreq.setMethod('GET');
   httpreq.setHeader('Content-Type', 'application/atom+xml;charset=utf-8'); 
   
   httpreq.setEndpoint('XXXXXXXXXX');
   
 
   Http http = new Http();
      HTTPResponse response = http.send(httpreq);
      result = response.getBody(); 
      system.debug(response.getBody());
      return result;
     }
The error I am getting is 
08:18:27.044|CALLOUT_REQUEST|[71]|System.HttpRequest[Endpoint=XXXXXXXX, Method=GET] 08:18:27.439|CALLOUT_RESPONSE|[71]|System.HttpResponse[Status=Bad Request, StatusCode=400] 08:18:27.439|METHOD_EXIT|[71]|System.Http.send(APEX_OBJECT) 08:18:27.439|METHOD_ENTRY|[72]|System.HttpResponse.getBody() 08:18:27.439|METHOD_EXIT|[72]|System.HttpResponse.getBody() 08:18:27.439|METHOD_ENTRY|[73]|System.debug(ANY) 08:18:27.439|METHOD_ENTRY|[73]|System.HttpResponse.getBody() 08:18:27.439|METHOD_EXIT|[73]|System.HttpResponse.getBody() 08:18:27.439|USER_DEBUG|[73]|DEBUG|<?xml version="1.0" encoding="utf-8" standalone="yes"?> <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code></code> <message xml:lang="en-US">Media type requires a '/' character.</message> </error>
Not sure what that means, I tried using all content types.
Please help.

 

Hello,

 

I am wondering if we can convert the SOAP WS written in APEX to REST based? What are steps in doing it? Do I need to change the Integration logic also written in .NET? 

 

Here is my APEX Class - 

 

 

global class putLocationId {
  webservice String City;
  webservice String State;
  
  global class LocationInput {
    webservice String GUID; 
    webservice String locationinfo;
    webservice String LocationId;
    }
 global class LocationOutput {
    webservice String errorMessage; 
    webservice boolean Success;
    // webservice List<LocationInput> vlocationinfo;    
    }
  webservice static LocationOutput createLocationws(List<LocationInput> vlocationinfo) {
     
     integer newcount = 0;
     List<Location__c> newloc = new List<Location__c>();
     for (integer i = 0; i < vlocationinfo.size() ; i++) {
     Location__c l = new Location__c();
     l.Location_ID__c = vlocationinfo[i].GUID;
     l.Name__c = vlocationinfo[i].locationinfo;
     l.LocationIntStatusLastChanged__c = System.now();
     l.Current_Backlog_Minutes__c = 100;
     l.Postal_Code__c = '03801';
     newloc.add(l);
     newcount = newcount + 1;
     }
     insert newloc;
     system.debug(' the locations added:'  + newcount);   
     LocationOutput ops = new LocationOutput();
     ops.errorMessage = 'No Errors from this API';
     ops.success = true;
     return ops;
     
    }
}

 

 

Hi,
I have written a custom APEX WebService that I am trying to use in .NET. When I am trying to call a method using webservice, it is giving me a SOAP Header Exception,. Not sure what the exception means and please let me know if i am doing something wrong here. Appreciate your response.
APEX WS Class - 
global class putLocationId {
  webservice String City;
  webservice String State;
  
  global class LocationInput {
    webservice String GUID; 
    webservice String locationinfo;
    webservice String LocationId;
    }
 global class LocationOutput {
    webservice String errorMessage; 
    webservice boolean Success;
    }
  webservice static LocationOutput createLocationws(List<LocationInput> vlocationinfo) {
     
     integer newcount = 0;
     List<Location__c> newloc = new List<Location__c>();
     for (integer i = 0; i < vlocationinfo.size() ; i++) {
     Location__c l = new Location__c();
     l.Location_ID__c = vlocationinfo[i].GUID;
     l.Name__c = vlocationinfo[i].locationinfo;
     l.LocationIntStatusLastChanged__c = System.now();
     l.Current_Backlog_Minutes__c = 100;
     l.Postal_Code__c = '03801';
     newloc.add(l);
     newcount = newcount + 1;
     }
     insert newloc;
     system.debug(' the locations added:'  + newcount);   
     LocationOutput ops = new LocationOutput();
     ops.errorMessage = 'No Errors from this API';
     ops.success = true;
     return ops;
     
    }
}
.NET Code calling this WS is 
            SforceService sforceService = new SforceService();
            LoginResult loginResult = putLocationIdService.login("xxxxxx", "xxxxxxx");
            putLocationIdService locService = new putLocationIdService();
            putLocationId.SessionHeader header = new putLocationId.SessionHeader();
            enterprise.SessionHeader header1 = new enterprise.SessionHeader();
            locService.SessionHeaderValue = header;
            header.sessionId = loginResult.sessionId;
            locService.Url = loginResult.serverUrl;
            try
            {
                LocationInput input1 = new LocationInput();
                input1.GUID = "10101010";
                input1.LocationId = "L1500";
                input1.locationinfo = "Test Location 1";
                LocationInput input2 = new LocationInput();
                input2.GUID = "20202020";
                input2.LocationId = "L2500";
                input2.locationinfo = "Test Location 2";
                LocationInput[] array1 = { input1, input2 };
                LocationOutput output1 = new LocationOutput();
                output1 = locService.createLocationws(array1);
                String error1 = output1.errorMessage;
                System.Console.WriteLine(error1);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
            }
        }

 

 

Hello,
I am trying to write a APEX Webservice that will be called from .NET. Before trying to use it at NET i wanted to test the WS Class I wrote in the APEX using a test class. Does anyone have examples of any test classes to test the APEX Web services?
Appreciate your response.

Hi.

 

I am trying to save a record into a custom object from a picklist that I generated for a list of fields. When i try to click the save action, the picklist is resetting and I am not able to get the value from selected picklist. Please let me know what is that I am doing wrong with the code. 

<apex:page controller="testobjfields">
   <apex:form>
   <apex:pageBlock>
   <apex:commandButton value="Save" action="{!save}" />
   <apex:PageBlockSection columns="3" >     
               
            <apex:pageBlockSectionItem >                  
                <apex:outputPanel layout="block" styleClass="requiredInput" >
                <apex:outputPanel layout="block" styleClass="requiredBlock" />  
                  <apex:SelectList value="{!savedsearchFields.Fieldname__c}" size="1" >
                     <apex:selectOptions value="{!objfields}"></apex:selectOptions>

                  </apex:SelectList>
                </apex:outputPanel>            
             </apex:pageBlockSectionItem>
     
         <apex:pageBlockSectionItem >
            <apex:outputPanel layout="block" styleClass="requiredInput" >
            <apex:outputPanel layout="block" styleClass="requiredBlock" />  
               <apex:inputField value="{!savedsearchFields.Operator__c}" style="border:{!nameErr};"/>
            </apex:outputPanel>
         </apex:pageBlockSectionItem>
       
         <apex:pageBlockSectionItem >
           <apex:outputPanel layout="block" styleClass="requiredInput" >
            <apex:outputPanel layout="block" styleClass="requiredBlock" />  
               <apex:inputField value="{!savedsearchFields.DefaultValue__c}" style="border:{!nameErr};"/>
            </apex:outputPanel>
          </apex:pageBlockSectionItem>
           
                
       </apex:PageBlocksection> 
       </apex:pageBlock>
       </apex:form>
</apex:page>

 My controller is 

 

public with sharing class testobjfields{

    public SavedSearchField__c savedsearchfields{get;set;} 
    
    public List<SavedSearchField__c> multisavedfields{get;set;} 
    
    public String listObject{get;set;}
    public String fieldname{get;set;}
    
    //CSS error formatting vars
    
     public string nameErr{get;set{this.nameErr=value;}}
    public string visibilityErr{get;set{this.visibilityErr=value;}}
    
    public testObjfields() {   
     
   // initialize the objects for inserts

        savedsearchFields = new SavedSearchField__c();
     
        multisavedfields = new List<SavedSearchField__c>();
        multisavedfields.add(new SavedSearchField__c());        
        
          }
    
        
        
   
    public void addrow(){
        system.debug('Fieldname: ' + savedsearchFields.name);
        multisavedfields.add(savedsearchFields);
        
       }
        
    public PageReference save() { 

        try {
       insert savedSearchFields;
       system.debug('fieldname' + savedsearchfields.fieldname__c);
       system.debug('operator' + savedsearchfields.operator__c);
       /*  for (Integer i = 0 ; i<multisavedfields.size(); i++) {
        multisavedfields[i].SavedSearch__c = selectedsearch.Id;
        system.debug('Field Name' + multisavedfields[i].Name);
         }
         insert multisavedfields;
      
      /*   selectedList.addAll(selectedNames);
         for (Integer i = 0 ; i<selectedList.size(); i++) {
           system.debug('selected' + selectedList[i]);  
           SavedSearchColumn__c savedColumn = new SavedSearchColumn__c();
           savedColumn.name = selectedList[i];
           savedColumn.SequenceNumber__c = i;
           savedColumn.SavedSearch__c = selectedsearch.Id;
           multisavedcolumns.add(savedColumn);       
         }
        insert multisavedcolumns; */
       
        }
        catch(Exception e){
        system.debug('No record inserted');
        
        return null;
        }
        return null;}
    
     
    public List<SelectOption> getObjfields() { 
   
      List<SelectOption>  options = new List<SelectOption>();
       options.add(new SelectOption('','--Select Field --'));
        Map<String, Schema.SobjectField> fields =
        Schema.SobjectType.Location__c.fields.getMap();
        for (String s : fields.keySet()) {
            Schema.SobjectField so = fields.get(s);
            DescribeFieldResult f = so.getDescribe();
            if (s != 'Name') { // name is always displayed       
            options.add(new SelectOption('',f.getlabel())); 
        }
    }
            return options;
 }  
         
 }

 Any help is appreciated. 

 

Thanks.

Kartik

 

 

 

Hello All,

Please help me.
I am trying to integrate salesforce with external web app (Gliffy) using API.
I am done with Oauth 1.0 oauth_signature generation and header creation for the authentication of external system but when I pass those parameters to request token I am getting this error in response.

I have created self-signed certificate in salesforce but I cann't install that on Gliffy server.
So I am unable to find out solution on this.

let me know if anyone have solution for this.

 
Hi every body,

I want to display Record Type in Visualforce page. But how, i tried this but it doen`t work.
User-added image

My Code:
<apex:page standardController="Project_Task__c" extensions="projectTaskController" action="{!runSearch}" showHeader="false" standardStylesheets="true" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0" >
  <apex:form >
  <apex:pageMessages id="errors" />
  <apex:pageBlock title="Find Project Task" mode="edit">
  <apex:pageBlockButtons location="top">
    <apex:commandButton value="New Project Task " action="{!create}"/>
  </apex:pageBlockButtons>
  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">
      <apex:pageBlock title="Parameters" mode="edit" id="criteria">
      <script type="text/javascript">
          function doSearch() {
            searchServer(
              document.getElementById("ProjectTaskName").value,
              document.getElementById("LeaveType").options[document.getElementById("LeaveType").selectedIndex].value);
          }
      </script> 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
           <apex:param name="ProjectTaskName" value="" />
           <apex:param name="LeaveType" value="" />
      </apex:actionFunction>
      <table cellpadding="2" cellspacing="2">
       <tr>
       <td style="font-weight:bold;">Project Task Name<br/>
        <input type="text" id="ProjectTaskName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Leave Type<br/>
          <select id="LeaveType" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!LeaveType}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>
      </apex:pageBlock>
    </td>
    <td valign="top">
    <apex:pageBlock mode="edit" id="results">
        <apex:pageBlockTable value="{!projectTask}" var="pt">
		<apex:column headerValue="Action" style="float:right;width:90%">
            <apex:outputLink style="Color:blue" value="{!URLFOR($Action.Project_Task__c.Edit,pt.Id)}"> 
                Edit 
            </apex:outputLink>     
         </apex:column> 
                  <!--<apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Code" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!pt.Name}"/>
            </apex:column>-->
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Project Task Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Project Name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!pt.Project_Task_Name__c}"/>
            </apex:column>
             <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Project Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Project Name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!pt.pro_has_many_protask__c}"/>
            </apex:column>
             <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Leave Type" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Leave Type" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!pt.Leave_Type__c}"/>
            </apex:column>
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Reccord Type" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Reccord Type" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!pt.RedordType}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
    </td>
  </tr>
  </table>
  </apex:pageBlock>
  </apex:form>
</apex:page>


 
Is it possible to query all knowledge articles through the rest API without needing an ID, versionid, FIND, or anything like that? I am setting up a site that needs to pull in all online public articles within a specific data category.

This SOSL query works, but it needs a "Find":
FIND {"faq"} IN ALL FIELDS 
RETURNING Support_Article__kav(id, articlenumber, Title, Summary, Full_Description__c, FirstPublishedDate,LastPublishedDate, VersionNumber,IsDeleted, IsVisibleInPkb
 where PublishStatus='Online' and Language='en_US' )
WITH Data Category Savant_Knowledge__c below Savant_Consumers__c
I also got this working, but still, it needs a search term:
/services/data/v34.0/search/?q=FIND+%7B%22faq%22%7D+IN+ALL+FIELDS+RETURNING+Support_Article__kav%28id%2carticlenumber%2cTitle%2cSummary%2cFull_Description__c%2cFirstPublishedDate,LastPublishedDate%2cVersionNumber,IsDeleted%2cIsVisibleInPkb+where+isVisibleinPKB+%3D+True+and+PublishStatus%3D%27ONLINE%27+and+Language%3D%27en_US%27%29+WITH+Data+Category+Savant_Knowledge__c+below+Savant_Consumers__c


I need to be able to run an API call that just returns all articles that meet the specific criteria. Is it possible?
 
I am having trouble combining the following 2 sets of SOQL Queries.  I cannot do a join because they are pulling from the same object.  Basically I need to combine
Select Owner.Name, Owner.ID, Calendar_Month(CloseDate), SUM(Amount)
From Opportunity
Where CloseDate=This_Year AND StageName='Closed/Won'
GROUP BY ROllup(Owner.Name, Owner.Id, Calendar_Month(CloseDate))
With
Select Owner.Name, Owner.ID, Owner.SmallPhotoUrl
From Opportunity
Where CloseDate=This_Year AND StageName='Closed/Won'

I also need to combine
Select COUNT(CaseNumber), Calendar_Month(CreatedDate)
From Case
Where CreatedDate=This_Year
GROUP BY Calendar_Month(CreatedDate)
with
Select COUNT(CaseNumber), Calendar_Month(ClosedDate)
From Case
Where         ClosedDate=This_Year
GROUP BY Calendar_Month(ClosedDate)
Greetings I was hopin anyone could shed some insight into what may be happenign here. We have a SFDC application wich integrates with a target system ( case management system) SFDC is passing the correct date stamp to the aformetioned, We have checked the SOOQL as well as WDSL xml and it is well formed and with the appropiate attribute data. No transformations take splace prior to this step in the process however we are getting the following error fromt he target system :

mesgCode=801, mesgDesc=800030:CSTK_LAST_UPD_DTM  can not be future ;

mesgCode=801, mesgDesc=888888:CSTK_RECD_DT  can not be future ; 

The target system is indicating the date being passed in future e.g. 2016.

Any assistance would be greatly appreciated
Regarding using SOQL to assign and retrieve attributes, I need identify the Postal Code of the Contact and I do not know how to name it?

Imagine I am having the following code:

Contact[] cts = [SELECT Contact.LastName, Contact.Postal_Code FROM Contact WHERE LastName =: sName OR PostalCode =: sPostalCode]; 
  
        System.debug('Last Name forund + cts[0].LastName);
        System.debug('PostalCode found' + cts[0].PostalCode);

The problem is that Contact.PostalCode can't be found and I do not know how to name it. 

Anyone can help me?

Thanks!

Bea
 
I am working on force.com site. i have a method which insert a record. user have all the permission CRUD and all fields are visible. when this method is called by commandlink it work. when call by any other method with in the class. site give autorisation error.
How can i Fix this. when i do this.
<!-- Visual force active site home page-->

<apex:page controller="tempcontroller">
<apex:commandbutton value ="insert" action="{!ins}">
</apex:page>


<!-- visual force controller--->

public with sharing tempcontroller{

tempcontroller(){

}
public void ins(){
 position__C pos = new postion__C(name'test');
inser pos;

}

}
the above code works fine but if i do following
 
<!-- Visual force active site home page-->

<apex:page controller="tempcontroller">
<p> this is a page</p>
</apex:page>


<!-- visual force controller--->

public with sharing tempcontroller{

tempcontroller(){

}
public void check(){
ins();

}
public void ins(){
 position__C pos = new postion__C(name'test');
inser pos;

}

}

this gives autorisation error . 
how can i solve this please help

 
Scenario : In the ListView of Invoice Download button is placed. This will Download the Invoice PDFif the invoice has notes and attachments else notes and attachments is null for the invoice then it will download another PDF which has some contents of the invoice.
Problem : I can able to download the corresponding PDF for single invoice selection on the List View. If I select Records(Multiple selection) with notes and attachments and without notes and attachments then it is downloading the INVOICE PDF only for both record.

Below is my Code
 
global class DownloadInvoice 
{

   private static String API_STATUS_NORMAL = '200';

   webService static string getAttachmentByParentId(string sfdcId)
    {

         List<id> ids = new List<id>();
         if(string.isempty(sfdcId))  {
            return DownloadInvoiceResponse.errorJson('Parameter sfdcId is required.');
        }
        system.debug('SFDCid'+sfdcId);
        string[] idsArray = sfdcId.split(',');
        for(integer i=0; i<idsArray.size();i++)
        {
           ids.add(idsArray[i]);
        }


        List<Invoice__c> invList = New List<Invoice__c>();
        invList = [Select id, name, Print_Invoice__c,Account__r.name from Invoice__c where ID IN: ids];

        List<Attachment> attInsert = new List<Attachment>();

        if(invList.size() > 0){

            for(Invoice__c invc : invList){

                String msg = 'Selected invoices are not eligible for Invoice Printing, please check the Account '+invc.Account__r.name;
                if(invc.Print_Invoice__c == false){

                    return DownloadInvoiceResponse.errorJson( msg );
                }
                Blob body;

       ****From here taking Attachment and adding the condition****

                Integer WithAttachCount = [SELECT count() FROM Attachment where ParentId IN:ids AND id !=null];

                if (WithAttachCount > 0){

                        PageReference pdf = new PageReference('/apex/InvoicePDF?id='+invc.id);

                        try {
                            if(Test.IsRunningTest()){
                                System.debug(' ==> as Test Class <== ');
                                body = Blob.valueOf('Some Text');
                            }
                            else{
                                System.debug(' ==> as Apex normal Class <== ');
                                body = pdf.getContentAsPDF(); 
                                Attachment attach = new Attachment(); 
                                attach.Body = body;
                                attach.name= invc.name +'_Invoice_'+ Datetime.Now() +'.PDF';
                                attach.IsPrivate = false;
                                attach.ParentId = invc.id;
                                attach.contentType = 'application/pdf';
                                attInsert.add(attach); 
                           }
                         } 
                        catch (VisualforceException e) {
                                String msg2 = e.getMessage();
                                return DownloadInvoiceResponse.errorJson( msg2 );
                           }

                        }

                 if(WithAttachCount <= 0 || WithAttachCount == null){

                        PageReference pdff = new PageReference('/apex/InvoicesIfAttachIsNull?id='+invc.id); 
                        try {
                             if(Test.IsRunningTest()){
                             body = Blob.valueOf('Some Text');
                            }
                        else{
                            System.debug(' ==> as Apex normal Class <== ');
                            body = pdff.getContentAsPDF();
                            Attachment attach = new Attachment(); 
                            attach.Body = body;
                            attach.name= invc.name +'_Invoice_'+ Datetime.Now() +'.PDF';
                            attach.IsPrivate = false;
                            attach.ParentId = invc.id;
                            attach.contentType = 'application/pdf';
                            attInsert.add(attach);   
                            }
                         } 
                        catch (VisualforceException e) {
                            String msg2 = e.getMessage();
                            return DownloadInvoiceResponse.errorJson( msg2 );
                           }
                       }                               
                    }       
                }    

        Insert attInsert;

        integer totalSizeOfFiles=0;
        integer totalSizeAnInvoice=0;
        String invoiceId='';
        set<String> remainingsIdsSet=new set<String>();
        List<attachment> attachmentList = new List<attachment>();
          //for(attachment att:[select ParentId,id,Name,Body,contenttype from attachment where ParentId IN:ids]) {
          for(attachment att: attInsert) {          
                integer eachFileSize=att.Body.size();
                String parentId=att.ParentId;
                att.contenttype='application/pdf';
                if(!invoiceId.equals(parentId)){
                    invoiceId=parentId;
                    totalSizeAnInvoice=eachFileSize;
                    System.debug('--ID: '+att.id+'. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalInvoiceSize: '+totalSizeAnInvoice);
                }else if(invoiceId.equals(parentId)){
                    totalSizeAnInvoice=totalSizeAnInvoice+eachFileSize;
                    System.debug('--ID: '+att.id+'. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalInvoiceSize: '+totalSizeAnInvoice);
                }
                if(eachFileSize<4500000 && totalSizeAnInvoice<4500000){
                    totalSizeOfFiles=totalSizeOfFiles+eachFileSize;
                    System.debug('--ID: '+parentId+'. FileSize: '+eachFileSize+'. TotalFileSize: '+totalSizeOfFiles+'. HeapSize: '+Limits.getHeapSize());
                    if(totalSizeOfFiles>= 4500000){
                          System.debug('--Adding to RemIDs ID: '+parentId+'. FileSize: '+eachFileSize);
                          remainingsIdsSet.add(parentId);
                     }else{
                          attachmentList.add(att);                      
                     }
                 }
           }
             String remainingIds=null;
             List<String> remainingIdList=new List<String>(remainingsIdsSet);
             for(integer i=0;i<remainingIdList.size();i++){
                 if(i==0){
                     remainingIds=remainingIdList.get(i);
                 }else{
                     remainingIds=remainingIds+','+remainingIdList.get(i);
                  }                 
             }

             List<Object> dataList = new List<Object>();
             for(Attachment at :attachmentList)
             {
                Map<String, String> atMap = new Map<String, String>();
                atMap.put( 'Name', at.Name );
                atMap.put( 'Body', EncodingUtil.base64Encode( at.body ));
                datalist.add( atMap );

             }

                 Map<String, Object> response = new Map<String, Object>();
                 response.put('status', API_STATUS_NORMAL);
                 if( datalist != null ){
                     response.put('data',datalist);
                     response.put('id', remainingIds);
                 }
                 return json.serialize( response );
          }                      

     }
}

How to deal with multiple selection of records with notes and attachments and without notes and attachments. Any help is appreciable. Thanks
I need help with the following code, I need latitude and longitude information using google map API javascript in visualforce Page and I have embedd this visualforce Page in account page in account detiail section. The Problem is when I upload the data using data loader the Lat/longitude are not coming. WHat to do with that?

<apex:page standardController="Account">
<apex:pageBlock >
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script src="/soap/ajax/27.0/connection.js" type="text/javascript"/>
<script type="text/javascript"> 
$(document).ready(function() {
  var myOptions = {
    zoom: 20,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    mapTypeControl: true
  }
  var map;
  var marker;
  var of;
  var of1;
  var geocoder = new google.maps.Geocoder();
  var address = "{!Account.ShippingStreet}, " + "{!Account.ShippingCity}, " + "{!Account.ShippingPostalcode}";
  var infowindow = new google.maps.InfoWindow({
    content: "<b>{!Account.Name}</b>"
  });
  geocoder.geocode( { address: address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      
        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);
        //center map
        map.setCenter(results[0].geometry.location);
        
        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,    
            title: "{!Account.Name}"
        });
        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition()); 
        });
      }
       
    } else {
      $('#map').css({'height' : '15px'});
      $('#map').html("Oops! {!Account.Name}'s address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  of= results[0].geometry.location.lat();
            of1 = results[0].geometry.location.lng();  
               
             var mappedContact = new sforce.SObject('Account');  
          mappedContact.ShippingLatitude  = of; 
          mappedContact.ShippingLongitude = of1; 
      mappedContact.Id="{!Account.Id}";    
         result = sforce.connection.update([mappedContact]);  
  });
  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";  }
    } } 
});       
</script>
<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:500px;
  background:transparent;
}
</style>
</head>
<body>
<div id="map"></div> 
</body> 
</apex:pageBlock>
</apex:page>
HI All,

We have created a Mobile Hybrid App,whenrin we  are making ajax callout from Mobile to salesforce Rest resource/
I am bale to connect from workbench,postman,Java App,Android App However when trying to connect from the hybrid app getting the 
CORS error.I did try putting the Source IP address from where callout is being made (IN CORS seeting) but no sucess.
It would be verymuch helpfull if you can share your insights on the same !!

Thanks Much,
Mahesh Patel
 
Hi all, 

I would like to find which custom lable is mapped with VF page or apex class in my Salesforce environment. I would like to know if any easy way to find this. Any suggesstions is much appreciated.

Total Custom lable count : 1000 or more than that. In that some custom lable might not used in either VF or apex class.
Hello,

An application is to be developed to allow information to be submitted to Salesforce from a public website.  Public users will not have Salesforce credentials.  What's the best way to achieve authentication for Rest API access?

I can see in the Force.com Rest API Developer's Guide that there is a username/password OAuth authentication flow.Are there any security drawbacks with this?
Would you normally set up a user specifically for this purpose, which will never be used by a real person, rather than using a 'real person' user, whose password may/should change at some point?
Any other suggestions?

Many Thanks,
Mike.
Hi,

  I need a suggestion in my organization code coverage is only 46% please advice me how to increase the percentage. right now not able to right any code and deploye it to production.

Thanks
Sudhir
Hello,
I wonder if anyone can help please? My knowledge of Apex is extremely limited. In our Salesforce we have a Visualforce page that places text at the top of the Opportunity page. In this order: Stage ¦ Grant Amount/Paid Amount ¦ Decision Date - it works fine except the text on the right hand side (Decision Date) sometimes is 'pushed down' to a new line on the left side of the page. Is there away of 'right aligning' this field so that it is always right-aligned on the same line as the other fields? The code is below.

Many thanks, Rob

<apex:page standardController="Opportunity"> <script> function reload(){ window.setTimeout('window.location.reload(true);',5); } </script> <div> <span style="color:#a52a2a;font-size:125%;font-weight:bold;padding-left:42px;"> <apex:outputField value=" {!opportunity.StageName}"/></span> <span style="color:#2a2aa5;text-align:center;font-size:125%;font-weight:bold;padding-left:30%;padding-right:30%;">Grant:&nbsp;<apex:outputField value=" {!opportunity.Grant_Amount__c}"/> / Paid &nbsp;<apex:outputField value=" {!opportunity.Total_Paid__c}"/></span> <span style="color:#259125;text-align:left;font-size:125%;font-weight:bold;padding-left:42px;"> <apex:outputField value="{!opportunity.Charity__c}"/></span> </div> <apex:detail subject="{!Opportunity.Id}" relatedList="true" title="true" inlineEdit="true" oncomplete="reload()"/> </apex:page>
 
L.S.,

I'm quite new to this, so could be that I'm missing something.

I've tried to embed a Flow in a Visualforce page and include that page in a Chatter Quick action. This works fine. However, I also want the page to refresh automatically after the Flow is finished. I've let the Visualforce page set the retURL to another page that refreshes the browser. This refresh Visualforce page redirects the user to the Home page.

How can I refresh the page and direct the user to same (updated) record? For clarity, please find the explanation of the setup below.

Thanks in advance for your help.

I've embedded the Flow in a Visualforce page which is launched via the Chatter Quick Action.
<apex:page standardController="Lead" Showchat="False">
<apex:outputPanel layout="block" style="overflow:auto;width:100%;height:600px" >
<flow:interview name="Qualification_Call" finishLocation="/{!$CurrentPage.parameters.id}">
    <apex:param name="varLeadID" value="{!Lead.Id}"/>
    <apex:param name="varUserID" value="{!$User.Id}"/>
</flow:interview>
</apex:OutputPanel>
</apex:page>
This refreshes the Lead in the Visualforce page rather than the full window. I've tried redirecting the page to a separate Visualforce page that should do the refresh, but as said above this redirects to the Homepage.
<apex:page standardController="Lead">
 <script>
    window.top.location='/{!lead.id}';
 </script>
</apex:page>


 
Hi,

I have created one visualforce component to show data from Account object and a custom object CS. Like for one Account, there can be more than one CS object records and I want to show this data in tabular form but I am not getting the data on VF page through which I am calling this component. 
I have created a Map<Id, List<Custom_Object__c>> mapAcc to get the data in the controller but this is not retrieving data on the VF page. 


 
I follwoed the instructions found here:  http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/  which are pretty straight forward to try to override the standard lookup functionality.  I implemented this within my apex component and it is never getting inside the function openLookup that I have defined within my component.  Is there anything that would need ot be done differently when called from a component vs a VF page?
I have a javascript button I am trying to create to update a picklist field on a custom object.  Here is the code for the button:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var p = new sforce.SObject('Projects__c');
p.id = "{Projects__c.Id}";
p.Status__c = "Closed";
result = sforce.connection.update([p]);
location.reload(true);

The code is not throwing errors on the object it is just not updating the field.  The page is reloading. Anything wrong with the code?

  • January 06, 2014
  • Like
  • 2
I have a method intended to generate an email with a users login credentials with a button click.  I used to have it pulling the information off a custom object but am now trying to consolidate with just the standard Contact object, but now in my tests it throws an error in execution.  My code is:
public with sharing class CM_InfoController{

        private static String ORG_WIDE_EMAIL_ADDRESS = 'customerservice@maximusautogroup.com';
               
        public Contact user    {get;set;}
        private static ID orgWideEmailId = [SELECT id FROM OrgWideEmailAddress WHERE address=:ORG_WIDE_EMAIL_ADDRESS].id;
               
    public CM_InfoController(){
    }
   
    public CM_InfoController(ApexPages.StandardController controller){
       user = (Contact)controller.getRecord();
    }   
   
    public PageReference sendEmail(){
        PageReference pageReference = null;
        if(user != null){
                Contact nu = [SELECT Id, Name, Password__c, Email FROM Contact WHERE id=:user.id];
                if(orgWideEmailId != null){
                  // Build new URL
                  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                  String htmlBody = '<h1>MAG User Info Request</h1>' +
                  '<p>Dear ' + nu.Name + ',</p>' +
                  '<p>We have received your request for user credential information in order to access some restricted features of the Maximus Auto Group website.</p>' +
                  '<p>Your Username is: ' + nu.Email + '</p>' +
                  '<p>Your Password is: ' + nu.Password__c + '</p>' +
                  '<p>If you have any questions or concerns regarding this information, please contact one of our associates at 1-800-801-1342 and we will assist you, or reply to this email with any specific questions.</p>' +
                  '<p>Thank you for your business and continued support!</p>' +
                  '<p>MAXIMUS AUTO GROUP</p>';
                                                                      
                   //Build Email
                   mail.setOrgWideEmailAddressId(orgWideEmailId);             
                            String[] toAddresses = new String[]{nu.Email};                                              
                                            mail.setToAddresses(toAddresses);
                                            mail.setSubject('MAG User Access');
                                            mail.setHtmlBody(htmlBody);
                                            mail.setWhatId(user.id);
                                       
                                        Messaging.sendEmail(new Messaging.Email[]{mail},true);
                                                                                                           
                            ApexPages.Message msg = new ApexPages.Message( ApexPages.Severity.INFO, 'Message sent successfully');                  
                            ApexPages.addMessage(msg);                                                                                                 
                                        }
                                        else{
                            ApexPages.Message msg = new ApexPages.Message( ApexPages.Severity.ERROR, 'Org wide email address not found ['+ ORG_WIDE_EMAIL_ADDRESS + ']');                  
                            ApexPages.addMessage(msg);                                                             
                                        }                                                                                                     
                            }   
                                else{
                                ApexPages.Message msg = new ApexPages.Message( ApexPages.Severity.ERROR, 'Email not specified on user to send information.');                  
                                ApexPages.addMessage(msg);                                                             
                                }
                                return(pageReference);
                                }
                                }

And the error I encounter each time is: "First exception on row 0; first error: INVALID_ID_FIELD, Only accounts, assets, campaigns, cases, contracts, opportunities, orders, products, solutions and custom objects are allowed as whatId.: "  which is directed at the "mail.setWhatId(user.id);" line.  However, this was working properly with the custom object I used to have in place so I am unsure why this would suddenly not work when all I did to the code was change the object referenses from my custom one to the Contact one.
Hi All,

I have to integrate SF to Sqlserver dB .which way is best for Integration?

1)using to write  Webservices 2)using any Middleware appns & How to do this Integration?pls give some example


Thanks,

Vicky

I'm wondering if anyone else has had this experience or knows why it won't work.

 

I know Map.values() returns a list of objects in an arbitrary order. However, what I didn't know was that Visualforce can't understand this order.

 

I had a visualforce page that was showing a list of Accounts and some objects inside of them. For many reasons I was storing the Accounts in a Map grouped by their IDs and stored in a wrapper class.

 

Map<Id,AccountWrapper> AccountMap;

 

So in my getAccounts() Method I was just using this at the end:

return AccountMap.values();

 

But I was getting some very strange behavior when users made changes to the Account Wrapper and saved it.

 

Turns out sometimes it would save Account 1 data into the Account 2 wrapper object. 

 

I switched the end of the getAccounts method to the following:

 

AccountWrapper[] AccountList = AccountMap.values();
return AccountList;

 Now the AccountList always has the right values.

 

Does anyone know why maps cannot be sent directly to the page? Why can't Salesforce update map values?

 

Hi to everyone!!,

 

I´m trying to synchronize with an external system, and i´m using a @futre call from a trigger, i´m trying to make a logic for the respond of the external call. I can use a flag field ( boolean ) if the call out fails, so that way i will know that the record is not synchronize, and then make some logic with a button or with schedule class that recollect all these record and and attempts to synchronize again.

 

Is There another way to do this?.. Best Practice to do this?...

 

I will appreciated any answer... Thanks a lot.