You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@wicket.apache.org by da...@apache.org on 2016/11/23 22:44:44 UTC

[11/22] wicket git commit: Moved wicket-7.x docs to asciidoctor

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_2.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_2.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_2.adoc
new file mode 100644
index 0000000..f1c48a6
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_2.adoc
@@ -0,0 +1,355 @@
+
+
+
+Wicket distribution comes with a number of built-in AJAX components ready to be used. Some of them are the ajaxified version of common components like links and buttons, while others are AJAX-specific components. 
+
+AJAX components are not different from any other component seen so far and they don't require any additional configuration to be used. As we will shortly see, switching from a classic link or button to the ajaxified version is just a matter of prepending \u201cAjax\u201d to the component class name.
+
+This paragraph provides an overview of what we can find in Wicket to start writing AJAX-enhanced web applications.
+
+=== Links and buttons
+
+In the previous paragraph we have already introduced component AjaxLink. Wicket provides also the ajaxified versions of submitting components SubmitLink and Button which are simply called AjaxSubmitLink and AjaxButton. These components come with a version of methods onSubmit, onError and onAfterSubmit that takes in input also an instance of _AjaxRequestTarget_. 
+
+Both components are in package _org.apache.wicket.ajax.markup.html.form_.
+
+=== Fallback components
+
+Building an entire site using AJAX can be risky as some clients may not support this technology. In order to provide an usable version of our site also to these clients, we can use components _AjaxFallbackLink_ and _AjaxFallbackButton_ which are able to automatically degrade to a standard link or to a standard button if client doesn't support AJAX.
+
+=== AJAX Checkbox
+
+Class _org.apache.wicket.ajax.markup.html.form.AjaxCheckBox_ is a checkbox component that updates its model via AJAX when user changes its value. Its AJAX callback method is _onUpdate(AjaxRequestTarget target)_. The component extends standard checkbox component _CheckBox_ adding an _AjaxFormComponentUpdatingBehavior_ to itself (we will see this behavior later in <<ajax.adoc#_built-in_ajax_behaviors,paragraph 19.3.3>>).
+
+=== AJAX editable labels
+
+An editable label is a special label that can be edited by the user when she/he clicks on it. Wicket ships three different implementations for this component (all inside package _org.apache.wicket.extensions.ajax.markup.html_):
+
+* *AjaxEditableLabel*: it's a basic version of editable label. User can edit the content of the label with a text field. This is also the base class for the other two editable labels.
+* *AjaxEditableMultiLineLabel*: this label supports multi-line values and uses a text area as editor component. 
+* *AjaxEditableChoiceLabel*: this label uses a drop-down menu to edit its value.
+
+Base component AjaxEditableLabel exposes the following set of AJAX-aware methods that can be overriden:
+
+* *onEdit(AjaxRequestTarget target)*: called when user clicks on component. The default implementation shows the component used to edit the value of the label.  
+* *onSubmit(AjaxRequestTarget target)*: called when the value has been successfully updated with the new input.
+* *onError(AjaxRequestTarget target)*: called when the new inserted input has failed validation.
+* *onCancel(AjaxRequestTarget target)*: called when user has exited from editing mode pressing escape key. The default implementation brings back the label to its initial state hiding the editor component.  
+
+Wicket module wicket-examples contains page class _EditableLabelPage.java_ which shows all these three components together. You can see this page in action at {externalink:wicket.examples.url_ajax/editable-label}:
+
+image::../img/edit-label-example-screenshot.png[]
+
+=== Autocomplete text field
+
+On Internet we can find many examples of text fields that display a list of suggestions (or options) while the user types a text inside them. This feature is known as autocomplete functionality. 
+
+Wicket offers an out-of-the-box implementation of an autocomplete text field with component _org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField_. 
+
+When using AutoCompleteTextField we are required to implement its abstract method getChoices(String input) where the input parameter is the current input of the component. This method returns an iterator over the suggestions that will be displayed as a drop-down menu:
+
+image::../img/autocomplete-example-screenshot.png[]
+
+Suggestions are rendered using a render which implements interface _IAutoCompleteRenderer_. The default implementation simply calls toString() on each suggestion object. If we need to work with a custom render we can specify it via component constructor.
+
+AutoCompleteTextField supports a wide range of settings that are passed to its constructor with class _AutoCompleteSettings_.
+
+One of the most interesting parameter we can specify for _AutoCompleteTextField_ is the throttle delay which is the amount of time (in milliseconds) that must elapse between a change of input value and the transmission of a new Ajax request to display suggestions. This parameter can be set with method _setThrottleDelay(int)_:
+
+[source,java]
+----
+AutoCompleteSettings settings = new AutoCompleteSettings();
+//set throttle to 400 ms: component will wait 400ms before displaying the options		
+settings.setThrottleDelay(400);
+//...		
+AutoCompleteTextField field = new AutoCompleteTextField<T>("field", model) {
+
+	@Override
+	protected Iterator getChoices(String arg0) {
+		//return an iterator over the options 
+	}
+};
+----
+
+Wicket module wicket-examples contains page class _AutoCompletePagePage.java_ which shows an example of autocomplete text field. The running example is available at {externalink:wicket.examples.url_ajax/autocomplete} .
+
+=== Modal window
+
+Class _org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow_ is an implementation of a  http://en.wikipedia.org/wiki/Modal_window[modal window] based on AJAX:
+
+image::../img/modal-window-example-screenshot.png[]
+
+The content of a modal window can be either another component or a page. In the first case the id of the  component used as content must be retrieved with method getContentId(). 
+
+If instead we want to use a page as window content, we must implement the inner interface _ModalWindow.PageCreator_ and pass it to method _setPageCreator_. The page used as content will be embedded in a <iframe> tag.
+
+To display a modal window we must call its method _show(AjaxRequestTarget target)_. This is  usually done inside the AJAX callback method of another component (like an _AjaxLink_). The following markup and code are taken from project _BasicModalWindowExample_ and illustrate a basic usage of a modal window:
+
+*HTML:*
+[source,html]
+----
+<body>
+	<h2>Modal Windod example</h2>
+	<a wicket:id="openWindow">Open the window!</a>
+	<div wicket:id="modalWindow"></div>
+</body>
+----
+
+*Java Code:*
+[source,java]
+----
+public HomePage(final PageParameters parameters) {
+   	super(parameters);
+   	final ModalWindow modalWindow = new ModalWindow("modalWindow");
+   	Label label = new Label(modalWindow.getContentId(), "I'm a modal window!");
+    	
+   	modalWindow.setContent(label);
+   	modalWindow.setTitle("Modal window");
+    	
+   	add(modalWindow);
+   	add(new AjaxLink("openWindow") {
+	  @Override
+	  public void onClick(AjaxRequestTarget target) {
+		modalWindow.show(target);				
+	  }    		
+	});
+}
+----
+
+Just like any other component also _ModalWindow_ must be added to a markup tag, like we did in our example using a <div> tag. Wicket will automatically hide this tag in the final markup appending the style value display:none. 
+The component provides different setter methods to customize the appearance of the window:
+
+* *setTitle(String)*: specifies the title of the window
+* *setResizable(boolean)*: by default the window is resizeable. If we need to make its size fixed we can use this method to turn off this feature.
+* *setInitialWidth(int) and setInitialHeight(int)*: set the initial dimensions of the window.
+* *setMinimalWidth(int) and setMinimalHeight(int)*: specify the minimal dimensions of the window.
+* *setCookieName(String)*: this method can be used to specify the name of the cookie used on  client side to store size and position of the window when it is closed. The component will use this cookie to restore these two parameters the next time the window will be opened. If no cookie name is provided, the component will not remember its last position and size.
+* *setCssClassName(String)*: specifies the CSS class used for the window. 
+* *setAutoSize(boolean)*: when this flag is set to true the window will automatically adjust its size to fit content width and height. By default it is false.
+
+The modal window can be closed from code using its method _close(AjaxRequestTarget target)_. The currently opened window can be closed also with the following JavaScript instruction:
+
+[source,java]
+----
+Wicket.Window.get().close();
+----
+
+_ModalWindow_ gives the opportunity to perform custom actions when window is closing. Inner interface _ModalWindow.WindowClosedCallback_ can be implemented and passed to window's method _setWindowClosedCallback_ to specify the callback that must be executed after window has been closed:
+
+[source,java]
+----
+modalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
+
+	@Override
+	public void onClose(AjaxRequestTarget target) {
+	  //custom code...
+	}			
+});
+----
+
+=== Tree repeaters
+
+Class _org.apache.wicket.extensions.markup.html.repeater.tree.AbstractTree_ is the base class of another family of repeaters called tree repeaters and designed to display a data hierarchy as a tree, resembling the behavior and the look & feel of desktop tree components. A classic example of tree component on desktop is the tree used by nearly all file managers to navigate file system:
+
+image::../img/file-system-trees.png[]
+
+Because of their highly interactive nature, tree repeaters are implemented as AJAX components,  meaning that they are updated via AJAX when we expand or collapse their nodes. 
+
+The basic implementation of a tree repeater shipped with Wicket is component _NestedTree_. In order to use a tree repeater we must provide an implementation of interface _ITreeProvider_ which is in charge of returning the nodes that compose the tree.  
+
+Wicket comes with a built-in implementation of ITreeProvider called TreeModelProvider that works with the same tree model and nodes used by Swing component _javax.swing.JTree_. These Swing entities should be familiar to you if you have previously worked with the old tree repeaters (components _Tree_ and _TreeTable_) that have been deprecated with Wicket 6 and that are strongly dependent on Swing-based model and nodes. _TreeModelProvider_ can be used to migrate your code to the new tree repeaters. 
+
+In the next example (project _CheckBoxAjaxTree_) we will build a tree that displays some of the main cities of three European countries: Italy, Germany and France. The cities are sub-nodes of a main node representing the relative county. The nodes of the final tree will be also selectable with a checkbox control. The whole tree will have the classic look & feel of Windows XP. This is how our tree will look like:
+
+image::../img/AJAX-tree-repeater.png[]
+
+We will start to explore the code of this example from the home page. The first portion of code we will see is where we build the nodes and the _TreeModelProvider_ for the three. As tree node we will use Swing class _javax.swing.tree.DefaultMutableTreeNode_:
+
+[source,java]
+----
+public class HomePage extends WebPage {
+    public HomePage(final PageParameters parameters) {
+     super(parameters);
+     DefaultMutableTreeNode root = new DefaultMutableTreeNode("Cities of Europe");
+      
+     addNodes(addNodes(root, "Italy"), "Rome", "Venice", "Milan", "Florence");
+     addNodes(addNodes(root, "Germany"),"Stuttgart","Munich", "Berlin","Dusseldorf", "Dresden");
+     addNodes(addNodes(root, "France"), "Paris","Toulouse", "Strasbourg","Bordeaux", "Lyon");
+      
+     DefaultTreeModel treeModel = new DefaultTreeModel(root);
+     TreeModelProvider<DefaultMutableTreeNode> modelProvider = new 
+                            TreeModelProvider<DefaultMutableTreeNode>( treeModel ){
+       @Override
+       public IModel<DefaultMutableTreeNode> model(DefaultMutableTreeNode object){
+          return Model.of(object);
+       }
+     };
+     //To be continued...
+----
+
+Nodes have been built using simple strings as data objects and invoking custom utility method addNodes which converts string parameters into children nodes for a given parent node. Once we have our tree of _DefaultMutableTreeNodes_ we can build the Swing tree model (_DefaultTreeModel_) that will be the backing object for a _TreeModelProvider_. This provider wraps each node in a model invoking its abstract method model. In our example we have used a simple _Model_ as wrapper model.
+
+Scrolling down the code we can see how the tree component is instantiated and configured before being added to the home page:
+
+[source,java]
+----
+//Continued from previous snippet...
+ NestedTree<DefaultMutableTreeNode> tree = new NestedTree<DefaultMutableTreeNode>("tree", 
+                                                      modelProvider)
+  {
+
+   @Override
+   protected Component newContentComponent(String id, IModel<DefaultMutableTreeNode>model)
+   {
+     return new CheckedFolder<DefaultMutableTreeNode>(id, this, model);
+   }
+  };
+  //select Windows theme
+  tree.add(new WindowsTheme());
+  
+  add(tree);
+  }
+  //implementation of addNodes
+  //...
+}
+----
+
+To use tree repeaters we must implement their abstract method _newContentComponent_ which is called internally by base class _AbstractTree_ when a new node must be built. As content component we have used built-in class _CheckedFolder_ which combines a _Folder_ component with a _CheckBox_ form control. 
+
+The final step before adding the tree to its page is to apply a theme to it. Wicket comes with two behaviors, WindowsTheme and HumanTheme, which correspond to the classic Windows XP theme and to the Human theme from Ubuntu.
+
+Our checkable tree is finished but our work is not over yet because the component doesn't offer many functionalities as it is. Unfortunately neither NestedTree nor CheckedFolder provide a means for collecting checked nodes and returning them to client code. It's up to us to implement a way to keep track of checked nodes.
+
+Another nice feature we would like to implement for our tree is the following user-friendly behavior that should occur when a user checks/unchecks a node:
+
+* When a node is checked also all its children nodes (if any) must be checked. We must also ensure that all the ancestors of the checked node (root included) are checked, otherwise we would get an inconsistent selection.
+* When a node is unchecked also all its children nodes (if any) must be unchecked and we must also ensure that ancestors get unchecked if they have no more checked children.
+
+The first goal (keeping track of checked node) can be accomplished building a custom version of _CheckedFolder_ that uses a shared Java Set to store checked node and to verify if its node has been  checked. This kind of solution requires a custom model for checkbox component in order to reflect its checked status when its container node is rendered. This model must implement typed interface _IModel<Boolean>_ and must be returned by _CheckedFolder_'s method _newCheckBoxModel_.
+
+For the second goal (auto select/unselect children and ancestor nodes) we can use _CheckedFolder_'s callback method onUpdate(AjaxRequestTarget) that is invoked after a checkbox is clicked and its value has been updated. Overriding this method we can handle user click adding/removing nodes to/from the Java Set.
+
+Following this implementation plan we can start coding our custom _CheckedFolder_ (named _AutocheckedFolder_): 
+
+[source,java]
+----
+public class AutocheckedFolder<T> extends CheckedFolder<T> {
+
+   private ITreeProvider<T> treeProvider;
+   private IModel<Set<T>> checkedNodes;
+   private IModel<Boolean> checkboxModel;
+   
+   public AutocheckedFolder(String id, AbstractTree<T> tree, 
+                        IModel<T> model, IModel<Set<T>> checkedNodes) {
+      super(id, tree, model);   
+      this.treeProvider = tree.getProvider();
+      this.checkedNodes = checkedNodes;            
+   }
+   
+   @Override
+   protected IModel<Boolean> newCheckBoxModel(IModel<T> model) {
+      checkboxModel =  new CheckModel();
+      return checkboxModel;
+   }
+   
+   @Override
+   protected void onUpdate(AjaxRequestTarget target) {
+      super.onUpdate(target);
+      T node = getModelObject();
+      boolean nodeChecked = checkboxModel.getObject();
+      
+      addRemoveSubNodes(node, nodeChecked);            
+      addRemoveAncestorNodes(node, nodeChecked);            
+   }
+
+  class CheckModel extends AbstractCheckBoxModel{
+      @Override
+      public boolean isSelected() {
+         return checkedNodes.getObject().contains(getModelObject());
+      }
+
+      @Override
+      public void select() {
+         checkedNodes.getObject().add(getModelObject());
+      }
+
+      @Override
+      public void unselect() {
+         checkedNodes.getObject().remove(getModelObject());
+      }				
+  }
+}
+----
+
+The constructor of this new component takes in input a further parameter which is the set containing checked nodes. 
+
+Class CheckModel is the custom model we have implemented for checkbox control. As base class for this model we have used _AbstractCheckBoxModel_ which is provided to implement custom models for checkbox controls. 
+
+Methods _addRemoveSubNodes_ and _addRemoveAncestorNodes_ are called to automatically add/remove children and ancestor nodes to/from the current Set. Their implementation is mainly focused on the navigation of tree nodes and it heavily depends on the internal implementation of the tree, so we won't dwell on their code.
+
+Now we are just one step away from completing our tree as we still have to find a way to update the checked status of both children and ancestors nodes on client side. Although we could easily accomplish this task by simply refreshing the whole tree via AJAX, we would like to find a better and more performant solution for this task. 
+
+When we modify the checked status of a node we don't expand/collapse any node of the three so we can simply update the desired checkboxes rather than updating the entire tree component. This alternative approach could lead to a more responsive interface and to a strong reduction of bandwidth consumption. 
+
+With the help of JQuery we can code a couple of JavaScript functions that can be used to check/ uncheck all the children and ancestors of a given node. Then, we can append these functions to the current _AjaxRequest_ at the end of method onUpdate:
+
+[source,java]
+----
+   @Override
+   protected void onUpdate(AjaxRequestTarget target) {
+      super.onUpdate(target);
+      T node = getModelObject();
+      boolean nodeChecked = checkboxModel.getObject();
+      
+      addRemoveSubNodes(node, nodeChecked);            
+      addRemoveAncestorNodes(node, nodeChecked);    
+      updateNodeOnClientSide(target, nodeChecked);		
+   }
+
+   protected void updateNodeOnClientSide(AjaxRequestTarget target,
+			boolean nodeChecked) {
+      target.appendJavaScript(";CheckAncestorsAndChildren.checkChildren('" + getMarkupId() + 
+                              "'," + nodeChecked + ");");
+		
+      target.appendJavaScript(";CheckAncestorsAndChildren.checkAncestors('" + getMarkupId() + 
+                              "'," + nodeChecked + ");");
+   }
+----
+
+The JavaScript code can be found inside file autocheckedFolder.js which is added to the header section as package resource:
+
+[source,java]
+----
+@Override
+public void renderHead(IHeaderResponse response) {
+	PackageResourceReference scriptFile = new PackageResourceReference(this.getClass(), 
+                                                      "autocheckedFolder.js");
+	response.render(JavaScriptHeaderItem.forReference(scriptFile));
+}
+----
+
+=== Working with hidden components
+
+When a component is not visible its markup and the related id attribute are not rendered in the final page, hence it can not be updated via AJAX. To overcome this problem we must use Component's method _setOutputMarkupPlaceholderTag(true)_ which has the effect of rendering a hidden <span> tag containing the markup id of the hidden component: 
+
+[source,java]
+----
+final Label label = new Label("labelComponent", "Initial value.");
+//make label invisible
+label.setVisible(false);
+//ensure that label will leave a placeholder for its markup id
+label.setOutputMarkupPlaceholderTag(true);
+add(label);
+//...
+new AjaxLink("ajaxLink"){
+	@Override
+	public void onClick(AjaxRequestTarget target) {
+	    //turn label to visible
+	    label.setVisible(true);
+	    target.add(label);
+	}  	
+};
+----
+
+Please note that in the code above we didn't invoked method _setOutputMarkupId(true)_ as _setOutputMarkupPlaceholderTag_ already does it internally.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_3.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_3.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_3.adoc
new file mode 100644
index 0000000..a22ff48
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_3.adoc
@@ -0,0 +1,124 @@
+
+
+
+In addition to specific components, Wicket offers also a set of built in AJAX behaviors that can be used to easily add AJAX functionalities to existing components. As we will see in this paragraph AJAX behaviors can be used also to ajaxify components that weren't initially designed to work with this technology. All the following behaviors are inside package _org.apache.wicket.ajax_. 
+
+=== AjaxEventBehavior
+
+AjaxEventBehavior allows to handle a JavaScript event (like click, change, etc...) on server side via AJAX. Its constructor takes in input the name of the event that must be handled. Every time this event is fired for a given component on client side, the callback method _onEvent(AjaxRequestTarget target)_ is executed. onEvent is abstract, hence we must implement it to tell _AjaxEventBehavior_ what to do when the specified event occurs.
+
+In project _AjaxEventBehaviorExample_ we used this behavior to build a \u201cclickable\u201d Label component that counts the number of clicks. Here is the code from the home page of the project:
+
+*HTML:*
+[source,html]
+----
+<body>
+  <div wicket:id="clickCounterLabel"></div>
+  User has clicked <span wicket:id="clickCounter"></span> time/s on the label above.
+</body>
+----
+
+*Java Code:*
+[source,java]
+----
+public class HomePage extends WebPage {
+   public HomePage(final PageParameters parameters) {
+      super(parameters);
+   
+      final ClickCounterLabel clickCounterLabel = 
+         new ClickCounterLabel("clickCounterLabel", "Click on me!");
+      final Label clickCounter =
+         new Label("clickCounter", new PropertyModel(clickCounterLabel, "clickCounter"));
+      
+      
+      clickCounterLabel.setOutputMarkupId(true);
+      clickCounterLabel.add(new AjaxEventBehavior("click"){
+
+         @Override
+         protected void onEvent(AjaxRequestTarget target) {
+            clickCounterLabel.clickCounter++;
+            target.add(clickCounter);
+         }         
+      });
+      
+      add(clickCounterLabel);
+      add(clickCounter.setOutputMarkupId(true));      
+    }
+}
+
+class ClickCounterLabel extends Label{
+   public int clickCounter;   
+
+   public ClickCounterLabel(String id) {
+      super(id);
+   }
+
+   public ClickCounterLabel(String id, IModel<?> model) {
+      super(id, model);
+   }
+
+   public ClickCounterLabel(String id, String label) {
+      super(id, label);      
+   }
+}
+----
+
+In the code above we have declared a custom label class named _ClickCounterLabel_ that exposes a public integer field called clickCounter. Then, in the home page we have attached a _AjaxEventBehavior_ to our custom label to increment clickCounter every time it receives a click event.
+
+The number of clicks is displayed with another standard label named _clickCounter_.
+
+=== AjaxFormSubmitBehavior
+
+This behavior allows to send a form via AJAX when the component it is attached to receives the specified event. The component doesn't need to be inside the form if we use the constructor version that, in addition to the name of the event, takes in input also the target form:
+
+[source,java]
+----
+Form form = new Form("form");		
+Button submitButton = new Button("submitButton");
+//submit form when button is clicked		
+submitButton.add(new AjaxFormSubmitBehavior(form, "click"){});
+add(form);
+add(submitButton);
+----
+
+NOTE: _AjaxFormSubmitBehavior_ does not prevent JavaScript default event handling. For _<input type= @[submit] you'll have to call _AjaxRequestAttributes1.setPreventDefault(true)_ to prevent the form from being submitted twice.
+
+=== AjaxFormComponentUpdatingBehavior
+
+This behavior updates the model of the form component it is attached to when a given event occurs. The standard form submitting process is skipped and the behavior validates only its form component. 
+
+The behavior doesn't work with radio buttons and checkboxes. For these kinds of components we must use _AjaxFormChoiceComponentUpdatingBehavior_:
+
+[source,java]
+----
+Form form = new Form("form");		
+TextField textField = new TextField("textField", Model.of(""));
+//update the model of the text field each time event "change" occurs
+textField.add(new AjaxFormComponentUpdatingBehavior("change"){
+	@Override
+	protected void onUpdate(AjaxRequestTarget target) {
+		//...				
+	}
+});
+add(form.add(textField));
+----
+
+=== AbstractAjaxTimerBehavior
+
+_AbstractAjaxTimerBehavior_ executes callback method _onTimer(AjaxRequestTarget target)_ at a specified interval. The behavior can be stopped and restarted at a later time with methods _stop(AjaxRequestTarget target)_ and _restart(AjaxRequestTarget target)_:
+
+[source,java]
+----
+Label dynamicLabel = new Label("dynamicLabel");
+//trigger an AJAX request every three seconds		
+dynamicLabel.add(new AbstractAjaxTimerBehavior(Duration.seconds(3)) {			
+	@Override
+	protected void onTimer(AjaxRequestTarget target) {
+		//...				
+	}
+});
+add(dynamicLabel);
+----
+
+NOTE: As side effect AJAX components and behaviors make their hosting page stateful. As a consequence they are unfit for those pages that must stay stateless. Project WicketStuff provides a module with a stateless version of the most common AJAX components and behaviors. You can find more informations on this module in Appendix B. 
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_4.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_4.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_4.adoc
new file mode 100644
index 0000000..23396c8
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_4.adoc
@@ -0,0 +1,33 @@
+
+
+
+One of the things we must take care of when we use AJAX is to notify user when an AJAX request is already in progress. This is usually done displaying an animated picture as activity indicator while the AJAX request is running. 
+
+Wicket comes with a variant of components _AjaxButton_, _AjaxLink_ and _AjaxFallbackLink_ that display a default activity indicator during AJAX request processing. These components are respectively _IndicatingAjaxButton_, _IndicatingAjaxLink_ and _IndicatingAjaxFallbackLink_.
+
+The default activity indicator used in Wicket can be easily integrated in our components using behavior AjaxIndicatorAppender (available in package _org.apache.wicket.extensions.ajax.markup.html_) and implementing the interface _IAjaxIndicatorAware_ (in package _org.apache.wicket.ajax_). 
+
+_IAjaxIndicatorAware_ declares method _getAjaxIndicatorMarkupId()_ which returns the id of the markup element used to display the activity indicator. This id can be obtained from the AjaxIndicatorAppender behavior that has been added to the current component. The following code snippet summarizes the steps needed to integrate the default activity indicator with an ajaxified component:
+
+[source,java]
+----
+//1-Implement interface IAjaxIndicatorAware
+public class MyComponent extends Component implements IAjaxIndicatorAware {
+	//2-Instantiate an AjaxIndicatorAppender
+	private AjaxIndicatorAppender indicatorAppender =
+			new AjaxIndicatorAppender();
+	
+	public MyComponent(String id, IModel<?> model) {
+		super(id, model);
+		//3-Add the AjaxIndicatorAppender to the component
+		add(indicatorAppender);
+	}
+	//4-Return the markup id obtained from AjaxIndicatorAppender
+	public String getAjaxIndicatorMarkupId() {		
+		return indicatorAppender.getMarkupId();
+	}
+//...
+}
+----
+
+If we need to change the default picture used as activity indicator, we can override method _getIndicatorUrl()_ of _AjaxIndicatorAppender_ and return the URL to the desired picture.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_5.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_5.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_5.adoc
new file mode 100644
index 0000000..901c475
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_5.adoc
@@ -0,0 +1,57 @@
+
+
+
+Starting from version 6.0 Wicket has introduced two entities which allow us to control how an AJAX request is generated on client side and to specify the custom JavaScript code we want to execute during request handling. These entities are class _AjaxRequestAttributes_ and interface _IAjaxCallListener_, both placed in package _org.apache.wicket.ajax.attributes_.
+
+AjaxRequestAttributes exposes the attributes used to generate the JavaScript call invoked on client side to start an AJAX request. Each attribute will be passed as a  http://en.wikipedia.org/wiki/JSON[JSON] parameter to the JavaScript function _Wicket.Ajax.ajax_ which is responsible for sending the concrete AJAX request. Every JSON parameter is identified by a short name. Here is a partial list of the available parameters:
+
+|===
+|*Short name* | *Description* | *Default value*
+|u | The callback URL used to serve the AJAX request that will be sent. |
+|c | The id of the component that wants to start the AJAX call. |
+|e | A list of event (click, change, etc...) that can trigger the AJAX call. | domready
+|m | The request method that must be used (GET or POST). | GET
+|f | The id of the form that must be submitted with the AJAX call. |
+|mp | If the AJAX call involves the submission of a form, this flag indicates whether the data must be encoded using the encoding mode \u201cmultipart/form-data\u201d. | false
+|sc | The input name of the submitting component of the form |
+|async | A boolean parameter that indicates if the AJAX call is asynchronous (true) or not. | true
+|wr | Specifies the type of data returned by the AJAX call (XML, HTML, JSON, etc...). | XML
+|ih, bh, pre, bsh, ah, sh, fh, coh, dh | This is a list of the listeners that are executed on client side (they are JavaScript scripts) during the lifecycle of an AJAX request. Each short name is the abbreviation of one of the methods defined in the interface IAjaxCallListener (see below). | An empty list
+|===
+
+NOTE: A full list of the available request parameters as well as more details on the related JavaScript code can be found at  https://cwiki.apache.org/confluence/display/WICKET/Wicket+Ajax[https://cwiki.apache.org/confluence/display/WICKET/Wicket+Ajax] .
+
+Parameters 'u' (callback URL) and 'c' (the id of the component) are generated by the AJAX behavior that will serve the AJAX call and they are not accessible through _AjaxRequestAttributes_.
+
+Here is the final AJAX function generate for the behavior used in example project _AjaxEventBehavior_ Example:
+
+[source,java]
+----
+Wicket.Ajax.ajax({"u":"./?0-1.IBehaviorListener.0-clickCounterLabel", "e":"click",               
+                  "c":"clickCounterLabel1"});
+----
+
+Even if most of the times we will let Wicket generate request attributes for us, both AJAX components and behaviors give us the chance to modify them overriding their method _updateAjaxAttributes (AjaxRequestAttributes attributes)_. 
+
+One of the attribute we may need to modify is the list of _IAjaxCallListeners_ returned by method _getAjaxCallListeners()_. 
+
+_IAjaxCallListener_ defines a set of methods which return the JavaScript code (as a _CharSequence_) that must be executed on client side when the AJAX request handling reaches a given stage:
+
+* *getInitHandler(Component)*: returns the JavaScript code that will be executed on initialization of the Ajax call, immediately after the causing event. The code is executed in a scope where it can use variable attrs, which is an array containing the JSON parameters passed to Wicket.Ajax.ajax.
+* *getBeforeHandler(Component)*: returns the JavaScript code that will be executed before any other handlers returned by IAjaxCallListener. The code is executed in a scope where it can use variable attrs, which is an array containing the JSON parameters passed to Wicket.Ajax.ajax. 
+* *getPrecondition(Component)*: returns the JavaScript code that will be used as precondition for the AJAX call. If the script returns false then neither the Ajax call nor the other handlers will be executed. The code is executed in a scope where it can use variable attrs, which is the same variable seen for getBeforeHandler. 
+* *getBeforeSendHandler(Component)*: returns the JavaScript code that will be executed just before the AJAX call is performed. The code is executed in a scope where it can use variables attrs, jqXHR and settings:
+** attrs is the same variable seen for getBeforeHandler.
+** jqXHR is the the jQuery XMLHttpRequest object used to make the AJAX call.
+** settings contains the settings used for calling jQuery.ajax().
+* *getAfterHandler(Component)*: returns the JavaScript code that will be executed after the AJAX call. The code is executed in a scope where it can use variable attrs, which is the same variable seen before for getBeforeHandler. 
+* *getSuccessHandler(Component)*: returns the JavaScript code that will be executed if the AJAX call has successfully returned. The code is executed in a scope where it can use variables attrs, jqXHR, data and textStatus:
+** attrs and jqXHR are same variables seen for getBeforeSendHandler:
+** data is the data returned by the AJAX call. Its type depends on parameter wr (Wicket AJAX response).
+** textStatus it's the status returned as text.
+* *getFailureHandler(Component)*: returns the JavaScript code that will be executed if the AJAX call has returned with a failure. The code is executed in a scope where it can use variable attrs, which is the same variable seen for getBeforeHandler. 
+* *getCompleteHandler(Component)*: returns the JavaScript that will be invoked after success or failure handler has been executed. The code is executed in a scope where it can use variables attrs, jqXHR and textStatus which are the same variables seen for getSuccessHandler. 
+* *getDoneHandler(Component)*: returns the JavaScript code that will be executed after the Ajax call is done, regardless whether it was sent or not. The code is executed in a scope where it can use variable attrs, which is an array containing the JSON parameters passed to Wicket.Ajax.ajax.
+
+In the next paragraph we will see an example of custom _IAjaxCallListener_ designed to disable a component during AJAX request processing.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc
new file mode 100644
index 0000000..fd0f63c
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_6.adoc
@@ -0,0 +1,184 @@
+
+
+
+Displaying an activity indicator is a nice way to notify user that an AJAX request is already running, but sometimes is not enough. In some situations we may need to completely disable a component during AJAX request processing, for example when we want to avoid that impatient users submit a form multiple times. In this paragraph we will see how to accomplish this goal building a custom and reusable _IAjaxCallListener_. The code used in this example is from project _CustomAjaxListenerExample_.
+
+=== What we want for our listener
+
+The listener should execute some JavaScript code to disable a given component when the component it is attached to is about to make an AJAX call. Then, when the AJAX request has been completed, the listener should bring back the disabled component to an active state.
+
+When a component is disabled it must be clear to user that an AJAX request is running and that he/she must wait for it to complete. To achieve this result we want to disable a given component covering it with a semi-transparent overlay area with an activity indicator in the middle. 
+
+The final result will look like this:
+
+image::../img/custom-ajax-call-listener.png[]
+
+=== How to implement the listener
+
+The listener will implement methods _getBeforeHandler_ and _getAfterHandler_: the first will return the code needed to place an overlay <div> on the desired component while the second must remove this overlay when the AJAX call has completed.
+
+To move and resize the overlay area we will use another module from  http://jqueryui.com/position/[JQueryUI library] that allows us to position DOM elements on our page relative to another element.
+
+So our listener will depend on four static resources: the JQuery library, the position module of JQuery UI, the custom code used to move the overlay <div> and the picture used as activity indicator. Except for the activity indicator, all these resources must be added to page header section in order to be used. 
+
+Ajax call listeners can contribute to header section by simply implementing interface _IComponentAwareHeaderContributor_. Wicket provides adapter class _AjaxCallListener_ that implements both _IAjaxCallListener_ and _IComponentAwareHeaderContributor_. We will use this class as base class for our listener.
+
+=== JavaScript code
+
+Now that we know what to do on the Java side, let's have a look at the custom JavaScript code that must be returned by our listener (file moveHiderAndIndicator.js):
+
+[source,java]
+----
+DisableComponentListener = {
+   disableElement: function(elementId, activeIconUrl){
+      var hiderId = elementId + "-disable-layer";
+      var indicatorId = elementId + "-indicator-picture";
+      
+      elementId = "#" + elementId;
+      //create the overlay <div>
+      $(elementId).after('<div id="' + hiderId 
+         + '" style="position:absolute;">'
+         + '<img id="' + indicatorId +  '" src="' + activeIconUrl + '"/>'
+         + '</div>');
+      
+      hiderId = "#" + hiderId;
+      //set the style properties of the overlay <div>
+      $(hiderId).css('opacity', '0.8');               
+      $(hiderId).css('text-align', 'center');
+      $(hiderId).css('background-color', 'WhiteSmoke');
+      $(hiderId).css('border', '1px solid DarkGray');
+      //set the dimention of the overlay <div>
+      $(hiderId).width($(elementId).outerWidth());
+      $(hiderId).height($(elementId).outerHeight());       	 
+      //positioning the overlay <div> on the component that must be disabled.     
+      $(hiderId).position({of: $(elementId),at: 'top left', my: 'top left'});
+       
+      //positioning the activity indicator in the middle of the overlay <div>
+      $("#" + indicatorId).position({of: $(hiderId), at: 'center center',
+                                     my: 'center center'});
+   },
+   //function hideComponent
+----
+
+Function DisableComponentListener.disableElement places the overlay <div> an the activity indicator on the desired component. The parameters in input are the markup id of the component we want to disable and the URL of the activity indicator picture. These two parameters must be provided by our custom listener.
+
+The rest of custom JavaScript contains function DisableComponentListener.hideComponent which is just a wrapper around the JQuery function remove():
+
+[source,java]
+----
+hideComponent: function(elementId){
+	var hiderId = elementId + "-disable-layer";
+	$('#' + hiderId).remove();
+	}
+};
+----
+
+=== Java class code
+
+The code of our custom listener is the following:
+
+[source,java]
+----
+public class DisableComponentListener extends AjaxCallListener {
+   private static PackageResourceReference customScriptReference = new   
+   PackageResourceReference(DisableComponentListener.class, "moveHiderAndIndicator.js");
+   
+   private static PackageResourceReference jqueryUiPositionRef = new    
+   PackageResourceReference(DisableComponentListener.class, "jquery-ui-position.min.js");
+   
+   private static PackageResourceReference indicatorReference = 
+         new PackageResourceReference(DisableComponentListener.class, "ajax-loader.gif");
+   
+   private Component targetComponent;
+   
+   public DisableComponentListener(Component targetComponent){
+      this.targetComponent = targetComponent;
+   }
+   
+   @Override
+   public CharSequence getBeforeHandler(Component component) {   
+      CharSequence indicatorUrl = getIndicatorUrl(component);
+      return ";DisableComponentListener.disableElement('" + targetComponent.getMarkupId() 
+              + "'," + "'" + indicatorUrl + "');";
+   }
+
+   @Override
+   public CharSequence getCompleteHandler(Component component) {
+      return ";DisableComponentListener.hideComponent('" 
+		+ targetComponent.getMarkupId() + "');";
+   }
+   
+   protected CharSequence getIndicatorUrl(Component component) {
+      return component.urlFor(indicatorReference, null);
+   }
+   
+   @Override
+   public void renderHead(Component component, IHeaderResponse response) {   
+      ResourceReference jqueryReference = 
+      Application.get().getJavaScriptLibrarySettings().getJQueryReference();
+      response.render(JavaScriptHeaderItem.forReference(jqueryReference));      
+      response.render(JavaScriptHeaderItem.forReference(jqueryUiPositionRef));
+      response.render(JavaScriptHeaderItem.forReference(customScriptReference) );
+   }
+}
+----
+
+As you can see in the code above we have created a function (_getIndicatorUrl_) to retrieve the URL of the indicator picture. This was done in order to make the picture customizable by overriding this method.
+
+Once we have our listener in place, we can finally use it in our example overwriting method _updateAjaxAttributes_ of the AJAX button that submits the form:
+
+[source,java]
+----
+//...
+new AjaxButton("ajaxButton"){
+	@Override
+	protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+	  super.updateAjaxAttributes(attributes);
+	  attributes.getAjaxCallListeners().add(new DisableComponentListener(form));
+	}
+}
+//...
+----
+
+=== Global listeners
+
+So far we have seen how to use an AJAX call listener to track the AJAX activity of a single component. In addition to these kinds of listeners, Wicket provides also global listeners which are triggered for any AJAX request sent from a page. 
+
+Global AJAX call events are handled with JavaScript. We can register a callback function for a specific event of the AJAX call lifecycle with function _Wicket.Event.subscribe('<eventName>', <callback Function>)_. The first parameter of this function is the name of the event we want to handle. The possible names are:
+
+* '/ajax/call/init': called on initialization of an ajax call
+* '/ajax/call/before': called before any other event handler.
+* '/ajax/call/beforeSend': called just before the AJAX call.
+* '/ajax/call/after': called after the AJAX request has been sent.
+* '/ajax/call/success': called if the AJAX call has successfully returned.
+* '/ajax/call/failure': called if the AJAX call has returned with a failure.
+* '/ajax/call/complete': called when the AJAX call has completed.
+* '/ajax/call/done': called when the AJAX call is done.
+* '/dom/node/removing': called when a component is about to be removed via AJAX. This  happens when component markup is updated via AJAX (i.e. the component itself or one of its containers has been added to _AjaxRequestTarget_) 
+* '/dom/node/added': called when a component has been added via AJAX. Just like '/dom/node/removing', this event is triggered when a component is added to _AjaxRequestTarget_.
+
+The callback function takes in input the following parameters:  attrs, jqXHR, textStatus, jqEvent and errorThrown. The first three parameters are the same seen before with _IAjaxCallListener_ while jqEvent is an event internally fired by Wicket. The last parameter errorThrown indicates if an error has occurred during the AJAX call. 
+
+To see a basic example of use of a global AJAX call listener, let's go back to our custom datepicker created in 
+<<_an_example_of_integration_with_javascript,chapter 19>>. When we built it we didn't think about a possible use of the component with AJAX.  When a complex component like our datepicker is refreshed via AJAX, the following two side effects can occur: 
+
+* After been refreshed, the component loses every JavaScript handler set on it. This is not a problem for our datepicker as it sets a new JQuery datepicker every time is rendered (inside method renderHead).
+* The markup previously created with JavaScript is not removed. For our datepicker this means that the icon used to open the calendar won't be removed while a new one will be added each time the component is refreshed.
+
+To solve the second unwanted side effect we can register a global AJAX call listener that completely removes the datepicker functionality from our component before it is removed due to an AJAX refresh (which fires event '/dom/node/removing'). 
+
+Project _CustomDatepickerAjax_ contains a new version of our datepicker which adds to its JavaScript file JQDatePicker.js the code needed to register a callback function that gets rid of the JQuery datepicker before the component is removed from the DOM:
+
+[source,java]
+----
+Wicket.Event.subscribe('/dom/node/removing', 
+    function(jqEvent, attributes, jqXHR, errorThrown, textStatus) {
+	var componentId = '#' + attributes['id'];
+	if($(componentId).datepicker !== undefined)
+	      $(componentId).datepicker('destroy');
+     }
+);
+----
+
+The code above retrieves the id of the component that is about to be removed using parameter attributes. Then it checks if a JQuery datepicker was defined for the given component and if so, it removes the widget calling function destroy.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_7.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_7.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_7.adoc
new file mode 100644
index 0000000..5e04876
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_7.adoc
@@ -0,0 +1,49 @@
+
+Wicket makes working with AJAX easy and pleasant with its component-oriented abstraction. However as side effect, AJAX components and behaviors make their hosting page stateful. This can be quite annoying if we are working on a page that must be stateless (for example a login page).
+Starting from version 7.4.0 Wicket has made quite easy forcing existing AJAX components to be stateless. All we have to do is to override component's method _getStatelessHint_ returning true:
+
+[source,java]
+----
+final Link<?> incrementLink = new AjaxFallbackLink<Void>("incrementLink")
+{
+
+    ...
+    
+    @Override
+    protected boolean getStatelessHint()
+    {
+        return true;
+    }
+};
+----
+
+
+Just like components also AJAX behaviors can be turned to stateless overriding _getStatelessHint(Component component)_
+
+[source,java]
+----
+ final AjaxFormSubmitBehavior myBehavior = new AjaxFormSubmitBehavior(form, event)
+ {
+    ...
+    
+    @Override
+    protected boolean getStatelessHint(Component component)
+    {
+        return true;
+    }
+};
+----
+
+=== Usage
+
+Stateless components and behaviors follows the same rules and conventions of their standard stateful version, so they must have a markup id in order to be manipulated via JavaScript.
+However in this case calling _setOutputMarkupId_ on a component is not enough. Since we are working with a stateless page, the id of the component to refresh must be unique but also static, meaning that it should not depend on page instance. In other words, the id should be constant through different instances of the same page.
+By default calling _setOutputMarkupId_ we generate markup ids using a session-level counter and this make them not static. Hence, to refresh component in a stateless page we must provide them with static ids, either setting them in Java code (with _Component.setMarkupId_) or simply writing them directly in the markup:
+
+[source,java]
+----
+   <span id="staticIdToUse" wicket:id="componentWicketId"></span>
+----
+
+{externalink:wicket.examples.url_stateless}See examples{externalink} page for a full showcase of AJAX-stateless capabilities.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/ajax/ajax_8.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/ajax/ajax_8.adoc b/wicket-user-guide/src/main/asciidoc/ajax/ajax_8.adoc
new file mode 100644
index 0000000..b4bcb27
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/ajax/ajax_8.adoc
@@ -0,0 +1,9 @@
+
+
+
+AJAX is another example of how Wicket can simplify web technologies providing a good component and object oriented abstraction of them. 
+
+In this chapter we have seen how to take advantage of the AJAX support provided by Wicket to write AJAX-enhanced applications. Most of the chapter has been dedicated to the built-in components and behaviors that let us adopt AJAX without almost any effort. 
+
+In the final part of the chapter we have seen how Wicket physically implements an AJAX call on client side using AJAX request attributes. Then, we have learnt how to use call listeners to execute custom JavaScript during AJAX request lifecycle.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices.adoc
new file mode 100644
index 0000000..73c58a2
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices.adoc
@@ -0,0 +1,2 @@
+
+This section is addressed to developers, who have already made their first experiences with Apache Wicket. Developers who get into Wicket often have difficulties with it because they apply the typical JSF and Struts patterns and approaches. These frameworks primarily use procedural programming methods. In contrast Wicket is strongly based on object oriented patterns. So forget all Struts and JSF patterns, otherwise you won't have fun with Wicket in the long run.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_1.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_1.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_1.adoc
new file mode 100644
index 0000000..32dc926
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_1.adoc
@@ -0,0 +1,128 @@
+
+
+
+A component should be self-contained. The user of a component should neither have to know nor care about its internal structure. She should just be familiar with its external interfaces and its documentation in order to be able to use it. This means in detail: Every component that extends Wicket's own Panel type (thus is a Panel itself) must provide its own HTML template. In contrast, when a component extends the classes _WebMarkupContainer_ or _Form_, there is no HTML template. This implies that you should add components through composition in _WebMarkupContainer_ or _Form_.
+
+*Listing 1:*
+
+[source,java]
+----
+// Poor component
+public class RegistrationForm extends Form<Registration> {
+    public RegistrationForm(String id, IModel<Registration> regModel) {
+        super(id, new CompoundPropertyModel<Registration>(regModel))
+        // Wrong: RegistrationForm provides its own components
+        add(new TextField("username"));
+        add(new TextField("firstname"));
+        add(new TextField("lastname"));
+    }
+}
+----
+
+This snippet is an example for a poor component. The user of the _RegistrationForm_ must know the internal structure of the markup and component in order to use it.
+
+*Listing 2:*
+
+[source,java]
+----
+public class RegistrationPage extends Page {
+    public RegistrationPage(IModel<Registration> regModel) {
+        Form<?> form = new RegistrationForm("form");
+        form.add(new SubmitButton("register") {
+            public void onSubmit() {
+                 // do something
+            }
+        });
+        add(form);
+    }
+}
+----
+
+[source,html]
+----
+<html>
+<body>
+    <form wicket:id="form">
+        <!-- These are internal structure information from RegistrationForm -->
+        Username <input type="text" wicket:id="username"/>
+        First name <input type="text" wicket:id="firstname"/>
+        Last name <input type="text" wicket:id="lastname"/>
+        <!-- Above new components from page which the user knows  -->
+        <input type="submit" wicket:id="register" value="Register"/>
+    </form>
+</body>
+</html>
+----
+
+The code above shows the usage of the poor component in the _RegistrationPage_. You can see that the input fields _firstname_, _lastname_ and _username_ get used, even though these components are not added explicitly to the _RegistrationPage_. Avoid this, because other developers cannot directly see that the components were added in _RegistrationPage_ class.
+
+*Listing 3:*
+
+[source,java]
+----
+// Good component
+public class RegistrationInputPanel extends Panel{
+    public RegistrationInputPanel(String id, IModel<Registration> regModel) {
+        super(id, regModel);
+        IModel<Registration> compound = new CompoundPropertyModel<Registration(regmodel)
+        Form<Registration> form = new Form<Registration>("form", compound);
+        // Correct: Add components to Form over the instance variable
+        form.add(new TextField("username"));
+        form.add(new TextField("firstname"));
+        form.add(new TextField("lastname"));
+        add(form);
+    }
+}
+----
+
+[source,html]
+----
+<html>
+<body>
+    <wicket:panel>
+    <form wicket:id="form">
+        Username <input type="text" wicket:id="username"/>
+        First name <input type="text" wicket:id="firstname"/>
+        Last name <input type="text" wicket:id="lastname"/>
+    </form>
+    </wicket:panel>
+</body>
+</html>
+----
+
+Now we have a properly encapsulated input component which provides its own markup. Furthermore you can see the correct usage of a Wicket _Form_. The components get added by calling _form.add(Component)_ on the instance variable. On the other hand, it is allowed to add behaviours and validators over inheritance, because those do not have markup ids which must be bound.
+
+With that, the usage of _RegistrationInputPanel_ is much more intuitive. There is no markup of other embedded components present anymore, just markup of components which get directly added. The _RegistrationPage_ provides its own form that delegates the submit to all Wicket nested forms which are contained in the component tree.
+
+*Listing 4:*
+
+[source,java]
+----
+public class RegistrationPage extends Page {
+    public RegistrationPage(IModel<Registration> regModel) {
+        Form<?> form = new Form("form");
+        form.add(new RegistrationInputPanel("registration", regModel);
+        form.add(new SubmitButton("register") {
+            public void onSubmit() {
+              // do something
+            }
+        });
+        add(form);
+    }
+}
+----
+
+[source,html]
+----
+<html>
+<body>
+    <form wicket:id="form">
+        <div wicket:id="registration">
+           Display the RegistrationInputPanel
+        </div>
+        <input type=&rdquo;submit&rdquo; wicket:id="register" value="Register"/>
+    </form>
+</body>
+</html>
+----
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc
new file mode 100644
index 0000000..73129ab
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_10.adoc
@@ -0,0 +1,65 @@
+
+
+
+Do not pass entire components or pages to constructors of other components.
+
+*Listing 12:*
+
+[source,java]
+----
+// Bad solution
+public class SettingsPage extends Page {
+    public SettingsPage (IModel<Settings> settingsModel, final Webpage backToPage) {
+        Form<?> form = new Form("form");
+        // add components
+        form.add(new SubmitButton("changeSettings") {
+            public void onSubmit() {
+               // do something
+               setResponsePage(backToPage);
+            }
+        });
+        add(form);
+    }
+}
+----
+
+The _SettingsPage_ expects the page which should be displayed after a successful submit to be passed to its constructor. This solution works, but is very bad practice. You need to know during the instanciation of _SettingsPage_ where you want to redirect the user. This requires a predetermined order of instanciation. It is better to order the instanciation based on business logic (e.g. the order in the HTML template).�Furthermore, you need an unnecessary instance of the next success page which might never be displayed. The solution is once again the Hollywood principle. For this you create an abstract method or a hook:
+
+*Listing 13:*
+
+[source,java]
+----
+// Good solution
+public class SettingsPage extends Page {
+    public SettingsPage (IModel<Settings> settingsModel) {
+        Form<?> form = new Form("form");
+        // add components
+        form.add(new SubmitButton("changeSettings") {
+            public void onSubmit() {
+               // do something
+               onSettingsChanged();
+            }
+         });
+         add(form);
+    }
+
+    // hook
+    protected void onSettingsChanged() {
+    }
+
+// The usage of the new component
+Link<Void> settings = new Link<Void>("settings") {
+    public void onClick() {
+        setResponsePage(new SettingsPage(settingsModel) {
+            @Override
+            protected void onSettingsChanged() {
+               // reference to the current page
+               setResponsePage(this);
+            }
+        });
+    }
+}
+add(settings);
+----
+
+This solution has more code, but it is more flexible and reuseable. We can see there is an event _onSettingsChanged()_ and this event is called after a successful change. Furthermore, there is the possibility to execute additional code besides setting the next page. For example, you can display messages or persist information.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_11.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_11.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_11.adoc
new file mode 100644
index 0000000..8fcd53c
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_11.adoc
@@ -0,0 +1,26 @@
+
+
+
+The Wicket session is your own extension of Wicket's base session. It is fully typed. There is no map structure to store information unlike the servlet session. You just should use Wicket's session for global data. Authentication is a good example for global data. The login and user information is required on nearly each page. For a blog application it would be good to know whether the user is an author who is allowed to compose blog entries. So you are able to hide or or show links to edit a blog entry. In general you should store the whole authorization logic in Wicket's session, because it is a global thing and you would expect it there. Data of forms and flows which only span certain pages should not stored in the session. This data can be passed from one page to the next via the constructor (see listing 14). As a consequence of this, the models and data have a clearly defined lifecycle that reflects the corresponding the page flow.
+
+*Listing 14:*
+
+[source,java]
+----
+public class MyPage extends WebPage {
+    IModel<MyData> myDataModel;
+
+    public MyPage(IModel<MyData> myDataModel) {
+        this.myDataModel = myDataModel;
+        Link<Void> next = new Link<Void>("next") {
+             public void onClick() {
+                  // do something
+                  setResponsePage(new NextPage(myDataModel));
+             }
+        }
+        add(next);
+    }
+}
+----
+
+You should pass concrete information to the page. All models can simply be stored in fields because Wicket pages are user-specific instances and no singletons in contrast to Struts. The big advantage of this approach is that the data gets automatically cleaned up when a user completes or exits the page flow. No manual cleanup anymore! This is basically an automatic garbage collector for your session.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_12.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_12.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_12.adoc
new file mode 100644
index 0000000..1aa9260
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_12.adoc
@@ -0,0 +1,70 @@
+
+
+
+The factory pattern is useful, but nevertheless not suitable for Wicket components.
+
+*Listing 15:*
+
+[source,java]
+----
+public class CmsFactory {
+   public Label getCmsLabel(String markupId, final String url) {
+       IModel<String> fragment = new AbstractReadOnlyModel<String>() {
+          @Override
+          public String getObject() {
+             return loadSomeContent(url);
+          }
+       };
+       Label result = new Label(markupId, fragment);
+       result.setRenderBodyOnly(true);
+       result.setEscapeModelStrings(false);
+       return result;
+   }
+
+   public String loadContent(String url) {
+      // load some content
+   }
+}
+
+// create the component within the page:
+public class MyPage extends WebPage {
+   @SpringBean
+   CmsFactory cmsFactory;
+
+   public MyPage() {
+      add(cmsFactory.getCmsLabel("id", "http://url.to.load.from"));
+   }
+}
+----
+
+This approach for adding a label from the _CmsFactory_ to a page seems to be okay at first glance, but it comes with some disadvantages. There is no possibility to use inheritance anymore. Furthermore, there is no possibility to override _isVisible()_ and _isEnabled()_. The factory could also be a Spring service which instanciates the component. A better solution is to create a _CmsLabel_.
+
+*Listing 16:*
+
+[source,java]
+----
+public class CmsLabel extends Label {
+   @SpringBean
+   CmsResource cmsResource;
+   public CmsLabel(String id, IModel<String> urlModel) {
+      super(id, urlModel);
+      IModel<String> fragment = new AbstractReadOnlyModel<String>(){
+         @Override
+         public String getObject() {
+            return cmsResource.loadSomeContent(urlModel.getObject());
+         }
+      };
+      setRenderBodyOnly(true);
+      setEscapeModelStrings(false);
+   }
+}
+
+// create the component within a page
+public class MyPage extends WebPage {
+   public MyPage() {
+      add(new CmsLabel("id", Model.of("http://url.to.load.from")));
+   }
+}
+----
+
+The label in listing 16 is clearly encapsulated in a component without using a factory. Now you can easily create inline implementations and override _isVisible()_ or other stuff. Naturally, you might claim  [I need a factory to initialize some values in the component, e.g. a Spring service.] For this you can create a implementation of _IComponentInstantiationListener_. This listener gets called on the super-constructor of every component. The most popular implementation of this interface is the _SpringComponentInjector_ which injects Spring beans in components when the fields are annotated with _\_SpringBean_. You can easliy write and add your own implementation of _IComponentInstantiationListener_. So there is no reason for using a factory anymore. More information about the instanciation listener is located in Wicket's JavaDoc.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_13.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_13.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_13.adoc
new file mode 100644
index 0000000..0c2bec4
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_13.adoc
@@ -0,0 +1,4 @@
+
+
+
+Every page and component should have a test. The simplest test just renders the component and validates its technical correctness. For example, a child component should have a matching wicket id in the markup. If the wicket id is not correctly bound - through a typo or if it was just forgotten - the test will fail. An advanced test could test a form, where a backend call gets executed and validated over a mock. So you can validate your component's behaviour. This is a simple way to detect and fix technical and business logic bugs during the build process. Wicket is very suitable for a test driven development approach. For instance, if you run a unit test which fails and shows a message that the wicket id not bound, you will avoid an unneccessary server startup (a server startup takes longer than running a unit test). This reduces the development turnaround. A disadvantage is the difficult testing possibility of AJAX components. However, the testing features of Wicket are much more s
 ophisticated than in other web frameworks.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_14.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_14.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_14.adoc
new file mode 100644
index 0000000..7e52c86
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_14.adoc
@@ -0,0 +1,5 @@
+
+
+
+Try to get within the Wicket world whenever possible. Avoid the usage of other servlet filters. For this you can use the _RequestCycle_ and override the methods _onBeginRequest()_ and _onEndRequest()_. You can apply the same to the _HttpSession_. The equivalent in Wicket is the _WebSession_. Just extend the _WebSession_ and override the _newSession()_-method from the Application class. There are very few reasons to access the servlet interfaces. An example could be to read an external cookie to authenticate a user. Those parts should be properly encapsulated and avoided when possible. For this example, you could do the handling within the Wicket session because this is an authentication.
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_15.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_15.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_15.adoc
new file mode 100644
index 0000000..ff99a53
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_15.adoc
@@ -0,0 +1,33 @@
+
+
+
+Avoid monolithic classes. Often I have seen that developers put the whole stuff into constructors. These classes are getting very unclear and chaotic because you use inline implementations over serveral levels. It is recommended to group logical units and extract methods with a correct business naming. This enhances the clarity and the understandability of the business aspect. When a developer navigates to a component, he is not interested in the technical aspect at first, however he just need the business aspect. To retrieve technical information of a component you can navigate to the method implementation. In case of doubt you should consider to extract seperate components. Smaller components increase the chances of reuse and make testing easier. Listing 17 shows an example of a possible structuring.
+
+*Listing 17:*
+
+[source,java]
+----
+public class BlogEditPage extends WebPage {
+    private IModel<Blog> blogModel;
+
+    public BlogEditPage(IModel<Blog> blogModel) {
+        super(new PageParameters());
+        this.blogModel = blogModel;
+        add(createBlogEditForm());
+    }
+
+    private Form<Blog> createBlogEditForm() {
+        Form<Blog> form = newBlogEditForm();
+        form.add(createHeadlineField());
+        form.add(createContentField());
+        form.add(createTagField());
+        form.add(createViewRightPanel());
+        form.add(createCommentRightPanel());
+        form.setOutputMarkupId(true);
+        return form;
+    }
+
+    // more methods here
+}
+----
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_16.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_16.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_16.adoc
new file mode 100644
index 0000000..9aa39f2
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_16.adoc
@@ -0,0 +1,7 @@
+
+
+
+It is a widespread opinion that Wicket has a bad documentation. This argument is just partly correct. There are a lot of code samples and snippets which can be used as code templates. Furthermore, there is a big community that answers complex questions very quickly. In Wicket it is very hard to document everything, because nearly everything is extensible and replaceable. If a component is not completely suitable, you will extend or replace it. Working with Wicket means permanently navigating through code. For example, just consider validators. How can I find all navigators that exist? Open the interface _IValidator_ (Eclipse: Ctrl + Shift + T) and then open the type hierachy (Crtl + T). Now we can see all the validators existing in Wicket and our project.
+
+image::../img/validator-type-hierachy.png[]
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_17.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_17.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_17.adoc
new file mode 100644
index 0000000..dfd00f3
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_17.adoc
@@ -0,0 +1,4 @@
+
+
+
+The best practices presented in this chapter should help you to write better and more maintainable code in Wicket. All described methodologies were already proven in a few Wicket projects. If you follow these advices, your Wicket projects will get future-proof and hopefully successful.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_2.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_2.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_2.adoc
new file mode 100644
index 0000000..0e86958
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_2.adoc
@@ -0,0 +1,4 @@
+
+
+
+In contrast to Struts, Wicket pages and components are no singletons, they are stateful and session-scoped. This enables us to store user-specific information within pages and components. The information should be stored in fields. This way you can access the information within a class while avoiding long method signatures only for passing the same information around. Instances of components can exist for several requests. For example, a page with a form which gets submitted and produces validation errors uses the same page instance. Furthermore the same page instance gets used when the user presses the back button of the browser and resubmits this formular again. Information which gets passed by the constructor should be assigned to fields (normally this must be models). When storing information in fields you should consider that the information is serializable, because the pages are stored using Java serialization. By default Wicket stores pages on the hard disk. A non-serializabl
 e object leads to _NullPointerExceptions_ and _NonSerializableExceptions_. Additionally, big data (like binary stuff) should not be stored directly in fields because this can cause performance losses and memory leaks during serialization and deserialization. In this case, you should use the _LoadableDetachableModel_ which can be assigned to a field because this provides an efficient mechanism to load and detach data.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_3.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_3.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_3.adoc
new file mode 100644
index 0000000..1bd4c86
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_3.adoc
@@ -0,0 +1,6 @@
+
+
+
+For many developers, naming is a dispensable thing, but I think it is one of the major topics in software development. With the help of correct naming, you can easily identify the business aspects of a software component. Additionally good naming avoids unneccessary and bad comments.
+
+Bad namings for Wicket-IDs are _birthdateTextField_, _firstnameField_ and _addressPanel_. Why? The naming contains two aspects: A technical aspect (_ )[TextField] and the business aspect (_ ).[birthdate] Only the the business aspect is relevant because both the HTML template as well as the Java code already contain the technical details ( [")@)] xtField( [")@)] te [)@)] Additionally, such names add a lot of effort when you do technical refactorings, e.g. if you have to replace a _TextField_ by a _DatePicker_ and the Wicket ID _birthdateTextField_ becomes _birthdateDatePicker_. Another reason for avoiding technical aspects in Wicket IDs is the _CompoundPropertyModel_. This model delegates the properties to its child components named by Wicket IDs (see listing 3). For example the _TextField username_ automatically calls _setUsername()_ and _getUsername()_ on the _Registration_ object. A setter like _setUsernameTextfield()_ would be very inconvenient here.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_4.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_4.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_4.adoc
new file mode 100644
index 0000000..f4fffef
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_4.adoc
@@ -0,0 +1,19 @@
+
+
+
+You should consider Wicket's component tree a constant and fixed skeleton which gets revived when its model is filled with data like a robot without brain. Without brain the robot is not able to do anything and is just a dead and fixed skeleton. However, when you fill it with data, it becomes alive and can act. There is no need for changing hardware when filling him with data. In Wicket, you should manipulate the component tree as little as possible. Consequently, you should avoid calling methods like _Component.replace(Component)_ and _Component.remove(Component)_. Calling these methods indicates missing usage or misusage of Wicket's models. Furthermore the component trees should not be constructed using conditions (see listing 5). This reduces the possibility of reusing the same instance significantly.
+
+*Listing 5:*
+
+[source,java]
+----
+// typical for struts
+if(MySession.get().isNotLoggedIn()) {
+    add(new LoginBoxPanel("login"))
+}
+else {
+    add(new EmptyPanel("login"))
+}
+----
+
+Instead of constructing _LoginBoxPanel_ conditionally, it is recommended to always add the panel  and control the visibility by overriding _isVisible()_. So the component _LoginBoxPanel_ is responsible for displaying itself. We move the responsibility into the same component which executes the login. Brilliant! Cleanly encapsulated business logic. There is no decision from outside, the component handles all the logic. You can see another example in  [Implement visibilities of components correctly] .

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc
new file mode 100644
index 0000000..ed1a4f2
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_5.adoc
@@ -0,0 +1,52 @@
+
+
+
+Visibility of components is an important topic. In Wicket you control any component's visibility via the methods�_isVisible()_ and _setVisible()_. These methods are within Wicket's base class _Component_ and therefore it is applicable for every component and page. Let's have a look at a concrete example of _LoginBoxPanel_. The panel just gets displayed when the user is not logged in.
+
+*Listing 6:*
+
+[source,java]
+----
+// Poor implementation
+LoginBoxPanel loginBox = new LoginBoxPanel("login");
+loginBox.setVisible(MySession.get().isNotLoggedIn());
+add(loginBox);
+----
+
+Listing 6 shows a poor implementation, because a decision about the visibility is made while instanciating the component. Again, in Wicket instances of components exist for several requests. To reuse the same instance you have to call _loginBox.setVisible(false)_. This is very unhandy, because we always have to call _setVisible()_ and manage the visibility. Furthermore you are going to duplicate the states, because visible is equal to  [not logged in] So we have two saved states, one for the business aspect  [not logged in] and one for the technical aspect  [visible] Both is always equal. This approach is error-prone and fragile, because we always have to pay attention to setting the correct information every time. But this is often forgotten because the logic is widely spread over the code. The solution is the Hollywood principle:  [Don't call us, we'll call you.] Take a look at the following diagram illustrating an application flow with some calls. We avoid three calls through the
   http://en.wikipedia.org/wiki/Hollywood_Principle[Hollywood-Principle] and we just have to instanciate the _LoginBoxPanel_.
+
+image::../img/login_calls_hollywood.png[]
+
+*Listing 7:*
+
+[source,java]
+----
+public class LoginBoxPanel {
+    // constructor etc.
+    @Override
+    public boolean isVisible() {
+        return MySession.get().isNotLoggedIn();
+    }
+};
+----
+
+Now the control over visibility has been inverted, the _LoginBoxPanel_ decides on its visibility autonomously. For each call of _isVisible()_ there is a refreshed interpretion of the login state. Hence, there is no additional state that might be outdated. The logic is centralized in one line code and not spread throughout the application. Furthermore, you can easily identify that the technical aspect _isVisible()_ correlates to the business aspect  [logged in] The same rules can be applied to the method _isEnabled()_. If _isEnabled()_ returns false the components get displayed in gray. Forms which are within an inactive or invisible component do not get executed.
+
+Note that there are cases in which you cannot avoid�to call the methods _setVisible()_ and _setEnabled()_. An example: The user presses a button to display an inlined registration form. In general, you can apply the following rules: data driven components override these methods and delegates to the data model. User triggered events call the method _setVisible(boolean)_. You can also override these methods with inline implementations:
+
+*Listing 8:*
+
+[source,java]
+----
+new Label("headline", headlineModel) {
+    @Override
+    public boolean isVisible() {
+        // Hidden headline if text starts with "Berlusconi"
+        String headline = getModelObject();
+        return headline.startWith("Berlusconi");
+    }
+}
+----
+
+*Note:* Some people insist on overriding _isVisible()_ being http://www.mail-archive.com/dev\@wicket.apache.org/msg07123.html[a bad thing]
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_6.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_6.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_6.adoc
new file mode 100644
index 0000000..855c3c7
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_6.adoc
@@ -0,0 +1,18 @@
+
+
+
+Always use models - period! Do not pass raw objects directly to components. Instances of pages and components can exist for several requests. If you use raw objects, you cannot replace them later. An example is an entity which gets loaded at each request within a _LoadableDetachableModel_. The entity manager creates a new object reference, but the page would keep the obsolete instance. Always pass _IModel_ in the constructor of your components:
+
+*Listing 9:*
+
+[source,java]
+----
+public class RegistrationInputPanel extends Panel{
+    // Correct: The class Registration gets wrapped by IModel
+    public RegistrationInputPanel(String id, IModel<Registration> regModel) {
+        // add components
+    }
+}
+----
+
+This code can use any implementation of _IModel_, e.g. the class _Model_, a _PropertyModel_ or a custom implementation of _LoadableDetachableModel_ which loads and persists the values automatically. The model implementations gets very easy to replace. You - as a developer - just need to know: if I call _IModel.getObject()_, I will get an object of type _Registration_. Where the object comes from is within the responsibility of the model implementation and the calling component. For example you can pass the model while instanciating the component. If you avoid using models, you will almost certainly have to modify the component tree sooner or later which forces you to duplicate states and thus produce unmaintainable code. Additionally, you should use models due to serialization issues. Objects which get stored in fields of pages and components get serialized and deserialized on each request. This can be inefficient in some cases.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_7.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_7.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_7.adoc
new file mode 100644
index 0000000..1c6cf66
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_7.adoc
@@ -0,0 +1,19 @@
+
+
+
+Avoid unwrapping models within the constructor hierarchy, i.e. do not call _IModel.getObject()_ within any constructor. As already mentioned, a page instance can exist for several page requests, so you might store obsolete and redundant infomation. It is reasonable to unpack Wicket Models at events (user actions), that are methods like _onUpdate()_, _onClick() or _onSubmit()_:
+
+*Listing 10:*
+
+[source,java]
+----
+new Form("register") {
+    public void onSubmit() {
+        // correct, unwrap model in an event call
+        Registration reg = registrationModel.getObject()
+        userService.register(reg);
+    }
+}
+----
+
+An additional possibility to unwrap models is via overriding methods like _isVisible()_, _isEnabled()_ or _onBeforeRender()_.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_8.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_8.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_8.adoc
new file mode 100644
index 0000000..8f1725a
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_8.adoc
@@ -0,0 +1,17 @@
+
+
+
+Always try to pass models on to the parent component. By that, you ensure that at the end of every request the method _IModel.detach()_ gets called. This method is responsible for a data cleanup. Another example: you have implemented your own model which persists the data in the _detach()_ method. So the call of _detach()_ is necessary for that your data gets persisted. You can see an exemplary passing to the super constructor here:
+
+*Listing 11:*
+
+[source,java]
+----
+public class RegistrationInputPanel extends Panel{
+    public RegistrationInputPanel(String id, IModel<Registration> regModel) {
+        super(id, regModel)
+        // add components
+    }
+}
+----
+

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_9.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_9.adoc b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_9.adoc
new file mode 100644
index 0000000..cff5fa2
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/bestpractices/bestpractices_9.adoc
@@ -0,0 +1,4 @@
+
+
+
+Validators should just validate. Consider a bank account form which has a _BankFormValidator_. This validator checks the bank data over a webservice and corrects the bank name. Nobody would expect that a validator modifies information. Such logic has to be located in _Form.onSubmit()_ or in the event logic of a button.

http://git-wip-us.apache.org/repos/asf/wicket/blob/7eba9998/wicket-user-guide/src/main/asciidoc/componentLifecycle.adoc
----------------------------------------------------------------------
diff --git a/wicket-user-guide/src/main/asciidoc/componentLifecycle.adoc b/wicket-user-guide/src/main/asciidoc/componentLifecycle.adoc
new file mode 100644
index 0000000..a56e44b
--- /dev/null
+++ b/wicket-user-guide/src/main/asciidoc/componentLifecycle.adoc
@@ -0,0 +1,2 @@
+
+Just like applets and servlets, also Wicket components follow a lifecycle during their existence. In this chapter we will analyze each stage of this cycle and we will learn how to make the most of the hook methods that are triggered when a component moves from one stage to another.