how to retrieve select options from my database - forms

I'm trying to retrieve my select option from 3 databases located in a connection that's not my defaut connection.
but I'm getting an error : Undefined variable: marqs (View: C:\wamp64\www\projetSovac\resources\views\home.blade.php)
Here's my controller code
public function index()
{
$marques= DB::connection('sqlsrv2')->table('marque')->get();
$modeles = DB::connection('sqlsrv2')->table('Modele')->select( DB::raw('CodeModele'))->get();
$finitions = DB::connection('sqlsrv2')->table('finition')->select( DB::raw('CodeFinition'))->get();
$marqs = $marques->all(['marque']);
$models = $modeles->all(['CodeModele']);
$Finitions = $finitions->all(['CodeModele']);
return View::make('home')
->with(compact($marqs))
->with(compact($models))
->with(compact($Finitions));
return View('home');
}
and my home.blade.php code
<tr class="filters">
<th><input type="text" class="form-control daterangepicker-field" placeholder="Période d'analyse" disabled ></th>
<th><select class="form-control " disabled>
{!! Form::Label('marque', 'marque:') !!}
#foreach($marqs as $marque)
<option value="{{$marque->codeMarque}}">{{$marque->codeMarque}}</option>
#endforeach
</select>
</th>
Can you help identify the problem?
Thanks

compact($marqs) wants to have a string divining the variable you want to pass to the view. Use: compact('marqs') you can also combine your variables like compact('marqs', 'models', ....etc )
Also you are returning something 2 times now in the function this is not possible.
I would rewrite your function to be like this:
$marques= DB::connection('sqlsrv2')->table('marque')->get();
$modeles = DB::connection('sqlsrv2')->table('Modele')->select( DB::raw('CodeModele'))->get();
$finitions = DB::connection('sqlsrv2')->table('finition')->select( DB::raw('CodeFinition'))->get();
$marqs = $marques->all(['marque']);
$models = $modeles->all(['CodeModele']);
$Finitions = $finitions->all(['CodeModele']);
return View::make('home')->with(compact('marqs', 'models', 'Finitions'));
Assuming the first 6 lines get you the actual data all i changed was the return.
You might want to read up on how to use laravel models
https://laravel.com/docs/5.7/eloquent
I am not sure if u have defined any but it could make your code allot simpler.

Related

Flask request not returning any info from select

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();
});
});

How to create a html select in code behind c#?

We need to create html dropdown list dynamically. Following is our current code. Option1 and Option2 are strings that include all the items. The reason we have two strings is we split all the items in two groups.
<td>
<div id="dvGroup" style="display:none;" runat="server"></div>
</td>
string Option1 = "<optgroup label='Group1'><option>1</option><option1>2</option>";
string Option2 = "<optgroup label='Group2'><option>a</option><option>b</option><option>c</option>;
…
dvGroup.InnerHtml = "<Select name='ddGroup' id='ddGroup'>" + Option1 + Option2 + "</Select>";
But by setting InnerHtml will potentially bring some security problem. So I changed it to:
HtmlSelect select = new HtmlSelect();
select.ID = "ddGroup";
select.Name = "ddGroup";
select.ClientIDMode = ClientIDMode.Static;
dvGroup.Controls.Add(select);
select.Controls.Add(new LiteralControl(Option1 + Option2));
However, it threw following error at the line select.Controls.Add…
'System.Web.UI.HtmlControls.HtmlSelect' does not allow child controls.
How do I fix this? Another problem is, setting ClientIDMode to Static only make sure the id is not changed, but name still being added extra stuff. How do I make sure name is not changed either?
You can do this way:
HtmlSelect mHtmlSelect = new HtmlSelect();
mHtmlSelect.ID = "ddGroup";
mHtmlSelect.Name = "ddGroup";
mHtmlSelect.ClientIDMode = ClientIDMode.Static;
String Option1 = "Hello";
String Option2 = "World";
mHtmlSelect.Items.Add(new ListItem(Option1 + Option2));
this.Controls.Add(mHtmlSelect);
Output:
<select name="ddGroup" id="ddGroup">
<option value="HelloWorld">HelloWorld</option>
</select>

How to serialize html form in dart as a string for submission

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.

playframework - how to set a select input in scala

So I have a form on a page, and I am trying to pre load all the old value when the page loads up. But I am having some trouble achieving this for the select object.
I have the following scala code for generating the select:
<select id="networkInterfaces">
<option value="">First Available</option>
#for(interface <- networkInterfaces) {
#if(interface.Name == configs.last.networkInterfaceName) {
<option selected="selected" value="#interface.Name">#interface.DisplayName</option>
} else {
<option value="#interface.Name">#interface.DisplayName</option>
}
}
</select>
And when the page loads it does show that the selected network interface is selected. But the problem is if I change some of my other settings and submit it is returning the options html not the value. Is there a way to select the form value for the select in scala while the page is loading?
Is there something fundamental I am missing? Otherwise I will change the way it is handled to process display name rather than value...
EDIT
As I could not get this to work i changed the value to #interface.DisplayName and then converted it in code on the server. I would like to be able to do it properly but it doesnt seem to work.
Is that correct that <select id="networkInterfaces"> has no name specified?
and than you should use play helper #select and Form object. I think its the better way to handle form values.
#(form : Form[ABean])
#import helper._
#select(
form("configs.last.networkInterfaceName"),
options(networkInterfaces),
'_label -> "Interface Name",
'_default -> "First Available"
)
Further info about helper #select visit :
https://github.com/playframework/Play20/blob/master/framework/src/play/src/main/scala/views/helper/select.scala.html
Try this way.
<input type="hidden" id="groupIdRef" name="groupIdRef" value="#userRecord.groupId">
#input(field=userRecordform("groupId"),'_label -> "") { (id, name, value, htmlArgs) =>
<select id="groupId" name="groupId" #toHtmlArgs(htmlArgs)>
options.map { v =>
#for(g <- groups){
<option value=#g.id >#g.displayName</option>
}
}
</select>
}
// User JavaScript this onload function
window.onload = function() {
document.getElementById('groupId').value = document.getElementById('groupIdRef').value;
}
It is work for me.

(Lift) Ajax submit using SHtml.select onchange event

I'm tring to implement the classic functionality of this select:elements depends on this other select:selection using Lift, E.g. select the country and get the possible states for the selected country.
The problem that I'm facing is that the "this.myForm.submit()" that I have inside the onchange of the select element is not firing the ajax request. If I use an input type"submit" it works perfectly.
Is this behaivior related with Lift framework? Is there a better way of implementing this kind of functionality using Lift libraries?
The relevant snipped code:
"name=distributionPoints" #> SHtml.select(distributionPoints, Empty, selectedDistributionPoint = _, "id" -> "the_distributionPoints") &
"name=devices" #> (SHtml.select(devices, Empty, selectedDevice = _, "id" -> "the_devices") ++ SHtml.hidden(process))
The view html:
<form class="lift:form.ajax">
<select name="distributionPoints" id="the_distributionPoints" onchange="submit()">
<option></option>
</select>
<br/>
Device:
<select name="devices" id="the_devices">
<option></option>
</select>
</form>
The rendered HTML:
<form id="F391649920812YBACEZ" action="javascript://" onsubmit="liftAjax.lift_ajaxHandler(jQuery('#'+"F391649920812YBACEZ").serialize(), null, null, "javascript");return false;">
<div>
Punto de distribución:
<select onchange="submit()" id="the_distributionPoints" name="F630704816482OLP514"></select>
<br />
Equipo:
<select name="F391649920817BLRJW5" id="the_devices"></select><input type="hidden" name="F391649920818HPS35E" value="true" />
<br />
</div>
</form>
[edit]
I finally got the solution. Like Chris mentioned I used ajaxSelect instead of just selects and instead of using setHtml there's a method called JsCmds.ReplaceOptions that does exactly what I was looking for.
You should understand that when using Ajax submit the page is not reloaded. So I would suggest you to use JsCmds.setHtml on server side to "reset" the second select element.
So, in fact the first select is an ajaxSelect which is meant to modify the second one (so it is not concerned by the hidden submit in my opinion). The second select is updated when the first one is changed, using 'selectPoint(s)'
Piece of Scala code
def selectPoint(s):JsCmd = {
selectedDistributionPoint = s;
newDevices:List[String] = findCorrespondingDevices(s);
JsCmds.setHtml("name=devices", SHtml.select(newDevices, Empty, selectedDevice = _, "id" -> "the_devices")) ++ SHtml.hidden(process))
}
"name=distributionPoints" #> SHtml.AjaxSelect(distributionPoints, Empty, s=> selectPoint(s), "id" -> "the_distributionPoints") &
"name=devices" #> (SHtml.select(Nil, Empty, selectedDevice = _, "id" -> "the_devices") ++ SHtml.hidden(process))
Piece of template code
<input name="distributionPoints" id="the_distributionPoints" onchange="submit()"/>
<input name="devices" id="the_devices"/>