Visualforce error when creating a apex:repeat on a selectoption - salesforce

Okay, I've been banging my head trying to figure out how to get around this issue without writing unnecessary code.
I have the following Visualforce code that is causing a error when saving:
<select id="rec_count">
<apex:repeat value="{!pg}" var="selpg">
<option {!IF(selpg.value = selectedpgtxt, 'selected','')} value="{!selpg.value}" >
{!selpg.value}
</option>
</apex:repeat>
</select>
The error is:
Error: Element type "option" must be followed by either attribute specifications, ">" or "/>".
Apparently the visual force parser is upset about a option tag not having a attribute for the {!IF(selpg.value = selectedpgtxt, 'selected','')}.
I have tried the equivalent of:
<option selected="" value="1">1</option>
<option selected="selected" value="2">2</option>
However browser considers all of the options selected doing this.

Unless this is considered unnecessary code, the following seems pretty straightforward to me.
Visualforce:
<apex:selectList value="{!theSelection}">
<apex:selectOptions value="{!theList}"/>
</apex:selectList>
Apex:
// Top of class
public List<SelectOption> theList {get; private set;}
public String theSelection {get; set;}
// In constructor
this.theList = new List<SelectOption>();
this.theList.add(new SelectOption('1', 'First Option'));
this.theList.add(new SelectOption('2', 'Second Option'));
// Now for the default
this.theSelection = '1';

Related

vaadin combobox addItem and option value(?)

code
ComboBox combo = new ComboBox('comboBox');
combo.addItem("A");
combo.addItem("B");
combo.addItem("C");
combo.addValueChangeListener(new ValueChangeListener() {
#Override
public void valueChange(ValueChangeEvent event) {
com.vaadin.data.Property changedProeprty = event.getProperty();
String value = changedProeprty.toString() ;
}
});
value is 'C'
However I want to input the other value, like selectBox's option in html
<select>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
How to input the option value and how to get the option value in vaadin combobox ?
You have to set the "real" value as the items in your ComboBox.
You can then use the setItemCaption(...) method to tell the system what do display in the UI.
// Set item caption for this item explicitly
select.addItem(2);
select.setItemCaption(2, "Demos");
Look in the book of vaadin for more details here

Spring MVC, Angular AngularJS drop-down list - problems on persist ManyToOne

Problem: I have a Purchase Order table and Country table which primary key is a foreign key in my PO table. On the front end I have a form (angularJS) used for creation of a new PO with a bunch of fields and about 9 drop-down list fields form where user can select whatever info is required for the PO.
For the sake of the example I will use the Country drop-down. (All drop-downs are getting populated from the DB).
The problem I have is with the persistence. After submitting the form, if I use the debugger and I check the Purchase Order object that is being passed to the service all my drop downs objects are null, except the other normal input fields which belong to the PO table.
I think the problem is Angular, If I check the network tab in my chrome browser under developer tools I see the country being passed as countryData:2. Thing is I am new to Angular so I am bit confused at this stage on how I should handle this as data is coming from the drop-down list and how I should return the country object. Here http://tinypic.com/r/2rd9pxl/8 I put a screenshot of my network tab from the browser which show the from Data that is being posted.
Populate the country drop-down list
<div class="control-group">
<label class="control-label">*Country</label>
<div class="input-append">
<div data-ng-init="getCountryDataFromServer()">
<b>Person Data:</b> <select id="countryData" ng-model="contact.countryData">
<option value="">-- Select Countries --</option>
<option data-ng-repeat="country in countries" value="{{country.countryId}}">{{country.countryname}}</option>
</select><br>
</div>
</div>
<div class="input-append">
<label>
<span class="alert alert-error"
ng-show="displayValidationError && newContactForm.countryData.$error.required">
<spring:message code="required"/>
</span>
</label>
</div>
</div>
Model
#Entity
#Table(name = "PURCHASEORDER",schema = "POTOOL")
#Audited
public class PurchaseOrder {
#Id
#GeneratedValue
private int id;
private String tower;
private Double revenue;
//other properties of the PO
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "country_id")
private Country country;
//Other ManyToOne relationships
//Getter and setters
Controller
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> create(#ModelAttribute("contact") PurchaseOrder purchaseOrder,
#RequestParam(required = false) String searchFor,
#RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page,
Locale locale) {
purchaseOrderServiceImpl.save(purchaseOrder);
if (isSearchActivated(searchFor)) {
return search(searchFor, page, locale, "message.create.success");
}
return createListAllResponse(page, locale, "message.create.success");
}
Service
public void save(PurchaseOrder purchaseOrder) {
purchaseOrderRepository.save(purchaseOrder);
}
Repository
public interface PurchaseOrderRepository extends
PagingAndSortingRepository<PurchaseOrder, Integer> {
}
I don't think there is any issue because of angular since you have defined ng-model="contact.countryData" for dropdown and option has value from value="{{country.countryId}}". When you submit value country.countryId is going to server which is absolutely fine. I think you should have conversion mechanism which will convert data from UI to Hibernate Entity(i.e. PurchaseOrder). Generally DTO(Data transfer Object) is used to get data from UI and using setter and getter we set to Hibernate entity and latter you will save that entity.
This question might help you.
DTO to Entity And Entity to DTO
When you are working with HTML(not with JSP), it better to use #RequestBody at place of #ModelAttribute to get complete body of data. Please refer the following links:
Link 1
Link 2

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.

radio button value not visible in vfpage

im tring to display records in question__c object along with fields in object as radio button. but im not able to get radio button value. getting only radio button without name.
im new to salesforce.if this is very basic question pls excuse me.
<apex:page standardController="question__c" extensions="GetQuestionList" >
<apex:form >
<apex:repeat value="{!que}" var="a">
<apex:pageBlock >
<apex:pageBlockSection columns="1">
{!a.Quiz_question__c} {!a.id} <br/>
<apex:selectRadio value="{!selectedAns}" >
<apex:selectOption itemValue="{!opt3}" itemLabel="{!a.option_3__c}"/>
<apex:selectOption itemValue="{!opt4}" itemLabel="{!a.option_4__c}"/>
</apex:selectRadio>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:repeat>
</apex:form>
</apex:page>
____mycontroller is
public class GetQuestionList {
question__c q1;
public List<question__c> que{set;}
public List<question__c> getque(){
List<question__C> que= new List<question__c>();
for(question__C q:[select Quiz_question__c,id from question__c]){
que.add(q);
system.debug(que);
}
system.debug(que);
return que;
}
public String selectedAns{get;set;}
public String opt2{get;set;}
public String opt4{get;set;}
public String opt3{get;set;}
public GetQuestionList(ApexPages.StandardController controller) {
}
}
The reason you have no label is because the value field on the <apex:selectRadio> is a String variable, rather than a field. If you want to add a label, there is a label attribute on that visualforce component you can use.
If you want the label to be dynamically shown based on an actual field's label in the data model, you need to set the value field to that field. An example of that would be if you had an Answer__c field on the Question__c object.
<apex:selectRadio value="{!a.Question__r.Answer__c}">
<apex:selectOption itemValue="{!opt3}" itemLabel="{!a.option_3__c}"/>
<apex:selectOption itemValue="{!opt4}" itemLabel="{!a.option_4__c}"/>
</apex:selectRadio>
That value field would use the label assigned to that field in the object model by default.

inputField databinding issue with VisualForce

I'm having strange results with a Visualforce page (yes, Salesforce.com is icky, I know). My issue is that I am trying to use the inputField to bind data on a custom sObject, but in my custom controller, it is not recognizing the user input data.
Here is the code snippet from the page:
<apex:pageBlockSection title="Enter New Fee" rendered="{!isRenderedFees}" >
<apex:inputField value="{!workingFee.Fee_Type__c}" required="True"/>
<apex:inputField value="{!workingFee.Fee__c}" required="True"/>
<apex:pageBlockSectionItem >
<apex:CommandButton value="Save Fee" action="{!saveFee}" immediate="true" />
<apex:CommandButton value="Cancel" action="{!cancelFee}" immediate="true" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
and here is the code from the controller:
public Fee__c workingFee {get; set;}
....
public PageReference saveFee(){
this.workingFee.Trade_Group__c = tradeGroup.id;
try{
System.debug('~~~~#~~#~~workingFee: '+workingFee.Fee_Type__c +'='+workingFee.Fee__c);
upsert workingFee;
}catch (System.Dmlexception e){
ApexPages.addMessages(e);
return null;
}
System.debug('~~~~#~~#~~workingFee: '+workingFee.Fee_Type__c +'='+workingFee.Fee__c);
//savedFees.add(workingFee.clone());
//re-render the page
this.isRenderedFees = False;
return null;
}
I've made sure the workingFee property is not null. Whenever I hit the "Save Fee" button after entering the values, it reloads the page and gives me the message "Error: Required fields are missing: [Fee__c]" (note, Fee__c here is a currency field -- it's not that it expects this to be an sObject, is it?)
The debug statement in the saveFee() method shows that workingFee's important fields are null, when I would expect them to have been assigned the values input by the user.
I have had a whole heap of issues binding controls to a property exposed with the simple { get; set; } notation... The rest of your code will see the properties, but for some bizarre reason, your View won't (always) bind...
Try writing explicit get/set methods, like
private workingFee;
public Fee__c getWorkingFee() {
return workingFee;
}
public void setWorkingFee(Fee__c value) {
workingFee = value;
}
There is no logical reason why this should work any different to
public Fee__c workingFee { get; set; }
but in my experience, it sometimes does...
what did you say about it being icky? ;)
Immediate=false/true has bitten me quite a few times too. Good catch Ian.

Resources