It's a simple thing I want to do that somehow raises a complex issue.. I'm going insane over this...
I want to compare my Pages field using criteriabuilder; get all that are less than, so use 'le' for numbers ('lessThanOrEqualTo' doesn't work here ).
How can you send an Integer from a Thymeleaf select so that if it is not selected it won't be added to your search criteriaBuilder ?
In the select you're forced by thymeleaf to have a String "undefined" option as a first option. If I use Integer as the field type it won't bind this "undefined" option to the posted model where I would later filter it out from the criteriabuilder. The numbers are OK here though. I need it to work if not selected or undefined.
If I go the other way and choose a String field for Pages then it will not be parsed for ...
le(Expression x, Expression y)
in the CriteriaBuilder. I cannot turn
b.get("pages")
into
Expression<? extends Number> myInteger
I've tried everyway....
<select th:field="*{pages}" ng-model="bookData.pages">
<option selected="selected" value=""> select an option </option>
<option th:each="selectItem: ${refData.pages}"
th:value="${selectItem.value}"
th:text="${selectItem.label}">Pages</option>
</select>
List<Predicate> predList = new LinkedList<Predicate>();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Book> c =cb.createQuery(Book.class);
Root<Book> b = c.from(Book.class);
if( (!pages.equals("")) && (!pages.equals("undefined")) ){
predList.add(cb.lessThanOrEqualTo(b.get("pages"), pages));
}
How could you send an Integer from a Thymeleaf select to be compared in the query so that if not selected doesn't get added to the query?
Ahhhhhhh!
I found the solution by Checking my Angularjs from the form
$scope.processSearchForm = function() {
var aData = $scope.bookData.author;
var gData = $scope.bookData.genre;
var pData = $scope.bookData.pages;
if(typeof pData === 'undefined'){
pData='0';
}
and setting it to '0' if it didn't exist and therefore undefined/unselected.
I then went with Integer for the field, obviously the right approach.
It binds to the model and 0 is filtered out of the Query with the CriteriaBuilder.
Johnny O.
Related
enter image description here I am using ngxdatatable in reactive forms where user can update all the fields in the table. i have three fields/columns for e.g fields a,b and c and they are dynamic as created below:
-- code for ngxdatatable columns
<div [formgroup]= this.form[rowindex]
<ngx-datatable-column *ngFor="let column of columns; let i = index;" name="{{column.name}}" prop="{{column.prop}}">
<ng-template #buttonsTemplate let-row="row" let-value="value" ngx-datatable-cell-template>
<input type =text isReadonly ="isreadonly">
</ng-template>
</ngx-datatable-column></div>
I am facing challenge in defining my validation for field B/column B,
1. **field b** can be autocalculated as number from field a and field c , **b = a+c**, but
user can't enter number manually in field b , on manual input only few strings are allowed like
'test', 'ok', 'any'. how can I achieve this ?
2. I tried to implement it via custom validation which works fine during manual input but it is failing because field/col B is autocalculated it shows error for number which is a valid scenario , as validation is only to be shown when user tries to input manually.
> this.fb.builder{ field a = validtion.Required,
> validation.patter(_number) field c=validtion.Required,
> validation.patter(_number) field b = customValidator }
>
>
> export function customValidator(c:abstract control) :{key:value}{
> if(c.value=='test' || c.value==''any || c.value == 'ok'} return null
>
> else {allowed:false} }
3. I thought of trying to achieve it with keydown event using directive , but not sure how to write a directive which allows words 'any', 'ok', 'test' and not anything else.**please suggest how can i write the directive for this as I am new to angular.**
4. Please suggest if you think any better approach can be used.
I'm trying to set up a simple select dropdown form with Flask. Based on the option chosen, I grab different data from my database, and display it back into a div on my html template. But I can't seem to get the Flask request to register any of the select options. When I print request.form or request.args, I always get empty Dicts. It's probably something simple I'm missing but I can't seem to find the problem. I've gotten this to work with several input and button forms, but I can't get it to work right for selects.
Here is a bit of my html template code, with the form and select. I've tried both GET and POST method in the form.
<div class="options" id="options">
<form class="form-horizontal container-fluid" role="form" method="GET" action="exploresn2.html">
<div class="form-group">
<label for="xaxis" class="col-sm-2 control-label">X-axis:</label>
<div class="col-sm-2">
<select name="xaxis" class="form-control" id="xaxis">
<option selected value="mjd" id="mjd">MJD</option>
<option value="seeing" id="seeing">Seeing</option>
<option value="airmass" id="airmass">Airmass</option>
<option value="hourangle" id="hourangle">Hour Angle</option>
</select>
</div>
</div>
</form>
</div>
In Flask, at first, I tried inside my app
import flask
from flask import request, render_template, send_from_directory, current_app
explore_page = flask.Blueprint("explore_page", __name__)
#explore_page.route('/exploresn2.html', methods=['GET','POST'])
def explore():
xaxis = str(request.args.get("xaxis", "any"))
.... [populate new xaxis variable based on request option selected]
exploreDict['xaxis'] = xaxis
return render_template("exploresn2.html", **exploreDict)
or
mjd = valueFromRequest(key='mjd', request=request, default=None)
if mjd:
mjds = [int(exp.platedbExposure.start_time/(24*3600)) for exp in exposures]
xaxis = mjds
exploreDict['xaxis'] = xaxis
to look for and grab a specific values, or in the first case, any value select. The valueFromRequest is function that grabs data from either GET or POST requests.
but this returns nothing, and then I tried just printing the entire request.args (or request.form) and it returns and empty Dict. Everything I try it still returns empty Dicts. So I'm missing some set up somewhere I think but the form looks right to me?
I'm not sure if this is the actual answer to this problem that I was looking for, but here is what I came up with. I couldn't actually get the Flask to accept a GET request into the original explore method defined, so I implemented a new method in Flask to return a JSON object
#explore_page.route('/getdata', methods=['GET','POST'])
def getData(name=None):
name = str(request.args.get("xaxis", "mjd"))
xaxis = 'populate new xaxis data based on value of name'
data = '(x,y) data array filled with values for plotting'
axisrange = range of x,y data for axes for plot
return jsonify(result=data, range=axisrange)
and then I just made a GET request via javascript to that method whenever the select button changes. So in my exploresn2.html template I have (using Flot for plotting)
$("#xaxis").change(function(){
var newname = $("#xaxis :selected").text();
var axes = plot.getAxes();
options = plot.getOptions();
var plotdata = plot.getData();
// make a GET request and return new data
$.getJSON($SCRIPT_ROOT + '/getdata', {'xaxis':$("#xaxis :selected").val()},
function(newdata){
// set new data
for (var i = 0; i < plotdata.length; ++i) {
plotdata[i].data = newdata.result[plotdata[i].label];
}
// set new axes
axes.xaxis.options.panRange = [newdata.range[0]-50,newdata.range[1]+50];
axes.xaxis.options.axisLabel = newname;
axes.xaxis.options.min = newdata.range[0]-1;
axes.xaxis.options.max = newdata.range[1]+1;
axes.yaxis.options.min = newdata.range[2];
axes.yaxis.options.max = newdata.range[3];
// redraw plot
plot.setData(plotdata);
plot.setupGrid();
plot.draw();
});
});
In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.
Let's say we have a form such as this:
<form id="form">
<select name="single">
<option>Single</option>
<option selected="selected">Single2</option>
</select>
<input type="checkbox" name="check" value="check1" id="ch1">
<input name="otherName" value="textValue" type="text">
</form>
If I do this with the help of jquery
var str = $( "form" ).serialize();
console.log(str);
the result would be
single=Single2&check=check1&otherName=textValue
Is there such functionality in dart's FormElement or I have to code it myself? Thanks.
I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:
First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
Then we will loop through this Map and manually create the resulting string.
The code might look something like this:
FormElement form = querySelector('#my-form'); // To select the form
Map data = {};
// Form elements to extract {name: value} from
final formElementSelectors = "select, input";
form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
data[el.name] = el.value;
});
var parameters = "";
for (var key in data.keys) {
if (parameters.isNotEmpty) {
parameters += "&";
}
parameters += '$key=${data[key]}';
}
Parameters should now contain all the {name: value} pairs from the specified form.
I haven't seen anything like that yet.
In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.
I have a problem that has taken me weeks to resolve and I have not been able to.
I have a class where I have two methods. The following is supposed to take the latest date from database. That date represents the latest payment that a customer has done to "something":
public DateTime getLatestPaymentDate(int? idCustomer)
{
DateTime lastDate;
lastDate = (from fp in ge.Payments
from cst in ge.Customers
from brs in ge.Records.AsEnumerable()
where (cst.idCustomer == brs.idCustomer && brs.idHardBox == fp.idHardbox
&& cst.idCustomer == idCustomer)
select fp.datePayment).AsEnumerable().Max();
return lastDate;
}//getLatestPaymentDate
And here I have the other method, which is supposed to call the previous one to complete a Linq query and pass it to a Crystal Report:
//Linq query to retrieve all those customers'data who have not paid their safebox(es) annuity in the last year.
public List<ReportObject> GetPendingPayers()
{
List<ReportObject> defaulterCustomers;
defaulterCustomers = (from c in ge.Customer
from br in ge.Records
from p in ge.Payments
where (c.idCustomer == br.idCustomer
&& br.idHardBox == p.idHardBox)
select new ReportObject
{
CustomerId = c.idCustomer,
CustomerName = c.nameCustomer,
HardBoxDateRecord = br.idHardRecord,
PaymentDate = getLatestPaymentDate(c.idCustomer),
}).Distinct().ToList();
}//GetPendingPayers
No compile error is thrown here, but when I run the application and the second method tries to call the first one in the field PaymentDate the error mentioned in the header occurs:
Linq to Entities does not recognize the method System.DateTime.. and cannot translate this into a store expression
Please anybody with an useful input that put me off from this messy error? Any help will be appreciated !
Thanks a lot !
Have a look at these other questions :
LINQ to Entities does not recognize the method
LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method
Basically, you cannot use a value on the C# side and translate it into SQL. The first question offers a more thorough explanation ; the second offers a simple solution to your problem.
EDIT :
Simply put : the EF is asking the SQL server to perform the getLatestPaymentDate method, which it has no clue about. You need to execute it on the program side.
Simply perform your query first, put the results into a list and then do your Select on the in-memory list :
List<ReportObject> defaulterCustomers;
var queryResult = (from c in ge.Customer
from br in ge.Records
from p in ge.Payments
where (c.idCustomer == br.idCustomer
&& br.idHardBox == p.idHardBox)).Distinct().ToList();
defaulterCustomers = from r in queryResult
select new ReportObject
{
CustomerId = r.idCustomer,
CustomerName = r.nameCustomer,
HardBoxDateRecord = r.idHardRecord,
PaymentDate = getLatestPaymentDate(r.idCustomer),
}).Distinct().ToList();
I don't have access to your code, obviously, so try it out and tell me if it works for you!
You'll end up with an in-memory list
I'm trying to find a way to get all values and label from drop-down in web page.
With label, I could use:
my #labels = $sel->get_select_options('s');
Return value is array of label in drop-down.
However, there's no equivalent method for getting all values.
Do you guys know how to do this?
As far as in Selenium 1 there is no direct API for this. However you could try this.
Consider a <select> like below.
<select name="mydropdown" id="optionset">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
Below is the snippet in Java to retrieve values. You can get the logic from this snippet and implement it in Perl.
int no_of_options = selenium.getSelectOptions("//select[#id='optionset']").length
String option_values[] = new String[no_of_options];
for (int i=0;i<no_of_options;i++){
String value = selenium.getAttribute("//select[#id='optionset']/option["+i+"]/#value");
option_values[i] = value;
}
Hope this helps.