Article summary

Summary

Discusses how to create a custom form action for an Experience Manager form built by using Form components.  

A special thank you to Ranta and Prince Shivhare, top AEM community members, for testing this article to ensure it works.

Digital Marketing Solution(s) Adobe Experience Manager 6.2
Audience Developer
Required Skills Java, HTML, JQuery
Version 6.2

Introduction

You can create an Adobe Experience Manager (AEM) form by using form components (such as the TextField component) located in the Forms Category and submit the data to a custom form action. The custom form action can send the data to an Experience Manager service that can process the data to meet your business requirements. For example, you can store the data in a database or send the data within an email message. However, to keep this article simple, the custom AEM service writes the posted data to the AEM log file.

An Experience Manager form can be consumed in a mobile device or a web browser running on a desktop. For example, consider a desktop user filling out the following form.

An Experience Manager Form built with Form components located in the Forms Category

You can build a custom form action that is invoked when an end user fills out the form and clicks the submit button. In this article, the custom form action named customFormAction is created, as shown in the following illustration.  

An Experience Manager Custom Form Action

This custom form action sends the posted data to an Experience Manager service. 

Create an application folder structure

Create an application folder structure that contains templates, components, and pages by using CRXDE Lite.

An Experience Manager folder structure

The following describes each Experience Manager folder:

  • application name: contains all of the resources that an application uses. The resources can be templates, pages, components, and so on. 
  • components: contains components that your application uses. 
  • content: contains page components. A page component is a script such as a JSP file.
  • structure: contains indivudual components that your application uses. For example, a header. 
  • template: contains templates on which you base page components. 

To create an application folder structure:

  1. To view the CQ welcome page, enter the URL http://[host name]:[port] into a web browser. For example, http://localhost:4502.
  2. Go to CRXDE Lite at http://localhost:4502/crx/de/index.jsp.
  3. Right-click the apps folder (or the parent folder), select Create, Create Folder.
  4. Enter the folder name into the Create Folder dialog box. Enter customFormAction
  5. Repeat steps 1-4 for each folder specified in the previous illustration. 
  6. Click the Save All button.

Note:

You have to click the Save All button when working in CRXDE Lite for the changes to be made.

Create a template for the page component

You can create a template by using CRXDE Lite. An AEM template enables you to define a consistent style for the pages in your application. A template comprises of nodes that specify the page structure. For more information about templates, see Templates.

To create a template, perform these tasks:

1. Go to Select CRXDE Lite at http://localhost:4502/crx/de/index.jsp.
2. Right-click the template folder (within your application), select Create, Create Template.
3. Enter the following information into the Create Template dialog box:

  • Label: The name of the template to create. Enter formTemplate
  • Title: The title that is assigned to the template. Enter formTemplate.
  • Description: The description that is assigned to the template.
  • Resource Type: The component's path that is assigned to the template and copied to implementing pages. Enter /apps/customFormAction/components/content/formTemplate.
  • Ranking: The order (ascending) in which this template will appear in relation to other templates. Setting this value to 1 ensures that the template appears first in the list.

4. Add a path to Allowed Paths. Click on the plus sign and enter the following value: /content(/.*)?.
5. Click Next for Allowed Parents.
6. Select OK on Allowed Children.

Create a Page Rendering Component

Components are re-usable modules that implement specific application logic to render the content of your web site. You can think of a component as a collection of scripts (for example, JSPs, Java servlets, and so on) that completely realize a specific function. In order to realize this functionality, it is your responsibility as a CQ developer to create scripts that perform specific functionality. For more information about components, see Components.

By default, a component has at least one default script, identical to the name of the component. To create a render component, perform these tasks:

1. Go to Select CRXDE Lite at http://localhost:4502/crx/de/index.jsp.

2. Right-click /apps/customFormAction/components/content, then select Create, Create Component.

3. Enter the following information into the Create Component dialog box:

  • Label: The name of the component to create. Enter formTemplate
  • Title: The title that is assigned to the component. Enter formTemplate.
  • Description: The description that is assigned to the template. Enter formTemplate.
  • Super Type: foundation/components/page

4. Select Next for Advanced Component Settings and Allowed Parents.

5. Select OK on Allowed Children.

6. Open the slingTemplateJCR.jsp located at: /apps/customFormAction/components/content/formTemplate/formTemplate.jsp.

7. Add the following code to formTemplate.JSP. 

<html>
<%@include file="/libs/foundation/global.jsp" %>
<cq:include script="/libs/wcm/core/components/init/init.jsp"/>
<body>
<h1>An Experience Manager Sample Form</h1>
<cq:include path="par" resourceType="foundation/components/parsys" />
</body>
</html>

Setup Maven in your development environment

You can use Maven to build an OSGi bundle that uses the JCR API and is deployed to Experience Manager. Maven manages required JAR files that a Java project needs in its class path. Instead of searching the Internet trying to find and download third-party JAR files to include in your project’s class path, Maven manages these dependencies for you.

You can download Maven 3 from the following URL:

http://maven.apache.org/download.html

After you download and extract Maven, create an environment variable named M3_HOME. Assign the Maven install location to this environment variable. For example:

C:\Programs\Apache\apache-maven-3.0.4

Set up a system environment variable to reference Maven. To test whether you properly setup Maven, enter the following Maven command into a command prompt:

%M3_HOME%\bin\mvn -version

This command provides Maven and Java install details and resembles the following message:

Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

Note:

For more information about setting up Maven and the Home variable, see: Maven in 5 Minutes.

Next, copy the Maven configuration file named settings.xml from [install location]\apache-maven-3.0.4\conf\ to your user profile. For example, C:\Users\scottm\.m2\.

You have to configure your settings.xml file to use Adobe’s public repository. For information, see Adobe Public Maven Repository at http://repo.adobe.com/.

Create an Experience Manager archetype project

You can create an Experience Manager archetype project by using the Maven archetype plugin. In this example, assume that the working directory is C:\AdobeCQ.

Maven generated files

To create an Experience Manager archetype project, perform these steps:

1. Open the command prompt and go to your working directory (for example, C:\AdobeCQ).

2. Run the following Maven command:

mvn archetype:generate -DarchetypeRepository=https://repo.adobe.com/nexus/content/groups/public/ -DarchetypeGroupId=com.day.jcr.vault -DarchetypeArtifactId=multimodule-content-package-archetype -DarchetypeVersion=1.0.2 -DgroupId=com.adobe.cq -DartifactId=form -Dversion=1.0-SNAPSHOT -Dpackage=com.adobe.cq -DappsFolderName=myproject -DartifactName="My Project" -DcqVersion="5.6.1" -DpackageGroup="My Company"

3. When prompted for additional information, specify Y.

4. Once done, you will see a message like:
[[INFO] Total time: 14:46.131s
[INFO] Finished at: Wed Mar 27 13:38:58 EDT 2013
[INFO] Final Memory: 10M/184M

5. Change the command prompt to the generated project. For example: C:\AdobeCQ\form. Run the following Maven command:

mvn eclipse:eclipse

After you run this command, you can import the project into Eclipse as discussed in the next section.

Note:

This Maven command creates a single bundle and does not create all of the other files that the Maven Archetype 10 archetype creates. This is the reason why this Maven command is used in this use case as opposed to the Maven Archetype 10 archetype.

Add Java files to the Maven project using Eclipse

To make it easier to work with the Maven generated project, import it into the Eclipse development environment, as shown in the following illustration.

The Eclipse Import Project dialog

Note:

Do not worry about the errors reported in Eclipse. It does not read the POM file where the APIs are resolved. You build the bundle with Maven. Eclipse is used to edit the Java files and the POM file. Delete the content project from the Eclipse IDE. Work in the bundle project and make sure that you work in the com.adobe.cq package.

The next step is to add the following Java files to the com.adobe.cq package:

  • A Java interface named HandleForm.
  • A Java class named HandleFormImp that implements the HandleForm interface

HandleForm interface

The following code represents the HandleForm interface. This interface contains a method signature named injestFormData. The implementation logic for this method is located in the HandleFormImp class.

package com.adobe.cq;
 
public interface HandleForm {
     
    public void injestFormData(String First, String Last, String City, String Address); 
 
}

HandleFormImpl class

The HandleFormImp class uses the following Apache Felix SCR annotations to create the OSGi component:

  • @Component – defines the class as a component
  • @Service - defines the service interface that is provided by the component

In this use case, the values that are submitted from the form are written to the AEM log file. The following Java code represents the HandleFormImpl class.
 

package com.adobe.cq;
 
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
     
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
 
//This is a component so it can provide or consume services
@Component
    
@Service
public class HandleFormImpl implements HandleForm {
     
    /** Default log. */
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
 
    @Override
    public void injestFormData(String First, String Last, String City,
            String Address) {
         
        //Simply write out the values that are posted from the AEM form to the AEM log file
        log.info("Data posted from the AEM EXAMPLE form - First: "+First +" Last: "+Last +" City: "+City +" Address "+Address) ;
    }
 
}

Note:

Once you have the submitted form values in the OSGi service, you can perform additional business logic to meet your business requirements. For example, you can use a DataSourcePool to store the data into a relational database. For information, see Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi bundle.

Modify the Maven POM file

Modify the POM files to successfully build the OSGi bundle. In the POM file located at C:\AdobeCQ\form\bundle, add the following dependencies.

  • org.apache.felix.scr
  • org.apache.felix.scr.annotations
  • org.apache.sling

The following XML represents this POM file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">
    <modelVersion>4.0.0</modelVersion>
    <!-- ====================================================================== -->
    <!-- P A R E N T P R O J E C T D E S C R I P T I O N -->
    <!-- ====================================================================== -->
    <parent>
        <groupId>com.adobe.cq</groupId>
        <artifactId>form</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!-- ====================================================================== -->
    <!-- P R O J E C T D E S C R I P T I O N -->
    <!-- ====================================================================== -->

    <artifactId>form-bundle</artifactId>
    <packaging>bundle</packaging>
    <name>My Project Bundle</name>

    <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>biz.aQute</groupId>
            <artifactId>bndlib</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.jcr</groupId>
            <artifactId>jcr</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.jcr.api</artifactId>
        </dependency>
    </dependencies>

    <!-- ====================================================================== -->
    <!-- B U I L D D E F I N I T I O N -->
    <!-- ====================================================================== -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-scr-descriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>com.adobe.cq.form-bundle</Bundle-SymbolicName>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.sling</groupId>
                <artifactId>maven-sling-plugin</artifactId>
                <configuration>
                    <slingUrl>http://${crx.host}:${crx.port}/apps/myproject/install</slingUrl>
                    <usePut>true</usePut>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                 <configuration>
                    <excludePackageNames>
                        *.impl
                    </excludePackageNames>
                 </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Build the OSGi bundle using Maven

To build and deploy the OSGi bundle, perform these tasks: 

  1. Open the command prompt and go to the C:\AdobeCQ\form folder.
  2. Run the following maven command: mvn -PautoInstallPackage install.
  3. The OSGi component can be found in the following folder: C:\AdobeCQ\form\bundle\target. The file name of the OSGi component is form-bundle-1.jar.

Note:

The command -PautoInstallPackage automatically deploys the OSGi bundle to AEM.

Build the AEM Form using Form components

Build the AEM form by using Form components. In this article, the Form is built by using the Touch UI and dragging and dropping the form components from the side rail to the AEM page, as shown in the following illustration. 

A form Text field component being dragged onto an AEM page

Ensure form components show up in page

When you build the form, you may notice that components do not show up in the side rail. To address this situtation, view the page in Classic view and go into Design mode. Then click Edit button and you will see the following view. Click the Form category. 

Click the Forms category

Create the form

Create a form located in an Experience Manager page based on the formTemplate by using the AEM Touch UI. Perform these tasks:

1. Click the Adobe Experience Manager in the upper left corner.

2. Navigate to Sites.

3. Click Create, page. 

4. Select the formTemplate, as shown in this illustration. 

 

The formTemplate shown in the Touch UI

5. Click Next.

6. Create a page with the following values:

  • Name: form
  • Title: MyForm

7. Click Create to open the page. 

8. Drag and Drop the Form component into the page (if empty - see the instructions listed in this section). Ensure your page resembles this illustration

 

An AEM page with a form component

9. Drag four text fields onto your form named First, Last, City and Address.

 

TextFields located in the AEM form

10. Drop the Submit button onto the form, as shown in the previous illustration. 

 

Create a custom form action for the Experience Manager form

Create a custom form action for the form so the posted data is sent to the HandleForm service that you created. To create a custom form action, you setup nodes and properties within the AEM repository. In addition, you define a JSP file named post.POST.jsp. When the user fills out the form and clicks the submit button, form data is posted to the post.POST.jsp. This JSP captures the submitted data and passes the data to a custom service defined within an OSGi bundle. 

A custom form action defined in the JCR

To create a custom form action, perform these tasks: 

1. Log in to CRXDE Lite at http://{server}:{port}/crx/de/index.jsp. Create a node with the property sling:Folder with the name customFormAction in the /apps/customFormAction/components

2. Add the following property to the customFormAction node: 

  • sling:resourceType (String) - foundation/components/form/action
  • componentGroup (String ) - .hidden

3. Under customFormAction, create a file named post.POST.jsp. Add the following code. 

<%@include file="/libs/fd/af/components/guidesglobal.jsp" %>
<%@include file="/libs/foundation/global.jsp"%>
<%@page import="com.day.cq.wcm.foundation.forms.FormsHelper,
             org.apache.sling.api.resource.ResourceUtil,
             org.apache.sling.api.resource.ValueMap" %>
<%@taglib prefix="sling"
                uri="http://sling.apache.org/taglibs/sling/1.0" %>
<%@taglib prefix="cq"
                uri="http://www.day.com/taglibs/cq/1.0"
%>
<cq:defineObjects/>
<sling:defineObjects/>
<%
 
    String First = request.getParameter("First");
    String Last = request.getParameter("Last");
    String City = request.getParameter("City");
    String Address = request.getParameter("Address");

    com.adobe.cq.HandleForm hf = sling.getService(com.adobe.cq.HandleForm.class);
    hf.injestFormData(First,Last,City, Address);
 
 
%>

This code captures the posted form fields that are submitted from the AEM form. It then creates an instance of com.adobe.cq.HandleForm object. Finally it invokes the HandleForm object's injestFormData method and passes posted form values. 

4. Open the Form again in Edit view. Click on Form Start and click the wrench icon.In the dialog, click the Advanced Tab. Select customFormAction from the drop-down list.

The custom form action showing up in the Form Action drop-down

5. Click Ok. 

Submit the form data

The final step is to preview the Customer adaptive form. Open the Customer form in the AEM Form view:

http://localhost:4502/content/MyForm.html

Fill out the form fields and click the Submit button.

 

The Experience Manager form

Once you click the Submit button, the data is posted to the post.POST.jsp file. The post.POST.jsp invokes the HandleForm service by invoking its injestFormData method. This service logs the posted values to the AEM log file. You will see the following log message in the AEM log file.

com.adobe.cq.HandleFormImpl Data posted from the AEM EXAMPLE form - First: Scott Last: Macdonald City: Ottawa Address No Where Dr

Note:

As stated eariler in this article, you can implement application logic in the AEM backend Java service to process the data to meet your business needs. For example, you can persist the data in a relational database using a DataSourcePool. For details, see Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi bundle

See also

Join the AEM community at: Adobe Experience Manager Community

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy