JSF Managed Bean Method for actionListener does not have property? - glassfish-3

I know this question is out there a lot, but after reading most of the answers and suggestions I believe I may have strayed from the proper path. Currently the error I am getting is the Following
/categorias.xhtml: The class 'Vista.CategoriaBean' does not have the property 'getcategoriaIDFromCat'.
Stack Trace
javax.el.ELException: /categorias.xhtml: The class 'Vista.CategoriaBean' does not have the property 'getcategoriaIDFromCat'.
I am checking back with JEE as I have not used it in over a year but do not recall how to resolve this error.
I am using JSF 2.2 and have a page given the following:
<ui:repeat value="#{categoriaBean.lista}" var="test">
<article class="row">
<div class="col col-md-12">
<img src="images/Category/#{test.categorianame}.jpg"
alt="#{test.categorianame}" class="img-thumbnail img-responsive img_left"/>
<h4>
<h:outputText value="#{test.categorianame}"/>
</h4>
<p>
<h:outputText value="#{test.categoriadesc}"/>
</p>
<h:form>
<p>
<h:commandButton action="negociosByCat.xhtml" immediate="true"
actionListener="#{categoriaBean.getcategoriaIDFromCat}"
class="btn btn-primary" role="button"
value="Ver #{test.categorianame}"/>
</p>
</h:form>
</div>
</article>
</ui:repeat>
And where the Managed bean is (sorry for the whole class being pasted by I suspect the issue is here):
#ManagedBean
#SessionScoped
public class CategoriaBean implements Serializable{
#EJB
private NegiciosBLLocal negociosBL;
#EJB
private CategoriaBLLocal categoriaBL;
int categoriaID;
Categoria categoria;
List <Categoria> listaCategoria;
List <Negocios> listaNegocios;
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public NegiciosBLLocal getNegociosBL() {
return negociosBL;
}
public void setNegociosBL(NegiciosBLLocal negociosBL) {
this.negociosBL = negociosBL;
}
public CategoriaBLLocal getCategoriaBL() {
return categoriaBL;
}
public void setCategoriaBL(CategoriaBLLocal categoriaBL) {
this.categoriaBL = categoriaBL;
}
public int getCategoriaID() {
return categoriaID;
}
public void setCategoriaID(int categoriaID) {
this.categoriaID = categoriaID;
}
public List<Categoria> getListaCategoria() {
return listaCategoria;
}
public void setListaCategoria(List<Categoria> listaCategoria) {
this.listaCategoria = listaCategoria;
}
public List<Negocios> getListaNegocios() {
return listaNegocios;
}
public void setListaNegocios(List<Negocios> listaNegocios) {
this.listaNegocios = listaNegocios;
}
public CategoriaBean() {categoria=new Categoria();}
public List<Categoria> getLista(){
listaCategoria = categoriaBL.getCategorias();
return listaCategoria;
}
public void getcategoriaIDFromCat (ActionEvent evento){
categoria = listaCategoria.get(Integer.parseInt(evento.getComponent().getClientId().split(":")[1]));
categoriaID=categoria.getCategoriaID();
}
public List<Negocios> getNegociosByCategory(){
listaNegocios = negociosBL.getNegociosByCat(categoriaID);
return listaNegocios;
}
}
When I run this in Glassfish 3.1.2.2 (build 5), can anybody assist?

Related

Why iterate last data from ArrayList<>?

I get data from database perfectly and pass to the Thymeleaf(Template), but the problem is near mdl.addAttribute("number" ,request.getNumber()) in controller to detect last value from foreach loop iteration and send by model
Here down my code:
Dto
public interface ProfileDto {
public Integer getU_id();
public Integer getP_id();
public String getEmail();
public String getUsername();
public String getPassword();
public String getContact();
public String getDate();
public String getProfile();
public String getWebsite();
public String getBio();
public String getGender();
public String getPost();
}
Entity
#Entity
#Table(name = "request_master")
public class Request {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int req_id;
private int sender_id;
private int receiver_id;
private String status;
private String date;
#Transient
private int number;
// getter setter
}
Repository
public interface profileRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value = "SELECT * FROM registration_master rm INNER JOIN profile_master pm ON rm.u_id = pm.user_id WHERE rm.u_id != ?")
List<ProfileDto> findByIdUser(Integer Id);
public interface requestRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value="SELECT * FROM request_master WHERE sender_id = ? and receiver_id = ?")
List<Request> getSuggetionButton(Integer Sender_id, Integer Receiver_id);
}
Service
#Service
public class ServiceImpl implements Service {
#Autowired
private profileRepo profileRepo;
#Autowired
private requestRepo requestRepo;
#Override
public List<ProfileDto> getSuggestedList(Integer Id) {
return this.profileRepo.findByIdUser(Id);
}
#Override
public List<Request> getSuggestionButton(Integer Sender_id, Integer Receiver_id) {
return this.requestRepo.getSuggetionButton(Sender_id, Receiver_id);
}
}
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
if(Friend_request.size() > 0)
{
request.setNumber(Friend_request.size());
}
else
{
request.setNumber(0);
}
}
mdl.addAttribute("number" ,request.getNumber());
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${number}">
</div>
</div>
</div>
</div>
</div>
in below image 1 is for condition matched and find data and 0 is for condition not matched and not find data
In My output i can get only last iterate data in both user
Output:
Expected output:
I think problem is to pass data from controller to thymeleaf
If you have good idea to transfer value from Controller to Template tell me please
You should maintain request for each profile/user instead of having single request, what I mean by that is you should have number of request for each profileId/userId, you can maintain a map of profileId/userId and number of request for that profile/user, and use that map in your template, try to modify your code as below
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
Map<Integer, Integer> profileToNoOfRequestMap = new HashMap<>();
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
profileToNoOfRequestMap.put(Suggestion_id.getU_id(), Friend_request.size());
}
mdl.addAttribute("profileToNoOfRequestMap", profileToNoOfRequestMap);
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${profileToNoOfRequestMap.get(suggetionFriend.u_id)}">
</div>
</div>
</div>
</div>
</div>

Dynamic Property and Child Model Not Binding

I want to build dynamic form using Blazor.
Here is my sample component.
#page "/customform"
#using System.Dynamic
#using System.Text.Json
#inject IJSRuntime JSRuntime;
<div class="card m-3">
<h4 class="card-header">Blazor WebAssembly Form Validation Example</h4>
<div class="card-body">
<EditForm EditContext="#editContext"
OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator></DataAnnotationsValidator>
#foreach (var field in Model.Fields)
{
<div class="form-group">
<label>#field.Name</label>
<input #bind-value="field.Value" class="form-control" />
<ValidationMessage For="(()=> field.Value)" />
<ValidationMessage For="(()=> field.Name)" />
<ValidationMessage For="(()=> field)" />
</div>
}
<div class="form-group">
<label>Address</label>
<input #bind-value="Model.Address" class="form-control" />
<ValidationMessage For="()=> Model.Address" />
</div>
<div class="form-group">
<label>Child</label>
<input #bind-value="Model.ChildModel.ChildName" class="form-control" />
<ValidationMessage For="()=> Model.ChildModel.ChildName" />
</div>
<div class="text-left">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</EditForm>
</div>
</div>
#code{
private SampleModel Model = new SampleModel();
private EditContext editContext;
private ValidationMessageStore _messageStore;
protected override void OnInitialized()
{
editContext = new EditContext(Model);
editContext.OnValidationRequested += ValidationRequested;
_messageStore = new ValidationMessageStore(editContext);
}
private void HandleValidSubmit(EditContext context)
{
var modelJson = JsonSerializer.Serialize(context.Model, new JsonSerializerOptions { WriteIndented = true });
JSRuntime.InvokeVoidAsync("alert", $"SUCCESS!! :-)\n\n{modelJson}");
}
async void ValidationRequested(object sender, ValidationRequestedEventArgs args)
{
_messageStore.Add(editContext.Field("FirstName"), "Test");
_messageStore.Add(editContext.Field("Address"), "Invalid Address");
_messageStore.Add(editContext.Field("ChildModel.ChildName"), "Invalid Child Name");
editContext.NotifyValidationStateChanged();
}
public class SampleModel
{
public string Address { get; set; }
public ChildModel ChildModel { get; set; }
public List<Field> Fields { get; set; }
public SampleModel()
{
this.ChildModel = new ChildModel();
this.Fields = new List<Field>();
this.Fields.Add(new Field()
{
Name = "FirstName",
Value = "",
ControlType = ControlType.Input
});
this.Fields.Add(new Field()
{
Name = "LastName",
Value = "",
ControlType = ControlType.Input
});
}
}
public class ChildModel
{
public string ChildName { get; set; }
}
public enum ControlType
{
Input
}
public class Field
{
public string Value { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public ControlType ControlType { get; set; }
}
}
Currently I am facing too many issues.
If I use For lookup instead of For each it is not working
ChildModel seems to be bind but its validation is not working
Dynamically generated based on Fields collection control does not display validation.
Only address in SimpleModel display validation.
Is there any suggestion or help around this ?
Your profile suggests you know what you're doing, so I'll keep this succinct.
Your for loop needs to look something like this. Set a local "index" variable within the loop to link the controls to. If you don't they point to the last value of i - in this case 2 which is out of range! The razor code is converted to a cs file by the razor builder. You can see the c# file generated in the obj folder structure - obj\Debug\net5.0\Razor\Pages. Note, the linkage of the Validation Message
#for(var i = 0; i < Model.Fields.Count; i++)
{
var index = i;
<div class="form-group">
<label>#Model.Fields[index].Name</label>
<input #bind-value="Model.Fields[index].Value" class="form-control" />
<ValidationMessage For="(()=> Model.Fields[index].Value)" />
</div>
}
Now the message validation store. Here's my rewritten ValidationRequested. Note I'm creating a FieldIdentifier which is the correct way to do it. "Address" works because it's a property of EditContext.Model. If a ValidationMessage doesn't display the message you anticipate, then it's either not being generated, or it's FieldIdentifier doesn't match the field the ValidationMessage is For. This should get you going in whatever project you're involved in - if not add a comment for clarification :-).
void ValidationRequested(object sender, ValidationRequestedEventArgs args)
{
_messageStore.Clear();
_messageStore.Add(new FieldIdentifier(Model.Fields[0], "Value"), "FirstName Validation Message");
_messageStore.Add(new FieldIdentifier(Model.Fields[1], "Value"), "Surname Validation Message");
_messageStore.Add(editContext.Field("FirstName"), "Test");
_messageStore.Add(editContext.Field("Address"), "Invalid Address");
_messageStore.Add(editContext.Field("ChildModel.ChildName"), "Invalid Child Name");
editContext.NotifyValidationStateChanged();
}
If you interested in Validation and want something more that the basic out-of-the-box validation, there's a couple of my articles that might give you info Validation Form State Control or there's a version of Fluent Validation by Chris Sainty out there if you search.

Blazor Server side, set parent class name based on child class name

I have a EditForm with MatBlazor Expansion panels. I am trying to set the individual panels border color if any of the form fields are invalid inside it. I am trying to achieve following..
<MatExpansionPanel Class="#(<bool>ChildElementHasValidationMessage() ? "invalid-red-border": "")">.....</MatExpansionPanel>
I am OK with simple equivalent css solution to find a parent element. Please advice.
Just use Style instead Class to override css:
<MatExpansionPanel Style="#(your expression);"
I answered a related question about MatExpansionPanel: Mat Blazor mat-expansion-panel remove elevation/border
Edited
I wrote my own component to send EditContext on changes. I pasted it below. This is how it works:
<h1>#ShowDemo</h1>
<EditForm Model="#model" OnValidSubmit="#SaveItem">
<DataAnnotationsValidator />
<ValidationSummary />
<MyValidationSneak UpdateDelegate="#( (ctx)=>UpdateUI(ctx) )" />
<InputText id="ItemName" #bind-Value="#model.ItemName" />
<ValidationMessage For="#(() => model.ItemName)" />
<button type="submit">Submit</button>
</EditForm>
#code {
string ShowDemo = "res de res";
protected void UpdateUI(EditContext ctx)
{
var _fieldIdentifier = FieldIdentifier.Create( () => model.ItemName );
ShowDemo = string.Join(", ", ctx.GetValidationMessages(_fieldIdentifier) );
}
ItemModel model = new ItemModel();
private void SaveItem() { }
public class ItemModel
{
[Required]
public string ItemName{ get; set; }
}
}
See it in action at BlazorFiddle:
The MyValidationSneak:
public class MyValidationSneak: ComponentBase, IDisposable
{
[CascadingParameter] EditContext CurrentEditContext { get; set; }
[Parameter] public Action<EditContext> UpdateDelegate { get; set; }
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
public MyValidationSneak()
{
_validationStateChangedHandler = (sender, eventArgs) => GoUpdate();
}
private void GoUpdate() => UpdateDelegate(CurrentEditContext);
private EditContext _previousEditContext;
protected override void OnParametersSet()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException($"{nameof(ValidationSummary)} requires a cascading parameter " +
$"of type {nameof(EditContext)}. For example, you can use {nameof(ValidationSummary)} inside " +
$"an {nameof(EditForm)}.");
}
if (CurrentEditContext != _previousEditContext)
{
DetachValidationStateChangedListener();
CurrentEditContext.OnValidationStateChanged += _validationStateChangedHandler;
GoUpdate();
_previousEditContext = CurrentEditContext;
}
}
protected virtual void Dispose(bool disposing) {}
void IDisposable.Dispose()
{
DetachValidationStateChangedListener();
this.Dispose(disposing: true);
}
private void DetachValidationStateChangedListener()
{
if (_previousEditContext != null)
{
_previousEditContext.OnValidationStateChanged -= _validationStateChangedHandler;
GoUpdate();
}
}
}
Get code at github

How to display values in a List of a SlingModel using Sightly

I am not able to display values in a lit that are part of a POJO/SlingModel. Please help.
Desired Output
Commodity 1
Product 1, Product 2, Product 3
Commodity 2
Product 2, Product 4, Product 5
Sightly Code
<!-- LIST :: SLING MODEL -- FINAL -->
<div data-sly-
use.model="${'com.tti.tticommons.service.models.LeadTimeTrendsModel' #
rawJson=ws.JSON}" data-sly-unwrap>
<div data-sly-list.commodity="${model.getProductsList}">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Sling Model(List) - ${commodity.name #
context='html'}</h3>
</div>
<div class="panel-body" data-sly-
list.pr="${model.getProductsList.getProducts}">
<div class="col-md-4 col-sm-12 industry list-group no-
border">
<div>
<a class="">
${model.getProductsList.getProducts[pr]}
</a>
</div>
</div>
</div>
</div>
</div>
</div>
My Sling Model Class
public class LeadTimeTrends {
private List<Commodity> productsList;
public List<Commodity> getProductsList() {
...business logic...
...........
return productsList;
}
public class Commodity {
public String code;
public String name;
public LinkedHashMap<String, Product> products;
public void Commodity(String code, String name, LinkedHashMap<String,
Product> products) {
this.code=code;
this.name=name;
this.products=products;
}
public LinkedHashMap<String, Product> getProducts() {
return this.products;
}
}
/***/
public class Product {
public String code;
public String name;
public Product() {
}
public Product(String code, String name) {
this.code=code;
this.name=name;
}
}
}
After some research and careful checks i found the solution to be working.
Output as desired
Here's the final code:
Sightly code block
<!-- LIST :: SLING MODEL -- FINAL -->
<div data-sly-use.model =
"${'com.tti.tticommons.service.models.LeadTimeTrendsModel' #
rawJson=ws.JSON, configurationId='leadtimetrends', webService=ws}"
data-sly-unwrap>
<div data-sly-list.commodity="${model.getProductsList}" data-sly-unwrap>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Sling Model(List) - ${commodity.name #
context='html'}</h3>
</div>
<div class="panel-body" data-sly-list.product =
"${commodity.products}">
<div class="col-md-4 col-sm-12 industry
list-group no-border">
<div>
<a class="">
${product.name}
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Sling Model Class
/** Sling Model class */
#Model(adaptables={Resource.class, SlingHttpServletRequest.class})
public class LeadTimeTrends {
private List<Commodity> productsList;
/** */
public List<Commodity> getProductsList() {
List<Commodity> productsList = buildProductsList(this.rawJson);
return productsList;
}
/** */
public List<Commodity> buildProductsList(String rawJson){
List<Commodity> productList = new ArrayList<Commodity>();
....business logic....
......................
return productList;
}
/** */
public class Commodity {
public String code;
public String name;
public List<Product> products;
public void Commodity() {
}
public void Commodity(String code, String name, List<Product> products)
{
this.code=code;
this.name=name;
this.products=products;
}
}
/** */
public class Product {
public String code;
public String name;
public Product() {
}
public Product(String code, String name) {
this.code=code;
this.name=name;
}
}

seam create drop down menu for a form, error

I am trying to create 3 drop down menu for a form. First one, is LOB field. Second one is Application field and last one is CTA field. There is one to many relationship between LOB and Application. There is many to many relationship from Application to CTA.
CreateRequest.xhtml
<h:selectOneMenu id="lobField" value="#{manager.lob}" required="true">
<s:selectItems var="lob" value="#{lobs}" label="#{lob.lobDescription}" noSelectionLabel="Select LOB"></s:selectItems>
<s:convertEntity />
<a:support action="#{manager.loadApps}" ajaxSingle="true" event="onchange" reRender="appField,ctaField"/>
</h:selectOneMenu>
<a:outputPanel id="appField">
<h:selectOneMenu value="#{manager.app}" required="true">
<s:selectItems var="app" value="#{manager.applications}" label="#{app.applicationName}" noSelectionLabel="Select Application"></s:selectItems>
<s:convertEntity />
<a:support action="#{manager.loadCtas}" ajaxSingle="true" event="onchange" reRender="ctaField"/>
</h:selectOneMenu>
</a:outputPanel>
<a:outputPanel id="ctaField">
<h:selectOneMenu value="#{manager.cta}" required="true">
<s:selectItems var="cta" value="#{manager.ctas}" label="#{cta.ctaDescription}" noSelectionLabel="Select CTA"></s:selectItems>
<s:convertEntity />
</h:selectOneMenu>
ManagerBean.java
#Stateful
#Name("manager")
public class ManagerBean implements Manager {
#Logger
private Log log;
#In
StatusMessages statusMessages;
private Lob lob;
private Application app;
private Cta cta;
#PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager entityManager;
#Out(required = false)
private List<Lob> lobs;
private List<Application> applications;
private List<Cta> ctas;
public void CreateRequest() {
System.out.println("Create Request");
System.out.println(app.getApplicationName());
}
public Lob getLob() {
return lob;
}
public void setLob(Lob lob) {
this.lob = lob;
}
public Application getApp() {
return app;
}
public void setApp(Application app) {
this.app = app;
}
public Cta getCta() {
return cta;
}
public void setCta(Cta cta) {
this.cta = cta;
}
public List<Lob> getLobs() {
return lobs;
}
public void setLobs(List<Lob> lobs) {
this.lobs = lobs;
}
public List<Application> getApplications() {
return applications;
}
public void setApplications(List<Application> applications) {
this.applications = applications;
}
public List<Cta> getCtas() {
return ctas;
}
public void setCtas(List<Cta> ctas) {
this.ctas = ctas;
}
#Destroy
#Remove
public void destroy() {
}
#Factory("lobs")
public void loadLobs() {
lobs = entityManager.createQuery("from Lob").getResultList();
}
public void loadApps() {
System.out.println("load apps called");
applications = lob.getApplicationList();
}
public void loadCtas() {
System.out.println("load ctas called====");
ctas = app.getCtaList();
System.out.println(ctas.size());
}
}
I am able to select a value from LOB, and loadApps is called. Then I am able to select applications, too. But when I select one, I get following error:
19:09:01,921 INFO [lifecycle] WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.
sourceId=managerForm:appField[severity=(ERROR 2), summary=(value is not valid), detail=(value is not valid)]
I am unable to figure out what mistake I am making here.
Are you in a conversation? Without specifying a scope your SFSB will be in the conversation context. Have you started the conversation?

Resources