Skip to content

Instantly share code, notes, and snippets.

@jyeary
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyeary/1188d01f30d77f0dbc24 to your computer and use it in GitHub Desktop.
Save jyeary/1188d01f30d77f0dbc24 to your computer and use it in GitHub Desktop.
Customized SelectItem with additional attributes from HTML specification that are not present in JSF 2.2 RI.
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/*
* (C) Copyright International Business Machines Corp., 2001,2002
* The source code for this program is not published or otherwise
* divested of its trade secrets, irrespective of what has been
* deposited with the U. S. Copyright Office.
*/
/*
* Copyright 2015 John Yeary <jyeary@bluelotussoftware.com>.
*/
package com.bluelotussoftware.renderer;
import com.bluelotussoftware.component.HtmlOption;
import com.sun.faces.renderkit.html_basic.MenuRenderer;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import javax.faces.render.Renderer;
/**
* A custom {@link Renderer} for Menus to allow the addition of attributes to an
* HTML {@literal <option>} element.
*
* @author John Yeary <jyeary@bluelotussoftware.com>
* @version 1.0
*/
public class CustomMenuRenderer extends MenuRenderer {
/**
* Default constructor.
*/
public CustomMenuRenderer() {
}
/**
* {@inheritDoc}
*/
@Override
protected boolean renderOption(FacesContext context, UIComponent component, UIComponent selectComponent, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, OptionComponentInfo optionInfo) throws IOException {
Object valuesArray;
Object itemValue;
String valueString = getFormattedValue(context, component,
curItem.getValue(), converter);
boolean containsValue;
if (submittedValues != null) {
containsValue = containsaValue(submittedValues);
if (containsValue) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
boolean isSelected = isSelected(context, component, itemValue, valuesArray, converter);
if (optionInfo.isHideNoSelection()
&& curItem.isNoSelectionOption()
&& currentSelections != null
&& !isSelected) {
return false;
}
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
writer.writeText("\t", component, null);
writer.startElement("option", (null != selectComponent) ? selectComponent : component);
if (curItem instanceof HtmlOption) {
HtmlOption option = (HtmlOption) curItem;
if (option.getId() != null && !option.getId().isEmpty()) {
writer.writeAttribute("id", option.getId(), "id");
}
if (option.getTitle() != null && !option.getTitle().isEmpty()) {
writer.writeAttribute("title", option.getTitle(), "title");
} else if (curItem.getDescription() != null && !curItem.getDescription().isEmpty()) {
writer.writeAttribute("title", curItem.getDescription(), "title");
}
if (option.getAccesskey() != null && !option.getAccesskey().isEmpty()) {
writer.writeAttribute("accesskey", option.getAccesskey(), "accesskey");
}
}
writer.writeAttribute("value", valueString, "value");
if (isSelected) {
writer.writeAttribute("selected", true, "selected");
}
// if the component is disabled, "disabled" attribute would be rendered
// on "select" tag, so don't render "disabled" on every option.
if ((!optionInfo.isDisabled()) && curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
if (curItem.isEscape()) {
String label = curItem.getLabel();
if (label == null) {
label = valueString;
}
writer.writeText(label, component, "label");
} else {
writer.write(curItem.getLabel());
}
writer.endElement("option");
writer.writeText("\n", component, null);
return true;
}
}
/*
* Copyright 2015 John Yeary <jyeary@bluelotussoftware.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bluelotussoftware.component;
import javax.faces.model.SelectItem;
/**
* An extension of the {@link SelectItem} which allows setting of additional
* attributes.
*
* @author John Yeary <jyeary@bluelotussoftware.com>
* @version 1.0
*/
public class HtmlOption extends SelectItem {
private static final long serialVersionUID = -266606679814647297L;
/**
* Defines a unique identifier (ID) which must be unique in the whole
* document. Its purpose is to identify the element when linking (using a
* fragment identifier), scripting, or styling (with CSS).
*/
private String id;
/**
* Contains a text representing advisory information related to the element
* it belongs to. Such information can typically, but not necessarily, be
* presented to the user as a tooltip.
*/
private String title;
/**
* Provides a hint for generating a keyboard shortcut for the current
* element. This attribute consists of a space-separated list of characters.
* The browser should use the first one that exists on the computer keyboard
* layout.
*/
private String accesskey;
/**
* Default constructor.
*/
public HtmlOption() {
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value Value to be delivered to the model if this item is selected
* by the user
*/
public HtmlOption(String id, String title, Object value) {
super(value);
this.id = id;
this.title = title;
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value The value to be delivered to the model if this item is
* selected by the user.
* @param label The label to be rendered for this item in the response.
*/
public HtmlOption(String id, String title, Object value, String label) {
super(value, label);
this.id = id;
this.title = title;
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value The value to be delivered to the model if this item is
* selected by the user.
* @param label The label to be rendered for this item in the response.
* @param description Description of this item, for use in tools.
*/
public HtmlOption(String id, String title, Object value, String label, String description) {
super(value, label, description);
this.id = id;
this.title = title;
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value The value to be delivered to the model if this item is
* selected by the user.
* @param label The label to be rendered for this item in the response.
* @param description Description of this item, for use in tools.
* @param disabled Flag indicating that this option is disabled.
*/
public HtmlOption(String id, String title, Object value, String label, String description, boolean disabled) {
super(value, label, description, disabled);
this.id = id;
this.title = title;
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value The value to be delivered to the model if this item is
* selected by the user.
* @param label The label to be rendered for this item in the response.
* @param description Description of this item, for use in tools.
* @param disabled Flag indicating that this option is disabled.
* @param escape Flag indicating that the text of this option should be
* escaped when rendered.
*/
public HtmlOption(String id, String title, Object value, String label, String description, boolean disabled, boolean escape) {
super(value, label, description, disabled, escape);
this.id = id;
this.title = title;
}
/**
*
* @param id The ID to set for the {@literal <option>}.
* @param title The title attribute to set.
* @param value The value to be delivered to the model if this item is
* selected by the user.
* @param label The label to be rendered for this item in the response.
* @param description Description of this item, for use in tools.
* @param disabled Flag indicating that this option is disabled.
* @param escape Flag indicating that the text of this option should be
* escaped when rendered.
* @param noSelectionOption Flag indicating that the current option is a "no
* selection" option.
*/
public HtmlOption(String id, String title, Object value, String label, String description, boolean disabled, boolean escape, boolean noSelectionOption) {
super(value, label, description, disabled, escape, noSelectionOption);
this.id = id;
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAccesskey() {
return accesskey;
}
public void setAccesskey(String accesskey) {
this.accesskey = accesskey;
}
}
@jyeary
Copy link
Author

jyeary commented Jun 21, 2015

Here is an example of how to use the code.

        List<SelectItem> selections = new ArrayList<>();
        selections.add(new HtmlOption("option_1", "Soylent Product", "soylent", "Soylent", "A product"));
        selections.add(new HtmlOption("option_2", "The color green", "green", "Green", "The color green"));
        selections.add(new HtmlOption("option_3", "Real food", "food", "Food", "Real Food", true));
        HtmlOption op = new HtmlOption("option_4", null, "soylent green", "Soylent Green", "Soylent Green is people!");
        op.setAccesskey("Y");
        selections.add(op);
        selections.add(new HtmlOption(null, null, "Fu Man Chu", "Fu Man Chu", null, false, false, true));

@jyeary
Copy link
Author

jyeary commented Jun 21, 2015

This is the faces_config.xml.

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <render-kit>
        <renderer>
            <component-family>javax.faces.SelectOne</component-family>
            <renderer-type>javax.faces.Menu</renderer-type>
            <renderer-class>com.bluelotussoftware.renderer.CustomMenuRenderer</renderer-class>
        </renderer>
    </render-kit>
</faces-config>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment