001// Copyright 2006, 2007, 2008, 2011 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.corelib.components;
016
017import org.apache.tapestry5.ComponentResources;
018import org.apache.tapestry5.MarkupWriter;
019import org.apache.tapestry5.ValidationTracker;
020import org.apache.tapestry5.annotations.*;
021import org.apache.tapestry5.corelib.base.AbstractField;
022import org.apache.tapestry5.corelib.mixins.RenderDisabled;
023import org.apache.tapestry5.ioc.annotations.Inject;
024import org.apache.tapestry5.services.Request;
025
026/**
027 * A Checkbox component is simply a <input type="checkbox">.
028 *
029 * @tapestrydoc
030 */
031public class Checkbox extends AbstractField
032{
033    /**
034     * The value to be read or updated. If not bound, the Checkbox will attempt to edit a property of its container
035     * whose name matches the component's id.
036     */
037    @Parameter(required = true, autoconnect = true)
038    private boolean value;
039
040    @Inject
041    private Request request;
042
043    @SuppressWarnings("unused")
044    @Mixin
045    private RenderDisabled renderDisabled;
046
047    @Inject
048    private ComponentResources resources;
049
050    @Environmental
051    private ValidationTracker tracker;
052
053    @BeginRender
054    void begin(MarkupWriter writer)
055    {
056        String asSubmitted = tracker.getInput(this);
057
058        boolean checked = asSubmitted != null ? Boolean.parseBoolean(asSubmitted) : value;
059
060        writer.element("input", "type", "checkbox",
061
062                "name", getControlName(),
063
064                "id", getClientId(),
065
066                "checked", checked ? "checked" : null);
067
068        resources.renderInformalParameters(writer);
069
070        decorateInsideField();
071    }
072
073    @AfterRender
074    void after(MarkupWriter writer)
075    {
076        writer.end(); // input
077    }
078
079    @Override
080    protected void processSubmission(String controlName)
081    {
082        String postedValue = request.getParameter(controlName);
083
084        // record as "true" or "false"
085
086        tracker.recordInput(this, Boolean.toString(postedValue != null));
087
088        value = postedValue != null;
089    }
090}