How can i hide the immediate validation for the datefield in Vaadin 8 . I have the follwing code
dateField.setLocale(new Locale("fr", "CA"));
binder.forField(dateField).withValidator(new Validator<LocalDate>() {
#Override
public ValidationResult apply(LocalDate value, ValueContext context) {
if (LocalDate.now().equals(value)) {
return ValidationResult.ok();
} else {
return ValidationResult.error("the date is not the current date");
}
}
}).withValidationStatusHandler(new BindingValidationStatusHandler() {
#Override
public void statusChange(BindingValidationStatus<?> statusChange) {
if (statusChange.getResult().isPresent()) {
ValidationResult validationResult = statusChange.getResult().get();
if (validationResult.isError()) {
label.setCaption("the date is not the current date");
} else {
label.setCaption("the date IS the current date");
}
}
}
}).bind(CustomDate::getLocalDate, CustomDate::setLocalDate);
The result is however, that vaadin default validation (for example when the entered dateformat is not the expected format ) getting execued and my validation. I want to do the validation of the format expecitly in my validator. how to achieve that.
Maybe using setComponentError works for your use case. It should provide a way to override default error message.
For examples, see Handling Errors.
I did not try it but you can check if it works as described in the documentation (here):
DateField date = new DateField("My Date") {
#Override
protected Result<LocalDate> handleUnparsableDateString(
String dateString) {
try {
// try to parse with alternative format
LocalDate parsedAtServer = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
return Result.ok(parsedAtServer);
} catch (DateTimeParseException e) {
return Result.error("Bad date");
}
}
};
According to documentation, client-side validation can be hidden via CSS.
Related
I want to perform few validations on Sales order screen, I am comparing the Customer(customerID) field and the Customer Order(CustomerOrderNbr) field and try to give an error message if both the fields match.
I am not a programmer but I tried some code which is giving lot of errors and i'm not able to fix it...
namespace PX.Objects.SO
{
public class SOOrderEntry_Extension:PXGraphExtension<SOOrderEntry>
{
public const string ordernbrErrorMessage = "Customer name and customer number cannot be same.";
public void SOOrder_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
if (!ValidateCustomerID(sender, e.Row as SOOrder))
{
PXUIFieldAttribute.SetError<SOOrder.customerID>(sender, e.Row, ordernbrErrorMessage);
}
}
public bool ValidateCustomerID(PXCache sender, SOOrder soOrder)
{
if (soOrder != null)
{
string soCustomerID = PXSelectorAttribute.GetField(sender, soOrder, typeof(SOOrder.customerID).Name, soOrder.CustomerID, typeof(Customer.acctCD).Name) as string;
string soCustomerOrderNbr = soOrder.CustomerOrderNbr;
if (soCustomerID != null && soCustomerOrderNbr != null)
{
return !soCustomerID.Trim().Equals(soCustomerOrderNbr.Trim(), StringComparison.OrdinalIgnoreCase);
}
}
return true;
}
}
}
And this is my 1st entry with some customer name and order number
enter image description here
And this is my 2nd entry with same customer name and order number
enter image description here
After doing the changes in the code it isn't showing any error message...I restarted the website and checked but no results
I fixed the syntax errors below. However I would be inclined to think this validation has no practical use case. CustomerID is an integer (number) field in the database that identifies the customer record, usually this is not shown to the user. CustomerOrderNbr is a free form text field that can contain any string value entered from the user. I wouldn't expect the user to enter a CustomerID in CustomerOrderNbr.
EDIT: changed SOOrder.CustomerID by Customer.AcctCD
namespace PX.Objects.SO
{
public class SOOrderEntry_Extension:PXGraphExtension<SOOrderEntry>
{
public const string ordernbrErrorMessage = "Customer name and customer number cannot be same.";
public void SOOrder_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
if (!ValidateCustomerID(sender, e.Row as SOOrder))
{
PXUIFieldAttribute.SetError<SOOrder.customerID>(sender, e.Row, ordernbrErrorMessage);
}
}
public bool ValidateCustomerID(PXCache sender, SOOrder soOrder)
{
if (soOrder != null)
{
string soCustomerID = PXSelectorAttribute.GetField(sender, soOrder, typeof(SOOrder.customerID).Name, soOrder.CustomerID, typeof(Customer.acctCD).Name) as string; string soCustomerOrderNbr = soOrder.CustomerOrderNbr;
if (soCustomerID != null && soCustomerOrderNbr != null)
{
return !soCustomerID.Trim().Equals(soCustomerOrderNbr.Trim(), StringComparison.OrdinalIgnoreCase);
}
}
return true;
}
}
}
I try to add a custom attribute to validate required field and trim value for white space.
So here is my custom attribute :
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class CustomRequired : ValidationAttribute, IClientModelValidator
{
public CustomRequired()
{
ErrorMessage = new ResourceManager(typeof(ErrorResource)).GetString("All_Required");
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-customrequired", ErrorMessage);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return value.ToString().Trim().Length > 0 ? ValidationResult.Success : new ValidationResult(ErrorMessage);
}
private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
And here how I add it (or try) :
$(document).ready(function () {
$.validator.addMethod("customrequired", function (value, element, parameters) {
return $.trim(value).length > 0;
});
$.validator.unobtrusive.adapters.addBool('customrequired');
});
And set it on property in a viewmodel :
[CustomRequired]
public string Code { get; set; }
My problem is it doesn't had any client side validation whereas the function is in the jQuery validator... The ModelState is invalid so the controller reject it but I want a client side validation.
console:
Edit :
I forgot to say I'm using kendo... See my own answer below.
I forgot to say that I'm using kendo...
My code is functional with a classic validation but not with kendo edit pop-up. :/
So here is the solution for those who have the same problem, write this in your javascript instead of add it in the $.validator :
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
customrequired: function (input) {
if (input.is("[data-val-customrequired]")) {
return $.trim(input.val()).length > 0;
}
return true;
}
},
messages: {
customrequired: function (input) {
return input.attr("data-val-customrequired");
}
}
});
})(jQuery, kendo);
Is there a way to get the _eventId parameter from the SWF RequestContext? Sometimes I need to use a bit of logic to decide where to transition to:
public String processATransition(RequestContext requestContext) {
String eventId = ?
if (eventId.equals("PREV")) {
if (currentViewState.equals("search")) {
return "searchParameters";
} else {
return "start";
}
}
}
Any help would be appreciated.
You can get it by:
String eventId = requestContext.getCurrentEvent().getId();
I have modified the onValueChange method of the class ValueChangeHandler, so that I can use it in all the DatePicker that I have in my application, but I would like to know which DatePicker fired the event. How do I get that information?
here is the code of my ValueChangeHandler custom class:
class calendarChangeHandler implements ValueChangeHandler<Date>{
#Override
public void onValueChange(ValueChangeEvent<Date> event) {
endCalendar.hideDatePicker();
initCalendar.hideDatePicker();
Date initDate = initCalendar.getValue();
Date endDate = endCalendar.getValue();
int numDias = 0;
if (initDate != null && endDate != null && (endDate.after(initDate))){
numDias = (int)((endDate.getTime()-initDate.getTime())/MILLSECS_PER_DAY);
createTable(numDias+2);
}
}
}
Thank you very much :)
If you only have a few widgets attached to the handler, it's probably easier to use an if statement:
ValueChangeHandler<Date> handler = new ValueChangeHandler<Date>() {
#Override
public void onValueChange(ValueChangeEvent<Date> event) {
if (box1.equals(event.getSource())) {
//It was box1.
} else {
//It was box2.
}
}
};
Otherwise, just use event.getSource() and cast the result to the desired type:
ValueChangeHandler<Date> handler = new ValueChangeHandler<Date>() {
#Override
public void onValueChange(ValueChangeEvent<Date> event) {
DateBox srouce = (DateBox) event.getSource();
//Do something with the source.
}
};
The getSource() method of ValueChangeEvent should give you who fired the event.
I have a couple of text-boxes on a page where the user can enter some numeric values; however, try as I might, I can't fill those text-boxes with default values - specifically I would like 0.0 displayed in both upon page load.
Here is how I create them and what I have tried -
GroupSection engineering_group = new GroupSection();
KSTextBox engrDesignTextBox = new KSTextBox();
engrDesignTextBox.setWidth("2.875em");
//engrDesignTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrDesignTextBox.setText("0.0"); ==> this doesn't work
engrDesignTextBox.setValue("0.0"); // doesn't work either
KSTextBox engrScienceTextBox = new KSTextBox();
engrScienceTextBox.setWidth("2.875em");
//engrScienceTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrScienceTextBox.setText("0.0"); ==> this doesn't work
engrScienceTextBox.setValue("0.0"); // doesn't work either
I'm thinking that I need to attach an "onload" event listener and then try the setText in there? That seems overkill for something that should be rather simple.
Incidentally, I have attached onBlurHandlers for both these text boxes and they work as expected (see code below)
The following code will simply insert0.0 if the user clicks or tabs out of the text-box while it is EMPTY.
engrDesignTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
engrScienceTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
EDIT : As requested here is how I have defined the setText and setValue methods in KSTextBox
public class KSTextBox extends TextBox implements HasWatermark {
.
.
.
#Override
public void setText(String text) {
String oldValue = super.getText();
if(hasWatermark) {
if(text == null || (text != null && text.isEmpty())){
super.setText(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setText(text);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setText(text);
}
ValueChangeEvent.fireIfNotEqual(this, oldValue, text);
}
#Override
public void setValue(String value) {
if(hasWatermark) {
if(value == null || (value != null && value.isEmpty())){
super.setValue(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setValue(value);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setValue(value);
}
}
So, getting back to the original question, how I do I initially set the values for these textboxes to 0.0?
That should have worked.Its very suprising. Is there a possibility that some other code is resetting the value after you did a setText or a setValue? Try debugging it in hosted mode.Put a breakpoint in setText and see when and how many times it is getting invoked