package wicket.examples.forminput;

import wicket.markup.html.WebMarkupContainer;
import wicket.markup.html.form.FormComponent;
import wicket.model.IModel;

/**
 * Component used to connect instances of SingleRadioChoice components into a
 * group. Instances of SingleRadioChoice have to be in the component hierarchy
 * somewhere below the group component. The model object of the gorup is set to
 * the model object of the selected choice component or null if none selected.
 * This component does not render its tag, so it should be attached to ane extra
 * span.
 * 
 * ie
 * 
 * <code>
 * <span wicket:id="radiochoicegroup">
 *   ...
 *   <input type="radio" wicket:id="singleradiochoice1">choice 1</input>
 *   ...
 *   <input type="radio" wicket:id="singleradiochoice2">choice 2</input>
 *   ...
 * </span>
 * </code>
 * 
 * @author Igor Vaynberg (ivaynberg@users.sf.net)
 * 
 */
public class RadioChoiceGroup extends FormComponent
{
	/**
	 * @see WebMarkupContainer#WebMarkupContainer(String)
	 */
	public RadioChoiceGroup(String id)
	{
		this(id, null);
	}

	/**
	 * @see WebMarkupContainer#WebMarkupContainer(String, IModel)
	 */
	public RadioChoiceGroup(String id, IModel model)
	{
		super(id, model);
		setRenderBodyOnly(true);
	}

	/**
	 * this is where we update the model object. we figure out the activated
	 * selected single radio choice component and set the value of the group's
	 * model object to that of the selected component.
	 */
	public void updateModel()
	{
		// the input value contains the full path of the single radio choice
		// component
		// unless no choice was selected in which case the input contains null
		String path = getInput();

		if (path != null)
		{
			/*
			 * single radio choice component path sans group path = relative
			 * path from group to choice since we know the choice is child of
			 * group
			 */
			path = path.substring(getPath().length() + 1);

			// retrieve the selected single radio choice component
			SingleRadioChoice choice = (SingleRadioChoice)get(path);

			// assign the value of the group's model
			setModelObject(choice.getModelObject());
		}
	}

}
