How to Filter a DropDownList from another DropDownList (SPDataSource + ControlParameter way) - sharepoint

I’m trying to connect two DropDownList (ddlCountry and ddlCity) together. I want that when the user changes the Country, the ddlCity is updated consequently.
To do it, I created two lists:
· Country (ID, Title)
· City (ID, Title, Country) [Country is a lookup field]
Then I created an ASPX page with 2 DropDownList connected to Country and City through 2 SPDataSource (dsCountry and dsCity).
When I load my page, the City DropDownList is populated accordingly to the Country DropDownList, but when I change the Country, nothing happens and ddlCity shows null always
This is my code:
<SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true" selectcommand="<Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query>" id="dsCountry">
<SelectParameters>
<asp:Parameter Name="ListName" DefaultValue="Country"/>
</SelectParameters>
</SharePoint:SPDataSource>
<p>Country:
<asp:DropDownList runat="server" id="ddlCountry" DataValueField="Title" DataTextField="Title" DataSourceID="dsCountry" AutoPostBack="True" />
</p>
<SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true" selectcommand="<Query><Where><Eq><FieldRef Name="Country" /><Value Type="Lookup">{country}</Value></Eq></Where></Query>" id="dsCity">
<SelectParameters>
<asp:parameter DefaultValue="City" Name="ListName"></asp:parameter>
<asp:controlparameter name="country" controlid="ddlCountry" propertyname="SelectedValue"/>
</SelectParameters>
</SharePoint:SPDataSource>
<p>City:
<asp:DropDownList runat="server" id="ddlCity" DataValueField="Title" DataTextField="Title" DataSourceID="dsCity" />
</p>
Please note:
· In ddlCountry AutoPostBack = True
· In dsCity, in the CAML query there’s a parameter called “country”, connected to ddlCountry through a ControlParameter
I don’t understand why my filtering doesn’t work when I change the country… I can see the page reloading, but nothing happens… any suggestion?

Shouldn't the variable be:
{$country}
Interested in knowing if you ever found a solution.

I realise this is serious thread necromancy, but in case you're still interested, or anyone else finds this through Google...
Try setting the EnableViewState attribute of the second (filtered) dropdown to false. This will force the control to get a new set of data (with the new filter) from the SPDataSource, instead of getting its previous set from before the post back from the View State.
Have a look at this page for this specific example, and this page for a more general overview of the View State and what it does.

Related

How can I get a selector to do a partial lookup on any field in the list

I have a selector that is selecting cases among several other fields, as follows:
[PXSelector(typeof(Search2<CRCase.caseCD,
InnerJoin<PMProject,
On<CRCase.customerID, Equal<PMProject.customerID>>>,
Where<PMProject.contractID, Equal<Current<EPTimecardDetail.projectID>>>,
OrderBy<Desc<CRCase.caseCD>>>),
typeof(CRCase.caseCD),
typeof(CRCase.subject),
typeof(CRCase.createdDateTime),
typeof(CRCase.caseClassID),
typeof(CRCase.status),
typeof(CRCase.contactID),
typeof(CRCase.ownerID))]
When the selector is open, the search bar will only search on the first field - the CaseCD. If I type part of the Subject field text, I want it to show, as in other lookups, the entries that have that snippet of text in them. i.e., if I know part of the Subject field, I want it to filter or show entries filtered on that bit of text I enter.
Is there a setting in the PXSelector attribute that allows this, or would it be on the aspx page for the Selector?
In the past (unless there is something new) we set the FastFilterFields in the page.
Ex from project entry on contract cd (page PM301000):
<px:PXSegmentMask ID="edContractCD" runat="server" DataField="ContractCD" DataSourceID="ds" AutoRefresh="True">
<GridProperties FastFilterFields="Description, CustomerID, CustomerID_Customer_acctName" />
</px:PXSegmentMask>
Each field listed in FastFilterFields will be searchable in the selector.
Use of FastFilterFields will apply to PXSegmentMask or PXSelector.
Another example showing selector:
<px:PXSelector ID="edReceiptNbr" runat="server" DataField="ReceiptNbr" AutoRefresh="true">
<GridProperties FastFilterFields="InvoiceNbr, VendorID, VendorID_Vendor_acctName">
</GridProperties>
</px:PXSelector>

Changing a result from p:autoComplete's completeMethod before using it

I'm implementing a dialog for registering an address. In the street name field, I'm using PrimeFaces' <p:autoComplete> tag to help the user find the name of their street. The completeMethod works as expected, but to avoid confusion between similar street names I would like the drop-down list to also include the municipality the given street is in, for instance on the format "<street name>, <municipality name>".
I don't want the municipality name to be included in the actual field, so I've concluded that I need a method that performs some sort of string manipulation (substring using the position of the first comma, for instance), but I can't figure out where such a method would be called from. I've had a look through the PrimeFaces documentation, but I haven't been able to find anything that would allow me to do this. Is this at all possible in <p:autoComplete>? Alternatively, is there another autocomplete implementation which supports this, or would I have to implement my own javascript component?
EDIT: This is what the xhtml code I'm using looks like:
<div class="form-group row required">
<h:outputLabel value="#{msgs['#common.mailingAddress']}" for="address" styleClass="col-xs-12"/>
<p:autoComplete
id="address"
name="address"
size="50"
maxlength="50"
styleClass="col-xs-12 street-name"
label="#{msgs['#common.search']}"
disabled="#{not configurationController.cardCtrl.editable}"
value="#{configurationController.cardCtrl.selected.address}"
required="true"
completeMethod="#{configurationController.cardCtrl.autoCompleteTest}">
<f:validator binding="#{onlyLettersOrDigitsValidator}"/>
</p:autoComplete>
<h:message id="addressMessage" for="address" styleClass="inline-error inline-error-small"/>
</div>
The autoCompleteTest method in the controller is as follows:
public List autoCompleteTest(String input) {
AddressSearch addressSearch = AddressSearch.builder()
.streetName(input)
.municipality(municipality.getName())
.maxResultsPerPage(10)
.build();
return addressesToStreetNames(mapService.addressSearch(addressSearch).getAddresses());
}
With a helper method addressesToStreetNames which takes a list of Address objects and returns an ArrayList<String> containing those addresses' street names.
EDIT2: Based on suggestions in the comments, I tried setting itemValue and itemLabel to different values, to see if that had any effect. The new xhtml looks like the above, with the addition of the following three lines:
var="address"
itemValue="#{address.streetName}"
itemLabel="#{configurationController.cardCtrl.formatAddress(address.streetName, address.postTown)}"
The autoCompleteTest method now also returns the Address object directly rather than a String representation of the street name, so that these fields are available. The formatAddress method is simply return streetName + ', ' + postTown;
This causes the dropdown list to look how I want it to look, but when I click an item it still inserts the whole string with both street name and post town/municipality into the text field (and in fact, before I've written anything, the text field already contains ", ").

Sharepoint Custom Field Render Pattern: Render to multiple fields

Initial Question
Can I render the data from one field into multiple columns?
Background
I have created a custom field that contains a drop down list and two text boxes. The idea is that users can select a supplier from the drop down list that is connected to a list of suppliers. Which will get the contact name and number of the supplier and populate the corresponding textboxes.
I have done it this way as it is important to be able to override the contact number and the address but the client wants to see the defaults.
Heres what it looks like:
On saving the new entry the value of the field is saved as follows:
;#1;#Supplier 1;#Contact Name;#01234 567890;#
I chose to save the data in this was so I can treat it like a multi-column field when I render it.
I am using the below code to split the data and override the display pattern for the list view:
<RenderPattern Name="DisplayPattern">
<Switch>
<Expr>
<Column />
</Expr>
<Case Value="" />
<Default>
<!--<Column SubColumnNumber="0" HTMLEncode="TRUE" />
<HTML><![CDATA[<br/>]]></HTML>-->
<Column SubColumnNumber="1" HTMLEncode="TRUE" />
<HTML><![CDATA[ - ]]></HTML>
<Column SubColumnNumber="2" HTMLEncode="TRUE" />
<HTML><![CDATA[ - ]]></HTML>
<Column SubColumnNumber="3" HTMLEncode="TRUE" />
<HTML><![CDATA[]]>]></HTML>
</Default>
</Switch>
</RenderPattern>
This allows me to present the data to the end user as follows:
Question
I would like to be able to display this split data in seperate columns. I notice that the build in title field SharePoint uses has four types of columns you can add to a view for a single field. I am trying to reproduce this kind of functionality so each section of the data can be added or removed from views. Is this possible?
It turns out you have access the list item which meant I was able to simply just add to additional fields within the list item by overriding the UpdateFieldValueInItem method.
Public Overrides Sub UpdateFieldValueInItem()
Me.ItemFieldValue = ddlSupplier.SelectedItem.Value
If Me.Item.Fields.ContainsField(Me.Field.InternalName & "-" & "Telephone") Then
Me.Item(Me.Field.InternalName & "-" & "Telephone") = txtTelephone.Text
End If
End Sub
A much more effective way of doing this.

Expression Engine: How do I display the category name of an entry?

I am using SafeCracker to create some entries on a site and when the form is submitted it comes up in a preview template.
I need to be able to display the selected category for the entry.
I am using the following code to display the results in the preview template:
{exp:safecracker channel="jobs" id="contact" return="jobs/preview/ENTRY_ID" entry_id="{segment_3}"}
<p>Job Type: {job_type}<br />
Category: {exp:channel:category_heading}{category_name}{/exp:channel:category_heading}<br />
Location: {job_location}</p>
<p>Description:<br />
{job_description}
</p>
<p>Apply by: {how_to_apply} at: {apply_value}</p>
<p>Company: {company}</p>
<p>Description: <br />
{company_description}</p>
{/exp:safecracker}
As it is, the Category: value is blank. What is the correct way to do this?
Thanks!
Use: {categories}{if selected}{category_name}{/if}{/categories}.
Failing that, you could use the query module:
{exp:query sql="
SELECT c.cat_name
FROM exp_categories c, exp_category_posts cp
WHERE cp.entry_id = {segment_3}
AND c.cat_id = cp.cat_id
" backspace="2"}{cat_name}, {/exp:query}

Using a4j:support to update the model and view, ready for the next button/submit action

The Problem
We have a swing based front end for an enterprise application and now are implementing a (for now simpler) JSF/Seam/Richfaces front end for it.
Some of the pages include fields that, when edited, should cause other fields to change as a result. We need this change to be shown to the user immediately (i.e. they should not have to press a button or anything).
I have implemented this successfully using h:commandButton and by adding onchange="submit()" to the fields that cause other fields to change. That way, a form submit occurs when they edit the field, and the other fields are updated as a result.
This works fine functionally, but especially when the server is under significant load (which happens often) the form submits can take a long time and our users have been continuing to edit fields in the meantime which then get reverted when the responses to the onchange="submit()" requests are rendered.
To solve this problem, I was hoping to achieve something where:
Upon editing the field, if required, only that field is processed and only the fields it modifies are re-rendered (so that any other edits the user has made in the meantime do not get lost).
Upon pressing a button, all fields are processed and re-rendered as normal.
The (Unstable) Solution
Okay, I think it might be easiest to show a bit of my page first. Note that this is only an excerpt and that some pages will have many fields and many buttons.
<a4j:form id="mainForm">
...
<a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" reRender="mainForm" />
...
<h:outputLabel for="firstName" value=" First Name" />
<h:inputText id="firstName" value="#{life.firstName}" />
...
<h:outputLabel for="age" value=" Age" />
<h:inputText id="age" value="#{life.age}">
<f:convertNumber type="number" integerOnly="true" />
<a4j:support event="onchange" ajaxSingle="true" reRender="dob" />
</h:inputText>
<h:outputLabel for="dob" value=" DOB" />
<h:inputText id="dob" value="#{life.dateOfBirth}" styleClass="date">
<f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{userPreference.timeZone}" />
<a4j:support event="onchange" ajaxSingle="true" reRender="age,dob" />
</h:inputText>
...
</a4j:form>
Changing the value of age causes the value of dob to change in the model and vice versa. I use reRender="dob" and reRender="age,dob" to display the changed values from the model. This works fine.
I am also using the global queue to ensure ordering of AJAX requests.
However, the onchange event does not occur until I click somewhere else on the page or press tab or something. This causes problems when the user enters a value in say, age, and then presses calculateButton without clicking somewhere else on the page or pressing tab.
The onchange event does appear to occur first as I can see the value of dob change but the two values are then reverted when the calculateButton request is performed.
So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them? Why is that not happening already since I am using the AJAX queue?
The Workarounds
There are two strategies to get around this limitation but they both require bloat in the facelet code which could be confusing to other developers and cause other problems.
Workaround 1: Using a4j:support
This strategy is as follows:
Add the ajaxSingle="true" attribute to calculateButton.
Add the a4j:support tag with the ajaxSingle="true" attribute to firstName.
The first step ensures that calculateButton does not overwrite the values in age or dob since it no longer processes them. Unfortunately it has the side effect that it no longer processes firstName either. The second step is added to counter this side effect by processing firstName before calculateButton is pressed.
Keep in mind though that there could be 20+ fields like firstName. A user filling out a form could then cause 20+ requests to the server! Like I mentioned before this is also bloat that may confuse other developers.
Workaround 2: Using the process list
Thanks to #DaveMaple and #MaxKatz for suggesting this strategy, it is as follows:
Add the ajaxSingle="true" attribute to calculateButton.
Add the process="firstName" attribute to calculateButton.
The first step achieves the same as it did in the first workaround but has the same side effect. This time the second step ensures that firstName is processed with calculateButton when it is pressed.
Again, keep in mind though that there could be 20+ fields like firstName to include in this list. Like I mentioned before this is also bloat that may confuse other developers, especially since the list must include some fields but not others.
Age and DOB Setters and Getters (just in case they are the cause of the issue)
public Number getAge() {
Long age = null;
if (dateOfBirth != null) {
Calendar epochCalendar = Calendar.getInstance();
epochCalendar.setTimeInMillis(0L);
Calendar dobCalendar = Calendar.getInstance();
dobCalendar.setTimeInMillis(new Date().getTime() - dateOfBirth.getTime());
dobCalendar.add(Calendar.YEAR, epochCalendar.get(Calendar.YEAR) * -1);
age = new Long(dobCalendar.get(Calendar.YEAR));
}
return (age);
}
public void setAge(Number age) {
if (age != null) {
// This only gives a rough date of birth at 1/1/<this year minus <age> years>.
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR) - age.intValue(), Calendar.JANUARY, 1, 0, 0, 0);
setDateOfBirth(calendar.getTime());
}
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
if (notEqual(this.dateOfBirth, dateOfBirth)) {
// If only two digits were entered for the year, provide useful defaults for the decade.
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfBirth);
if (calendar.get(Calendar.YEAR) < 50) {
// If the two digits entered are in the range 0-49, default the decade 2000.
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2000);
} else if (calendar.get(Calendar.YEAR) < 100) {
// If the two digits entered are in the range 50-99, default the decade 1900.
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1900);
}
dateOfBirth = calendar.getTime();
this.dateOfBirth = dateOfBirth;
changed = true;
}
}
What is the scope of your bean? When the button is executed, it's a new request and if your bean is in request scope, then previous values will be gone.
So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them?
What you could do is disable the submit button from the time you initiate your ajax request until your ajax request completes. This will effectively prevent the user from pressing the submit button until it resolves:
<a4j:support
event="onblur"
ajaxSingle="true"
onsubmit="jQuery('#mainForm\\:calculateButton').attr('disabled', 'disabled');"
oncomplete="jQuery('#mainForm\\:calculateButton').removeAttr('disabled');" />
One thing that is additionally helpful with this approach is if you display an "ajaxy" image to the end user while this is happening so that they intuitively understand that stuff is happening that will resolve soon. You can show this image in the onsubmit method as well and then hide it oncomplete.
EDIT:
The issue may just be that you need to add the process attribute to your a4j:commandButton. This attribute specifies the components by id that should participate in the model update phase:
<a4j:commandButton
id="calculateButton"
value="Calculate"
action="#{illustrationManager.calculatePremium()}"
process="firstName"
reRender="mainForm" />
i guess i can provide another work-around.
we should have two flags on js level:
var requestBlocked = false;
var requestShouldBeSentAfterBlock = false;
h:inputText element blocks the ajax request on blur:
<h:inputText id="dob" onblur="requestBlocked = true;" ...
a4j:commandButton sends the request if requestBlocked is false:
<a4j:commandButton id="calculateButton"
onkeyup="requestShouldBeSentAfterBlock = requestBlocked;
return !requestBlocked;" ...
a4j:support sends the request if requestShouldBeSentAfterBlock is true:
<a4j:support event="onchange"
oncomplete="requestBlocked = false;
if (requestShouldBeSentAfterBlock) {
requestShouldBeSentAfterBlock = false;
document.getElementById('calculateButton').click();
}" ...
since oncomplete block works after all needed elements are re-rendered, things will work in the needed order.
It looks like a reason is somewhere in getters/setters.
For example one of the possibilities: when no ajaxSingle=true and the calculate button is clicked. All the values are set to the model, so both setAge and setDateOfBirth are invoked. And it may happen so that setDateOfBirth is invoked before setAge.
Looking closer at setAge method it in fact resets the date to the beginning of the year, even though the date could have had the right year already.
I would recommend simplifying the logic first. For example have separate disconnected fields for year and birth day, and check if the issue is still reproducible to find minimal required conditions to reproduce.
Also from user experience standpoint, a common practice is to do something like the following, so the event fires once user stops typing:
<a4j:support event="onkeyup"
ajaxSingle="true"
ignoreDupResponses="true"
requestDelay="300"
reRender="..."/>

Resources