Invalid field Email for SObject AggregateResult in VisualForce - salesforce

I want to display the AggregateResult on my Visualforce page but it is generating the following error " Invalid field Email for SObject AggregateResult"
Below is my code:
public with sharing class searchDuplicate {
public AggregateResult[] con{get;set;}
public searchDuplicate()
{
find();
}
public void find(){
con = [select Email from Contact group by Email having count(Email) > 1];
System.debug(con);
}
}
Below is my visualforce page code:
<apex:page controller="searchDuplicate">
<apex:pageBlock title="Searching for Duplicate Contacts Record">
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:dataTable value="{!con}" var="c" border="2" cellspacing="5" cellpadding="5">
<apex:column headerValue="Email" value="{!c['Email']}" />
</apex:dataTable>
</apex:pageBlock>
</apex:page>
kindly Make a correction if possible

public with sharing class searchDuplicate {
public list <con> conList{get;set;}
public class con{
public string Email {get;set;}
public con( string email){
this.Email = email;
}
}
public searchDuplicate()
{
find();
}
public void find(){
conList = new list <con>();
for( AggregateResult ar : [select Email from Contact group by Email having count(Email) > 1];){ conList.add(new con(string.valueOf(ar.get('Email')))) }
}
}

Aggregate results (and their fields/columns) come as generic Objects, not sObjects. Therefore there's no obj.get('somefieldname') you can call on them.
Your best option might be to make a helper class that has String email; Integer count; fields and loop through the query results populating a list of objects of this helper class.
You could also use Map<String, Integer> but that'd come to VF as not sorted alphabetically.
See https://salesforce.stackexchange.com/questions/7412/count-a-grouped-by-soql if you need a code sample.

Although the other answers are correct in solving your problem, what you have is actually a bug in SalesForce.
The way to resolve this without creating a custom object is to separate the into two - The "headerValue" and "value" both being set cause this error.
You want to change it to this:
<apex:dataTable value="{!con}" var="c" border="2" cellspacing="5" cellpadding="5">
<apex:column headerValue="Email" >
<apex:outputText>{!c['Email']}</apex:outputText>
</apex:column>
</apex:dataTable>
Thanks,
Michael

Related

How to show error message on Visualforce Page when create records based on Condition

Project Requirement:-create new record when candidate's PAN is not blacklisted, if it is blacklisted then show warning message on visualforce page and update new phone number in blacklisted candidate object.
Pre exquisite:- i have two object 1.Sudent_matster__c : Fields:- Name, Phone__c, PAN__c, email__c etc 2.Black_Listed_Candidate__c Fields:- Name, Phone__c, PAN__c etc
QUESTION When i enter blacklisted field PAN- FHSJF10387 then this code runs perfectly fine, but i enter another blacklisted field PAN- DKFIT8888S,CNYY78912Q, RYHJI997Q.etc. then code wont work. why? i think old value should be cleared from memory?
Visual force page IMAGE [This is visualforce page ][1] [1]: https://i.stack.imgur.com/aLzjo.png
VFP CODE
<apex:page Controller="Class_Practice">
<apex:form id="frm" html-autocomplete="off" style="border-style:solid;border-width:2px;border-color:black;background-color:lightyellow">
<H1 style="text-align:center;font-size:30px;">PAN DATA CHECK</H1>
<apex:pageBlock >
<apex:pageMessages></apex:pageMessages>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:inputField value="{!newStudent.Name}"/>
<apex:inputField value="{!newStudent.First_Name__c}"/>
<apex:inputField value="{!newStudent.Last_Name__c}"/>
<apex:inputField value="{!newStudent.Email__c}"/>
<apex:inputField value="{!newStudent.Phone__c}"/>
<apex:inputField value="{!newStudent.PAN__c}"/>
<Apex:commandButton value="Save" Action="{!MySave}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
APEX CLASS Code
public class Class_Practice
{
public Student_Master__c newStudent {get;set;}
Map<Id, string> IdAndBlackListPhoneMap = New Map<Id, string>();
public static list< Black_Listed_Candidate__c> blackList =[SELECT Name,PAN__c,Phone__c FROM Black_Listed_Candidate__c];
public Class_Practice()
{
newStudent = new Student_Master__c();
}
public pageReference MySave()
{
for(Black_Listed_Candidate__c bp:blacklist)
{
if (bp.PAN__c==newStudent.PAN__c )
{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'PAN is Black Listed'));
bp.Phone__c = newStudent.Phone__c;
IdAndBlackListPhoneMap.put(bp.Id, bp.Phone__c);
Update blacklist;
return null;
}
else
{
insert newStudent;
PageReference pg = new PageReference('/' + newStudent.Id);
pg.setRedirect(true);
return pg;
}
}
return null;
}
}
THANK YOU

Selecting picklist option on Visual force page upon load

I have a visualforce page that has a picklist called Topic and sometimes I will need to select one of the picklist options upon page load (meaning the Topic will be passed on from another page and will need to be selected upon loading the page for the first time). I'm not sure how to do this? I'm posting part of the Visualforce page that handles topic selection and the Controller code that below. Any help would be appreciated.Thanks.
Visualforce page:
<!---------------------------------- Select Topic ----------------------------------------------------->
<apex:pageblockSection title="Select the Topic" >
<apex:selectList value="{!topic}" size="1">
<apex:outputlabel for="Topic" value="Pick a Topic :" ></apex:outputlabel>
<apex:selectOptions id="topic" value="{!Topics}"/>
<apex:actionSupport action="{!populateParameters}" reRender="parametersSection,querySection" event="onchange"/>
</apex:selectList>
</apex:pageblockSection>
<!---------------------------------- End of Select Topic ---------------------------->
<!---------------------------------- Parameters for Topic ----------------------------------------------------->
<apex:pageblockSection id="parametersSection" title="Input Parameters">
<apex:repeat value="{!topicpParamWrapperList}" var="params">
<apex:outputPanel >
<apex:outputlabel value="{!params.parameter.Name}" ></apex:outputlabel>
<apex:inputfield value="{!params.parameter.inputValue__c}" rendered="{!params.renderAsText}">
<apex:actionsupport action="{!placeValuesInQuery}" reRender="querySection,splunUrlLink" event="onchange"/>
</apex:inputfield>
<apex:inputfield value="{!params.parameter.DateTimeValueHolder__c}" rendered="{!params.renderAsDate}">
<apex:actionsupport action="{!placeValuesInQuery}" reRender="querySection,splunUrlLink" event="onchange"/>
</apex:inputfield>
</apex:outputPanel>
</apex:repeat>
</apex:pageblockSection>
<!---------------------------------- End of Parameters for Topic ----------------------------------------------------->
Apex Controller
public List < topicpParamWrapper > topicpParamWrapperList {
get;
set;
} {
topicpParamWrapperList = new List < topicpParamWrapper >();
}
public void populateParameters()
{
if(!topicpParamWrapperList.isEmpty())
{
topicpParamWrapperList.clear();
}
if(topic!='' && topic!=Null)
{
for(Query_Parameter__c qParam :[select id, Parameters__r.Variable_Name__c, Parameters__r.Type__c,Parameters__r.Name from Query_Parameter__c where Topics__c=:topic])
{
Parameters__c param = new Parameters__c();
param.Name =qParam.Parameters__r.Name ;
param.type__c = qParam.Parameters__r.type__c;
param.Variable_Name__c=qParam.Parameters__r.Variable_Name__c;
topicpParamWrapperList.add(new topicpParamWrapper(param));
}
getQueryToRun();
}
}
public void getqueryToRun(){
if(mapTopics.containsKey(topic))
{
this.queryToRun =mapTopics.get(topic).query__c;
this.queryMain=mapTopics.get(topic).query__c;
}
}
public List < topicpParamWrapper > paramList {
get;
set;
} {
paramList = new List <topicpParamWrapper>();
}
All you really have to do is to set the topic to some initial value in the constructor (the special function that has name identical to class' name). You set it to some value and then it'll be rendered properly in visualforce (assuming same value is one of the selectable options!).
You have omitted the constructor or <apex:page> tag so we don't know how you're navigating to that page. But probably easiest for you would be to pass the topic in the URL. So if you access the page like that:
/apex/MyPage?topic=Something, something
then in the constructor you could do this:
topic = ApexPages.currentPage().getParameters().get('topic');
(the name of the URL parameter doesn't have to be same as the variable name but it makes sense to have them at least similar)
You can read more about getParameters()
If there is risk that your topic will contain &, spaces etc you probably should URLENCODE it when building the link.

Unable to pass a parameter <apex:param> to the relevant method

Lets assume I have a Page code:
<apex:pageBlockTable value="{!allContacts}" var="c" >
<apex:column value="{!c.id}" headervalue="ID"/>
<apex:column value="{!c.FirstName}" headervalue="First Name"/>
<apex:column value="{!c.LastName}" headervalue="Last Name"/>
<apex:column value="{!c.Title}" headervalue="Title"/>
<apex:column value="{!c.Company}" headervalue="Company"/>
<apex:column>
<apex:commandButton action="{!addToRecruits}" value="Recruit">
<apex:param assignTo="{!leadID}" name="leadID" value="{!c.id}"/>
</apex:commandButton>
</apex:column>
</apex:pageBlockTable>
And relevant controller :
public String leadID { get; set; }
public PageReference addToRecruits() {
System.debug('LeadID is: ' + leadID);
List<Lead> potentialCandidate = [SELECT id, FirstName, lastName, Title, Company FROM Lead WHERE id = :leadID];
delete potentialCandidate;
return null;
}
It seems that I can NOT pass leadID to addToRecruits() method. Do you have any idea why is so?
UPDATE:
I could manage to solve it. Instead of querying using SOQL, I approached with this style:
public String leadID { get; set; }
public PageReference addToRecruits() {
Lead candidate=new Lead(id=leadID);
....
}
Looks like the infamous platform bug? where apex:param values are not always send to the controller with apex:commandButton (though they are send with apex:commandLink).
A simple overview of the issue and possible workarounds are summarised by Jeff Douglas here: http://blog.jeffdouglas.com/2010/03/04/passing-parameters-with-a-commandbutton/
Add "rerender" attribute to apex:commandButton and its will start working - Something like
<apex:commandButton rerender="myForm" action="{!addToRecruits}" value="Recruit">
There is one way to pass parameter to controller but it will use commandLink also. I mean we need to use
command link and command button
Eg:
<apex:commandLink action="{!applyNow}" id="applybuttonLink" style="text-decoration:none">
<apex:commandButton value="Apply now"/>
<apex:param name="passId" assignTo="{!passId}" value="{!Vac.id}"/>
</apex:commandLink>
Controller:
public String vacancyId{get;set;}

How can I link labels in a SelectCheckBoxes component in Visualforce?

I have an <apex:SelectCheckBoxes> component in my Visualforce page, which gets its select options from an Apex method. I want to have a label with a link appearing next to each checkbox. How can I achieve this? Please help.
One way to accomplish this is by using apex:inputCheckbox controls individually, rather than relying on selectCheckboxes to do all the rendering for you. It's hard to get more specific in a suggestion because the question can be answered in many ways.
If, for example, you need these checkboxes to appear in a list alongside SObject instances, create a wrapper class. If they are essentially a-la-carte, you can create a class that contains a Boolean and create a list of instances of this class. Then create a dataTable, pageBlockTable, etc., and in one of the columns you include the checkbox component. Or simply use apex:repeat if you don't want any of the other table formatting.
Here's the repeat example from the VF guide:
<!-- Page: -->
<apex:page controller="repeatCon" id="thePage">
<apex:repeat value="{!strings}" var="string" id="theRepeat">
<apex:outputText value="{!string}" id="theValue"/><br/>
</apex:repeat>
</apex:page>
/*** Controller: ***/
public class repeatCon
{
public String[] getStrings()
{
return new String[]{'ONE','TWO','THREE'};
}
}
Replacing outputText with inputCheckbox and a String array with Boolean. Then simply start with an apex:outputLink and follow it with the checkbox.
EDIT -
Here's an example of using a class to get the job you want done.
Apex:
public class Example
{
public List<CheckboxClass> theCheckboxes {get; private set;} // Reference THIS array
public Example()
{
theCheckboxes = new List<CheckboxClass>();
theCheckboxes.add(new Checkbox(true));
theCheckboxes.add(new Checkbox(false));
theCheckboxes.add(new Checkbox(true));
theCheckboxes.add(new Checkbox(false));
}
public class CheckboxClass
{
public Boolean theCheckbox {get; private set;}
public CheckboxClass(Boolean b)
{
this.theCheckbox = b;
}
}
}
Visualforce:
<apex:form>
<apex:pageBlock>
<apex:pageBlockTable value="{!theCheckboxes}" var="item">
<apex:column headerValue="The Checkboxes">
<apex:inputCheckbox value="{!item.theCheckbox}">
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
I haven't tested this, but this is the idea I believe you're looking for.

Visualforce Repeaters

Hi I am getting a headache with the visualforce repeater control:
<apex:repeat value="{!productDetails}" var="o">
<apex:pageBlockSectionItem >
<apex:outputText style="label" value="Name:"></apex:outputText>
<apex:outputLabel value="{!o.name}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="{!o.ProductCode}"/>
<apex:outputText value="{!o.Family}" />
</apex:pageblockSection>
<apex:pageBlockSection>
<apex:outputText style="label" value="Quantity:"> </apex:outputText>
<apex:inputText value="{!theList}"/>
</apex:pageblockSection>
</apex:repeat>
What I am trying to do, is for each record in the product details list, generate a text box. This text box is bound to another field (theList.quantity). But I am finding that when I change the value in the last text box it sets the quantity in all the text boxes(obviously as they are bound to the same field).
So my question is whats the best way to have each textbox that is generated in the repeater have its own parameter value?
Or am I using the repeater in the wrong way?
EDIT(clarification):
For each product detail record(What I am iterating through) I want to have a textbox where a user can enter the quantity of products. The value of this textbox is unrelated to the product detail records.
My question is how can I generate unique parameters for each iteration of the textbox? Hopefully that makes sense.
Cheers
You need to use the var in the <apex:repeat> for each element in the productDetails list. For example:
<apex:repeat value="{!productDetails}" var="productDetail">
<apex:pageBlockSection>
<apex:outputText style="label" value="Quantity:"> </apex:outputText>
<apex:inputText value="{!productDetail.quantity}"/>
</apex:pageblockSection>
</apex:repeat>
That will set the the quantity property of each productDetail.
If you're really iterating over a parent of the productDetail in this example, then you'll need to change your controller to create a parent for each and then iterate over that. I'll write the example code as if you're iterating over a list of potential orders.
In your controller, you'll need to create an order for each of the products. I'm not sure if the parent is an SObject or a custom class, but I'll write the example as if it was a custom class.
public class Order {
public Order(ProductDetail productDetail) {
this.productDetail = productDetail;
}
public ProductDetail productDetail;
public Integer quantity;
}
// I assume you've already implemented this getter or are setting it some other way.
public ProductDetail[] productDetails {
get {
if (productDetails == null) {
productDetails = ...;
}
return productDetails;
}
set;
}
public Order[] orders {
get {
if (orders == null) {
orders = new Order[]{};
for (ProductDetail productDetail: productDetails) {
orders.add(new Order(productDetail);
}
}
return orders;
}
set;
}
Now, in your VisualForce page you can iterate over the Order list and have the user set the quantity.
<apex:repeat value="{!orders}" var="order">
...
<apex:outputtext style="label" value="Name:"></apex:outputText>
<apex:outputLabel value="{!order.productDetail.name}" />
...
<apex:inputText value="{!order.quantity}"/>
....
</apex:repeat>
Back in your controller, only save the orders that have a quantity of more than zero (or whatever other criteria you have in mind).
The easiest way to do this is to add a custom field to the object you're repeating through. However, I understand there are cases where that's not desirable.
You probably could use a custom Apex object (not custom Salesforce object) for this. You can do this by adding a nested class within your Controller or Extension.
For example:
public class MyClass
{
public class MyProductDetail
{
public string Name {get;set;}
public string Family {get;set;}
public string ProductCode {get;set;}
public integer Quantity {get;set;} // theList
}
public List<MyProductDetail> MyProductDetails {get;set;}
}
You would need to loop through all of your Product detail records (returned from SOQL), and add them to the MyProductDetails list. Once you have that, though, you can use a Visualforce Repeater to display each of them them and save the inputted quantity data for each record.
<apex:repeat value="{!MyProductDetails}" var="o">
<apex:pageBlockSectionItem >
<apex:outputText style="label" value="Name:"></apex:outputText>
<apex:outputLabel value="{!o.Name}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="{!o.ProductCode}"/>
<apex:outputText value="{!o.Family}" />
</apex:pageblockSection>
<apex:pageBlockSection>
<apex:outputText style="label" value="Quantity:"> </apex:outputText>
<apex:inputText value="{!o.Quantity}"/>
</apex:pageblockSection>
</apex:repeat>
Hope that helps!

Resources