selectOneMenu choose everything and depending on a column - sql

hi i have a question i have a selectOneMenu and depending on the value chosen i display my datatable but i want when i open my jsf page at first to display all the rows and also if i choose everything in the selectOneMenu to display all the rows. how i could do that.
JSF :
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Annee : " style="font-size: 18px" />
<p:selectOneMenu value="#{anneeBean.annee}" >
<f:selectItem itemValue="#{null}" itemLabel="--Séléctionner une année--" />
<f:selectItems value="#{anneeBean.listeAnnees}" var="annee"
itemValue="#{annee}" itemLabel="#{annee}" />
<f:ajax listener="#{anneeBean.submit()}" render="display" />
</p:selectOneMenu>
</h:panelGrid>
Hibernate
#Override
public List getAllBudgets(Integer id) {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Budgetisation as b left join fetch b.rubrique as r left join fetch b.annee where b.id.annee=:annee");
q.setParameter("annee", id);
listeBudgets = q.list();
return listeBudgets;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}

Related

Select Option (for dropdown) Laravel

I make a dropdown for a form, I will show the code below. However, when I click the submit button, there is an error saying,
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'brand' cannot be null (SQL: insert into supplier_details.
The data that I chose from the dropdown is actually null. Actually, I'm new to Laravel.
I don't want to make a dropdown list from a database, I just want to display the option and the option will be inserted into the database when the user clicks the submit button after filling in the form.
<div class="form-group row">
<label style="font-size: 16px;" for="id" class = "col-sm-2">Item Brand </label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<select name="brand" class="form-control js-example-basic-single" required>
<option >Please select item brand</option>
<option value="machine1"> Item Brand 1 </option>
<option value="machine1"> Item Brand 2 </option>
<option value="machine1"> Tem Brand 3 </option>
</select>
</div>
</div>
Controller
public function createsupplierdetails()
{
return view ('frontend.praiBarcode.getweight');
}
public function supplierdetails(Request $r)
{
$details = new SupplierDetail;
$getuserPO = Supplier::where('PO',$r->PO)->first();
$details->brand = $getuserPO->brand;
$details->container_no = $getuserPO->container_no;
$details->date_received = $getuserPO->date_received;
$details->gross_weight = $getuserPO->gross_weight;
$details->tare_weight = $getuserPO->tare_weight;
$details->net_weight = $getuserPO->net_weight;
$details->save();
return view ('frontend.praiBarcode.viewsupplierdetails')
->with('details',$details);
}
This to check to verify if it is working:
Make sure you are submitting the correct form.
Try doing dd on your controller dd($request->all())
If data is reaching the controller and not inserted into the database, check on your model, if it is added to fillable or if there is only id in the guarded array. You can know about more here in https://laravel.com/docs/9.x/eloquent#mass-assignment
Error should be fixed, as soon as you fix it.
Controller
use Validator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'brand' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->with('error', $validator->errors()->first());
}
$details = new SupplierDetail();
$details->brand = $request->brand;
$details->container_no = $request->container_no;
$details->date_received = $request->date_received;
$details->gross_weight = $request->gross_weight;
$details->tare_weight = $request->tare_weight;
$details->net_weight = $request->net_weight;
$details->save();
if ($trending) {
return redirect(route('details.index'))->with('success', 'Field added successfully');
} else {
return redirect()->back()->with('error', 'Field has been not added successfully');
}
}

ASP.NET Razor split record and increase by one

in my code I'm trying to display in a text box the record that follows the last one of my database. For example, if my last record is A560 I want to display A561. To achieve this I know I have to split the record and then manipulate it, but I haven't had any luck. Here is what the database looks like:
Point_ID Project No. Project Manager Comments
A558 1304 Oscar Duran Found destroyed
A559 1304 Oscar Duran Helicopter access
A560 1356 Julio Bravo Airport parking lot
This is my code so far:
#{
Layout = "~/_Layout.cshtml";
var db = Database.Open("ControlPoints");
var SelectCommand = "SELECT * FROM( SELECT TOP 5 * FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC )AS BaseData Order BY Point_ID ASC";
var SearchTerm = "";
if(!Request.QueryString["SearchCP"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE Point_ID = #0";
SearchTerm = Request.QueryString["SearchCP"];
}
if(!Request.QueryString["SearchProject"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE [Project Used on] LIKE #0";
SearchTerm = "%" + Request["SearchProject"] + "%";
}
var SelectData = db.Query(SelectCommand, SearchTerm);
var grid = new WebGrid(source: SelectData, rowsPerPage: 10);
}
#{
Validation.RequireField("Point_ID", " Required");
Validation.RequireField("ProjectNo", " Required");
Validation.RequireField("ProjectManager", " Required");
var Point_ID = "";
var ProjectNo = "";
var ProjectManager = "";
if(IsPost && Validation.IsValid() ){
Point_ID = Request.Form["Point_ID"];
ProjectNo = Request.Form["ProjectNo"];
ProjectManager = Request.Form["ProjectManager"];
db = Database.Open("ControlPoints");
var InsertCommand = "INSERT INTO AllControlMergedND ([Point_ID], [Project No.], [Project Manager]) VALUES(#0, #1, #2)";
db.Execute(InsertCommand, Point_ID, ProjectNo, ProjectManager);
}
var SelectLastCP = "SELECT TOP 1 Point_ID FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC";
var SelectData2 = db.QuerySingle(SelectLastCP);
var SuggestedPoint_ID = SelectData2.Point_ID;
}
<h2>Airborne Imaging Control Points Database</h2><br/><br/>
<form method="get">
<fieldset>
<legend>Search Criteria</legend>
<div>
<p><label for="SearchCP">Control Point ID:</label>
<input type="text" name="SearchCP" value="#Request.QueryString["SearchCP"]" />
<input type="submit" value="Search"/></p>
</div>
<div>
<p><label for="SearchProject">Project:</label>
<input type="text" name="SearchProject" value="#Request.QueryString["SearchProject"]" />
<input type="Submit" value="Search" /></p>
</div>
</fieldset>
</form>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Point_ID"),
grid.Column("Project No."),
grid.Column("Project Used on"),
grid.Column("WGS84 Lat"),
grid.Column("WGS84 Long"),
grid.Column("Ellips_Ht"),
grid.Column("Project Manager"),
grid.Column("Comments")
)
)
<br/><br/>
</div>
<form method="post">
<fieldset>
<legend>Create Control Point(s)</legend>
<p><label for="Point_ID">Point ID:</label>
<input type="text" name="Point_ID" value="#SuggestedPoint_ID" />
#Html.ValidationMessage("Point_ID")</p>
<p><label for="ProjectNo">Project No:</label>
<input type="text" name="ProjectNo" value="#Request.Form["ProjectNo"]" />
#Html.ValidationMessage("ProjectNo")</p>
<p><label for="ProjectManager">Project Manager:</label>
<input type="text" name="ProjectManager" value="#Request.Form["ProjectManager"]" />
#Html.ValidationMessage("ProjectManager")</p>
<p><input type="submit" name="ButtonConfirm" value="Confirm" /></p>
</fieldset>
</form>
As you can see, all I am able to do is to display the last record of my database in the text box, which in this case would be A560. The variable 'SuggestedPoint_ID' is holding that record. I have tried converting the data type, but had no success. Any help would be greatly appreciated.
Update:
What I need is to do the following. Split A560 in two parts 'A' and '560'. Then increment '560' by one to obtain '561' and finally attach 'A' again to '561' in order to obtain the next increment 'A561'.
If you are trying to convert "A560" to int for example then it won't work because you don't have a valid number. A needs to be removed.
var SuggestedPoint_ID = SelectData2.Point_ID.Replace("A", "");
This is not my recommended way to do it as A could be anything such as AA or B or ZZZZ. My point is that you need to describe what you need to get a better solution to your problem.
UPDATE
var source = "A560";
var lhs = source.Substring(0, 1);
var tmp = source.Replace(lhs, "");
int rhs;
if(int.TryParse(tmp, out rhs))
{
rhs++;
}
var result = string.Format("{0}{1}", lhs, rhs);

Get list with cc.attrs and ValueExpression on CompositeComponent JSF

I should create a composite component and insert it in a parent component. I tried to find the answer to my problem on stackOverflow and i found this:
Add programmatically composite component in backing bean
So, I create the composite component:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://xmlns.jcp.org/jsf/passthrough"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:ic="http://java.sun.com/jsf/composite/inputComponent">
<composite:interface>
<composite:attribute name="idPanel" required="true" />
<composite:attribute name="typeBSPanel" default="default" />
<composite:attribute name="idPanelHeading" required="true" />
<composite:attribute name="idPanelBody" required="true" />
<composite:attribute name="listInputText" required="true"
shortDescription="Questo componente è un Panel con un numero variabile di InputText di tipo Text, Number e DropDown. Questa lista deve contenere degli oggetti con le seguenti proprietà: label, value e placeholder."></composite:attribute>
<composite:attribute name="objectBindToPanel" required="true" />
</composite:interface>
<composite:implementation>
<div class="panel-group" id="accordion">
<div id="#{cc.attrs.idPanel}"
class="panel panel-#{cc.attrs.typeBSPanel}">
<div id="#{cc.attrs.idPanelHeading}" class="panel-heading">
<button type="button" class="btn btn-#{cc.attrs.typeBSPanel}"
data-toggle="collapse" data-target="#collapseBodyPanel">
+/-</button>
</div>
<div id="collapseBodyPanel" class="panel-collapse collapse in">
<div id="#{cc.attrs.idPanelBody}" class="panel-body">
<ui:repeat var="inputText" value="#{cc.attrs.listInputText}">
<ic:inputTextBS preAddon="#{inputText.label}"
requiredMessage="This field must not be empty"
placeholder="#{inputText.placeholder}"
value="#{cc.attrs.objectBindToPanel[inputText.value]}" required="true">
</ic:inputTextBS>
</ui:repeat>
</div>
</div>
</div>
</div>
</composite:implementation>
</html>
the class and the method to add the composite component dinamically:
public class CCUtility {
public static void includeCompositeComponent(UIComponent parent, String libraryName, String resourceName, String id, Map<String, String> mapValueExpression) {
// Prepare.
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
FaceletContext faceletContext = (FaceletContext) context.getAttributes().get("javax.faces.FACELET_CONTEXT");
// This basically creates <ui:component> based on <composite:interface>.
Resource resource = application.getResourceHandler().createResource(resourceName, libraryName);
UIComponent composite = application.createComponent(context, resource);
composite.setId(id); // Mandatory for the case composite is part of UIForm! Otherwise JSF can't find inputs.
ExpressionFactory factory = application.getExpressionFactory();
ELContext ctx = context.getELContext();
for (Map.Entry<String, String> entry : mapValueExpression.entrySet()) {
ValueExpression expr = factory.createValueExpression(ctx, entry.getValue(), String.class);
composite.setValueExpression(entry.getKey(), expr);
//composite.getAttributes().put(entry.getKey(), entry.getValue());
}
// This basically creates <composite:implementation>.
UIComponent implementation = application.createComponent(UIPanel.COMPONENT_TYPE);
implementation.setRendererType("javax.faces.Group");
composite.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, implementation);
// Now include the composite component file in the given parent.
parent.getChildren().add(composite);
parent.pushComponentToEL(context, composite); // This makes #{cc} available.
try {
faceletContext.includeFacelet(implementation, resource.getURL());
} catch (IOException e) {
throw new FacesException(e);
}
}
}
and I call the previous method in another class that pass the map of Attributes I want for the composite component:
public void addPanelHostMachine(){
this.dataCenterController.getDataCenter().getGroupsHost().add(indexGroupHostMachine, new GroupHost());
Map<String, String> mapValueExpression = new HashMap<String, String>();
mapValueExpression.put("idPanel", "panelHostMachine" + indexGroupHostMachine);
mapValueExpression.put("idPanelHeading", "panelHostMachineHeading" + indexGroupHostMachine);
mapValueExpression.put("idPanelBody", "panelHostMachineBody" + indexGroupHostMachine);
mapValueExpression.put("typeBSPanel", "success");
mapValueExpression.put("listInputText", "#{dataCenterController.dataCenter.groupsHost.get(" + indexGroupHostMachine + ").listOfInputText}");
mapValueExpression.put("objectbindToPanel", "#{dataCenterController.dataCenter.groupsHost.get(" + indexGroupHostMachine + ")}");
CCUtility.includeCompositeComponent(panelBodyDataCenter, "panelComponent", "panelComponent.xhtml", "ccPanelHostMachine" + indexGroupHostMachine, mapValueExpression);
indexGroupHostMachine = indexGroupHostMachine + 1;
}
Now the problem is that when I try to add the CompositeComponent I get this error:
Grave: Servlet.service() for servlet [Faces Servlet] in context with path [/IcaroKBMassiveEditor] threw exception [/resources/panelComponent/panelComponent.xhtml #34,79 preAddon="#{inputText.label}": Property 'label' not found on type java.lang.String] with root cause
javax.el.PropertyNotFoundException: Property 'label' not found on type java.lang.String
I think that it's a problem with EL expression and 'composite:attribute' but I don't know how to fix this. Can anyone help me?
I find the solution in this post: DataTable Inside Composite Component.
Instead of:
for (Map.Entry<String, String> entry : mapValueExpression.entrySet()) {
ValueExpression expr = factory.createValueExpression(ctx, entry.getValue(),String.class);
composite.setValueExpression(entry.getKey(), expr);
}
I used:
for (Map.Entry<String, String> entry : mapValueExpression.entrySet()) {
ValueExpression expr = factory.createValueExpression(ctx, entry.getValue(),Object.class);
composite.setValueExpression(entry.getKey(), expr);
}
I replaced String.Class to Object.class in funciton call factory.createValueExpression

pass an ID with hyperlik but cant get this ID value from a fk in one table when i click in insert

Something strange happened in my codes, actually I have a hyperlink that pass ID value in a query string to second page.in second page i have 2 sql datasource that both these sql datasources should get this id value and pass it to a filter parameter to show sth in datalist.
so in another word I have a first page that has an hyperlink read ID value from a datasource and pass it to second page.its like below:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/forumpage.aspx?ID="+Eval("ID")%>'><%#Eval("title")%> </asp:HyperLink>
then in second page i have one sql datasource with a query like this ...where ID=#id and get this id in query string from db.it work great . but i have problem with second sql datasource in second page it has a query sth like below:...forms.question_id=#id
then in sql reference both to query string as ID that get by first page in hyperlink.
but when i click in insert button show me error with fk.
error:Error:The INSERT statement conflicted with the FOREIGN KEY
constraint "FK_forumreply_forumquestions". The conflict occurred in
database "forum", table "dbo.forumquestions", column 'ID'. The
statement has been terminated.
my tables
(question(ID,user_id(fk),Cat_id(fk),title,bodytext)
(reply(ID,userr_id(fk),questionn_id(fk),titlereply,bodytestreply);
When by hand in cb i gave a number in questionn_id like 1 it show me successful but when it want read from a filter by datasource this field face with problem.
plzzzz help i really need skip from this part.and cause i am new i guess I cant understand the logic way clearly.
<asp:SqlDataSource ID="sdsreply" runat="server"
ConnectionString="<%$ ConnectionStrings:forumConnectionString %>"
SelectCommand="SELECT forumreply.ID, forumreply.userr_id, forumreply.questionn_id, forumreply.bodytextreply, forumreply.datetimereply, forumquestions.ID AS Expr1, forumusers.ID AS Expr2, forumusers.username FROM forumquestions INNER JOIN forumreply ON forumquestions.ID = forumreply.questionn_id INNER JOIN forumusers ON forumquestions.user_id = forumusers.ID AND forumreply.userr_id = forumusers.ID where forumreply.questionn_id=#questionn_id">
<SelectParameters>
<asp:QueryStringParameter Name="questionn_id" QueryStringField="ID" />
</SelectParameters>
</asp:SqlDataSource>
it is cb for second page in insert button:
{
if (Session["userid"] != null)
{
lblreply.Text = Session["userid"].ToString();
}
else
{
Session["userid"]=null;
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
lblshow.Text = string.Empty;
string d = HttpContext.Current.User.Identity.Name;
lblshow.Text =d + "عزیز خوش آمدید." ;
foreach (DataListItem item in DataList2.Items)
{
Label questionn_idLabel = (Label)item.FindControl("questionn_idLabel");
Label userr_idLabel = (Label)item.FindControl("userr_idLabel");
lbltest.Text = string.Empty;
lbltest.Text = questionn_idLabel.Text;
lblreply.Text = string.Empty;
lblreply.Text = userr_idLabel.Text;
}
}
else
{
lblshow.Text = "اگر بار اول هست که می خواهید پاسخ دهید لطفا ابتدا ثبت نام و سپس لاگین فرمائید.";
}
}
{
if(HttpContext.Current.User.Identity.IsAuthenticated)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["forumConnectionString"].ConnectionString);
try
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into forumreply (userr_id,questionn_id,bodytextreply,datetimereply)values(#userr_id,#questionn_id,#bodytextreply,#datetimereply)", con);
cmd.Parameters.AddWithValue("userr_id",lblreply.Text);
cmd.Parameters.AddWithValue("questionn_id",lbltest.Text);
cmd.Parameters.AddWithValue("bodytextreply",txtbody.Text);
cmd.Parameters.AddWithValue("datetimereply",DateTime.Now );
cmd.ExecuteNonQuery();
}
catch (Exception exp)
{
Response.Write("<b>Error:</b>");
Response.Write(exp.Message);
}
finally
{
con.Close();
}
lblmsg.Text = "پیام شما با موفقیت ثبت گردید.thx";
lblshow.Visible = false;
//lbltxt.Text = txtbody.Text;
txtbody.Text = string.Empty;
}
}
else
{
lblmsg.Text = string.Empty;
Session["rem"] = Request.UrlReferrer.AbsoluteUri;
Response.Redirect("~/login.aspx");
}
}

Left OuterJoin in Entity/Linq

So I am deeply confused. I have two tables, one is locations assignments which consists of: location id, type and type id. I also have a table called services, which consists of name, id , description and icon.
The idea is to say, get me back all 13 services, from that we create 13 checkboxes. then we say, check the location assignments table, if this services (based on type, id and location id) matches a service in that list, check the checkbox, else leave it unchecked.
What I ahve so far is:
public static IEnumerable<Constants.Assignable> getAllService(int id)
{
List<Constants.Assignable> assign = new List<Constants.Assignable>();
using (var db = new Context())
{
var serv = from s in db.Services
join la in db.LocationAssignments on s.id equals la.typeId into LocationAssignments
from la in LocationAssignments
where la.locationId == id && s.id == la.typeId && la.type == Constants.SERV
select s;
foreach(var s in serv)
{
assign.Add(new Constants.Assignable(){
id = s.id, name = s.name
});
}
return assign;
}
}
which returns me, currently, two services, when it should return me 13. So there is something wrong with my join.
from there we do:
<h3 class="muted">Services Nearby</h3>
IEnumerable<UFA.Location.Core.Constants.Assignable> ServicesNearby = UFALocationApp.Helpers.LocationHelper.QueryHelper.getAllServicesNearby(Model.id);
foreach (var servicenb in ServicesNearby)
{
<div class="control-group">
<label class="control-label" for="serviceNearBy">
#servicenb.name
</label>
<div class="controls">
<input type="checkbox" id="Locationservice" value="#servicenb.id" name="serviceNB" checked="#(servicenb.assigned ? "checked" : "")" />
</div>
</div>
}
which prints out the two check boxes that are, in this case checked. there should be 11 more that are unchecked.
What do I have to change in my query to say: get me all services and only check off the ones associated with this location?
To make it a LEFT JOIN, you need to use DefaultIfEmpty(), it seems that the component you're missing to make this work;
var serv = from s in db.Services
join la in db.LocationAssignments on s.id equals la.typeId
into LocationAssignments
from la in LocationAssignments.DefaultIfEmpty()
where la.locationId == id && s.id == la.typeId
&& la.type == Constants.SERV
select s;
If I read you well you're after something like this:
var assign = (from s in db.Services
select new Constants.Assignable
{
id = s.id,
name = s.name,
checked= db.LocationAssignments.Any(la => la.typeId == s.id)
}).ToList();
Now you can change the value of checked by clicking the checkbox and process the changes when you post back.