rich:autocomplete strange behaviour - jsf-2

We are upgrading from jsf 1.2 to jsf 2.
We are using apache myfaces 2.1 and rich faces 4.3.
We are facing very strange issue with <rich:autocomplete>. Below is the xhtml code.
<rich:autocomplete mode="cachedAjax" minChars="2" autocompleteMethod="#{bean.getData}"
var="result" value="#{bean.inputData}">
<h:column>
<h:outputText value="#{result}" />
</h:column>
</rich:autocomplete>
Following is the scenario , when an input is entered in an autocomplete input box , suggetions are shown - that is bean.getData method is called.
Surprisingly , after any of the suggestion is selected , bean.getData method is called again with chosen option value , which I believe is not the correct behaviour
since user has selected an option and not typed any input.
I don't want the bean.getData method to be called again. Is there any alternative ?
Please help.
EDIT 1
Since I am running a db query to get suggestion values , they are different than the actual input value typed to get suggestions. That is if I type "at" , my sugegstions could be "check me" . I understand that once prefix for search is changed , suggestions are evaluated again , but here i am not changing the prefix but selecting the entire suggestion value.
EDIT 2
Providing the context the issue occured with.
When autoCompleted method is called , it populates a hashMap with all the suggestions with CustomUserObject as the value.
Below is the code for this :
public List<String> getData(FacesContext context, UIComponent component, String input) {
Map<String, CustomUserObject> userMap = new HashMap<String, CustomUserObject>();
//get users from db
List<CustomUserObject> users = bean.fetchUserList(input);
//put users in map
for (CustomUserObject user : users) {
userMap.put(user.id, user) ;
}
List<String> userList = new ArrayList<String>();
//convert the list to List<String>
if(userList != null && !userList.isEmpty()){
//convert the List<CustomUserObject> to List<String>
}
return userList;
}
Now because of the issue mentioned in the question , getData is called again and corrupts userMap.
This map is used to retrieve correct CustomUserObject by comparing it with selected Suggestion like below :
if(userMap != null && !userMap.isEmpty()){
for(CustomUserObject user : userMap.values()){
if(selectedSuggestion != null && selectedSuggestion.equals(user.name)){
//match is found
//set variables to update ui at re-render
}
//no match found
//set variables to update ui at re-render
}
}
EDIT 3
In addition to above issues , it seems that there is no "nothing label" attribute for rich:autocomplete which was present for rich:suggestionBox which comes into picture when there is no result found.
This issue alongwith above issue is really making a difficult job to get this component working same as rich:suggestionBox

Related

Why data is not send by form submitting (zf2 forms + filters)?

I have problem:
When I fill in form and pressing add button page is reloaded, but no data is added to the database.
Code of NewsController, add action is below:
public function addAction() {
$form = new AddNewsForm();
$form->get('submit')->setValue('Add1');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
var_dump($form->isValid());
if ($form->isValid()) {
echo "form is valid";
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$blogpost = new NewsItem();
$blogpost->exchangeArray($form->getData());
$blogpost->setCreated(time());
$blogpost->setUserId(0);
$objectManager->persist($blogpost);
$objectManager->flush();
// Redirect to list of blogposts
return $this->redirect()->toRoute('news');
}
}
return array('form' => $form);
}
Class AddNewsForm is included as use \News\Form\AddNewsForm as AddNewsForm; above.
I tried to debug my code and realized, that $form->isValid() return false all time. I tried to fill in all fields of form — it says that form is not valid. If not all fields are filled in it false too.
The problem is with validation, I think, so I will add here how I assing filter to the form. This is how I assing filter to my form:
$this->setInputFilter(new AddNewsInputFilter());
Class AddNewsInputFilter is included by this:
use \News\Form\AddNewsInputFilter as AddNewsInputFilter;
I don't think it is good to paste there ~100 lines of code, so I will just give a link to files in my github repo (full code of controllers/files available here):
AddNewsForm.php — file, where I create the form
AddNewsInputFilter.php — file, where I set fil
NewsController.php — file, controller, where I call created form
Repository link — root dir of my module
So the problem is that $form->isValid(); doesn't show is form valid or not properly and I don't know why. Note, that request is getting properly and first condition is passed (but second is not passed). It is the problem, thats why I am writing here.
How I can solve it?
Thanks is advance!
try var_dump($form->getMessages()) and var_dump($form->getInputFilter()->getMessages()) in controller(after calling $form->isValid()) or in view . see what error you getting and on witch element ?
NOTICE : getMessages() will be empty if $form->isValid() has not been called yet,
UPDATE : do this in controller :
var_dump($form->isValid());
var_dump($form->getMessages())
var_dump($form->getInputFilter()->getMessages())

loop through model in mvc razor code behind

I am working on MVC4 App, and I am stuck at one point, I tried using google to help me, but without success. This might be more simple then I think, but coming from web forms and shifting to mvc is "painful" sometime.
I am trying to loop through the model I have and get the values stored in that model. I tried few approaches but I am getting an error everytime. This is what I have:
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == Convert.ToInt32(AgentID)
select s;
if (modelAgentFilter != null)
{
ViewBag.FirstName = // Get FirstName object here
}
Thanks in advance for your comments.
Laziale
EDIT:
I did include for loop like this:
if (modelAgentFilter != null)
{
foreach (var property in modelAgentFilter)
{
string test = property.ADDRESS;
}
}
But when the compiler will reach the foreach step I am getting this error: "LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression."
I can get to the properties of the var model using that foreach look but as soon as the compiler will try to loop the model that error pops up.
Thanks again
LINQ to Entities does not recognize any methods. You can't use even ToString() in LINQ expression. You need first convert your value and than add it in LINQ.
In your example you need to do something like following:
var _agentID = int.Parse(AgentID);
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == _agentID
select s;

grails and double values saving

In my Grails project I have a Domain Class with a double field as follows:
double totalAmount;
the value of this field are calculated by a sum done after selecting values in a multiple select. the function for sum values is in the controller, as follows:
def sumReceiptItems(){
params.list("receiptItemsSelected").each {i-> println("element "+i)}
def appList = params.list("receiptItemsSelected")
List<ReceiptItem> allSelectedIds = ReceiptItem.findAllByIdInList(params.receiptItemsSelected.split(',')*.toLong())
def totalAmount = allSelectedIds.amount.sum()
println("totalAmount is = "+totalAmount)
render totalAmount as Double
}
the function works well. After function calling, to update the field in GSP page, I use a javascript method as follows:
function updateTotalAmount(name, data, presentNullAsThis){
if(data !=null)
document.getElementById(name).value= data;
else
document.getElementById(name).value=presentNullAsThis;
}
The javascript works and I see the updating of the field at runtime, but the double value is shown with a dot, and not with comma to separate decimal values. Infact, after clicking by save button to save the instance of the domain class, the value is saved without separating decimals, for example:
if the value into the fiels is 10.50 it is stored as 1050
In this discussion how can save a double type correctly in grails? I've read a similar problem, but solution is not good for my issue.
Anybody can help me?
Values with decimal separator depends on the current Locale of the user. Normally you use g.formatNumber in the view to display correctly the value.
You can check this topic on how to discover the decimal separator for a Locale.
To get the user's Locale use:
Locale locale = RequestContextUtils.getLocale(request)
I have solved the problem in this way:
I've updated my Javascript as follows:
function updateTotalAmount(name, data, presentNullAsThis)
{
var data2 = data.toString().replace(/\./g, ',');
if(data2 != null) document.getElementById(name).value= data2;
else document.getElementById(name).value= presentNullAsThis;
}
I've removed "type="number"" in the gsp related field

display seconds in DateTimeItem (SmartGWT)

when reading SmartGWT DateTimeItem: accept 12 hour format I found that using TimeDisplayFormat offers the options to display the seconds as, e.g. dateTimeItem.setTimeFormatter(TimeDisplayFormat.TOPADDED24HOURTIME); well, but there was no change in the displaying of the date.
As the code states that TimeDisplayFormat is deprecated, and one should use the DateDisplayFormatter instead, I tried dateTimeItem.setDateFormatter(DateDisplayFormat.TOSERIALIZEABLEDATE);, but still no change.
The value gets set via dateTimeItem.setValue(myDate);
Any idea what (else) I have to set to the DateTimeItem in order to get the seconds displayed as well?
I'm using SmartGWT 3.1
PS: I tried dateTimeItem.setDisplayFormat(DateDisplayFormat.TOSERIALIZEABLEDATE); as well, but still no change
It seems DateDisplayFormat.TOSERIALIZEABLEDATE is having some issue in SmartGWT 3.x.
dateTimeItem.setDateFormatter(DateDisplayFormat.TOSERIALIZEABLEDATE); works correctly in SmartGWT 4.0.
dateTimeItem.setDisplayFormat(DateDisplayFormat.TOSERIALIZEABLEDATE); did not provide required behavior even in 4.0, probably due to a default system wide format setting.
You should be able to use a value formatter as a workaround in 3.0.
dateTimeItem.setEditorValueFormatter(new FormItemValueFormatter() {
public String formatValue(Object value, Record record, DynamicForm form, FormItem item) {
if (value != null && value instanceof Date) {
return DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
}
return null;
}
});
Check DateItem.setEditorValueFormatter as you might have to set input format, etc. as well.
hi use the following code in your dateitem timeSheetDate.setShowPickerTimeItem(true); timeSheetDate.setTimeFormatter(TimeDisplayFormat.TOSHORTTIME); and also you can use timeSheetDate.setTimeFormatter(TimeDisplayFormat.TOTIME);

how to check null value of Integer type field in ASP.NET MVC view?

I have integer type field in database which is having property "Not Null".
when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!
one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" # Scott Gu blog. And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e
public partial class Person
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty(Name))
yield return new RuleViolation("Name is Required", "Name");
if (Age == 0)
yield return new RuleViolation("Age is Required", "Age");
yield break;
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
There is also problem with range.
Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".
so finally is there any best way for validation in ASP.NET MVC?
you can change your code with a nullable type?
Dim i As Nullable(Of Integer)
MsgBox(i.HasValue)
'result is false
i = 1
MsgBox(i.HasValue)
'result is true
i = Nothing
MsgBox(i.HasValue)
'result is false
I'm not realy up to speed with the details of MVC, but isn't there a way to change the default value of age to -1? This way you have a value to check on and people can still enter 0.
Another solution could be to use a nullable int. You can do this by appending a ? to the type.
HTH.
Jonathan
I would validate the form on the client first. If the age is 0 then let the user know that it's not a valid age. On the server change the message, it's misleading:
if (Age == 0)
yield return new RuleViolation("0 years is not a valid age", "Age");
I know that because you bind to a model property from your Person entity it gets 0 as the default value - why don't you change that in the database then? Set a default in the database to a value that you consider reasonable for the user age, so that it no longer displays as 0 for new entities.
If you don't want to change the db values, use jQuery to set the textbox values to empty strings on your Create page when it loads. If the user tries to submit such a form you can check on the client to disallow it and on the server you don't have to do anything, the user will get a "A value is required" message back.
By the way, you wrote:
i can not compare it with 0 because if
someone insert a value 0 then it will
be considered as error
I don't see a problem in this particular domain model. Do you think that age of 0 is a good value or not? Ask yourself.
check it with Utilities.GetNullableInt32(textbox1.Text.Trim());
if u check with this GetNullableInt32() function if the user entered value '0' it will saved as NUll in your table

Resources