Monday, March 25, 2013

Create Web Forms for Marketers Custom Save Action and Edit Screen

I was recently working on a project where I needed to create a custom save action to add to my Web Forms for Marketers module.  I needed a custom save action to push the data to salesforce and I also needed a custom edit screen so the author could setup some configuration values the action needed. Here are the details of what I did starting with the save action.

Save Action

The first thing you need to do is create a new class that inherits the “ISaveAction” interface (Sitecore.Form.Submit.ISaveAction) and implement the Execute method.

 
public class SalesforceSaveAction : ISaveAction
{
    public string FormKey { get; set; }
    public string FieldsToSend { get; set; }
 
    void ISaveAction.Execute(ID formid, AdaptedResultList fields, params object[] data)
    {
        // Code to execute here
    }
}

That is really all you need. Now it all becomes about custom code and configuration.  To configure the save action to show up you need to go to Modules –> WFM –> Settings –> Save action (master DB). Right click on save actions and select new save action. Give the item the name of the new save action you want to see in the list. In the assembly line put the name of the assembly your code shows up in, and in the Class put the name of the class with the namespace declaration. Don’t pay attention to the “Editor” section just yet. We will come back to that.

image

Once you have this step done you can now set up your save action via the form designer. Select the new action in the drop down and click add.

image

That is it. You now have a new custom save action. You can use the AdaptedResultList parameter object to access all the fields on the form and work with them. If all you want to do is work with the form values you are set. However, if you also need to allow the editor to provide some info to the action you need to also create an edit screen.  

Edit Screen

Creating and configuring the edit screen will make it so the “edit” button on the right will be enabled when you select your custom save action.  There are two parts to doing this. First you have to create the Sheer UI and then you have to create the code that Sheer UI calls. I started building this out from Sitecore’s “My First Sheer UI Application” example but found it only a somewhat helpful. Since I am not really creating an application it was not really addressing what I wanted to do. The XML section was helpful in understand what controls I can declare in the XML to create the UI. The first step is really just creating your XML file that holds that XAML that makes up your UI. I created a “SalesforceEditor.xml” file defined like this:

 
 
<?xml version="1.0" encoding="utf-8" ?>
<control xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense"
  xmlns:def="Definition"
  xmlns:asp="http://www.sitecore.net/microsoft/webcontrols">
  <SendToWebServiceSettings>
    <FormDialog ID="Dialog" Icon="Applications/32x32/gear.png"
      Header="Salesforce Web-to-Lead"
      Text="Define the OID for your Salesfoce form and define your mappings.">
      <CodeBeside Type="Web.Common.SalesforceWTLEditor,Web.Common"/>
      <GridPanel Class="scfContent" ID="MainGrid" Columns="2" Rows="5"
        Margin="20 25 25 15" Width="100%" Border="1">
 
        <Literal Text="Form Key:" GridPanel.Align="left" GridPanel.Column="0" GridPanel.Row="1"/>
        <Edit ID="FormKey" GridPanel.Column="1" GridPanel.Row="1"></Edit>
                
      </GridPanel>
    </FormDialog>
  </SendToWebServiceSettings>
</control>

All the fields are standard XAML controls. The key field to note is the “CodeBeside” element. This points the UI to where the codebeside file is that will execute against the XAML class. For our simple example we are just trying to create an edit screen that looks like this. This gives the editor a simple place to create an associated Salesforce key for each form they is generated.

image

Once we have the XML file we need to tell Sitecore about it. This happens in few places.

First you need to tell Sitecore about the layout you just created (the XML file). In the Sitecore “core” database you need to setup your page, under Sitecore –> layout –>layouts –> layouts, right click and add new item from template “/sitecore/templates/System/Layout/Xml layout.” Name it what you want and set the path to the actual physical location of where your xml file is.

Second, in the Sitecore “core” database you need to setup your page, under Sitecore –> content –> Applications –> Dialogs right click and add application.  Per the below picture give it a name and a icon. It can be whatever you want. Once this is done you want to go to the “presentation” ribbon and select the “Details” icon in the “layouts” section. Here you will select “edit” and select the Sitecore layout you created in the previous step.

imageimage

At this point you are done with the Sitecore configuration except for one thing. Earlier I told you about one field in the custom save action screen in Sitecore to ignore. Here is where it becomes meaningful. In the first image above there is a field called “editor.” By putting “control:SendToWebServiceSettings” we connect the edit button of the custom save action to our new Sheer UI edit screen. NOTE: The “SendToWebServiceSettings” is the name of our main node in the XML file.

Now the last thing. You need to create the code behind file that does all the processing of the XAML form.

Create a class that inherits from DialogForm

 
class SalesforceWTLEditor : DialogForm
{
   protected override void OnLoad(EventArgs e)
   {
       base.OnLoad(e);
       if (!Context.ClientPage.IsEvent)
       {
           // Execute your edit page onload code          
       }
   }
 
   protected override void OnOK(object sender, EventArgs args)
   {
        SheerResponse.SetDialogValue(
              ParametersUtil.NameValueCollectionToXml(new NameValueCollection() 
          { 
            {"FormKey", PersistentFormKeyValue },  
            {"FieldsToSend", string.Join(",", selectedFields)} 
          }));
 
 
            base.OnOK(sender, args);
   }
}

The Onload method, as you would expect, fires off when the form is opened. The OnOk is fired off when the user clicks the ok button at the button on the form.  I don’t have all my code here but I have listed the key parts. In the code behind you can access all the field IDs in your XAML. For example I can do MainGrid.Controls to get a list of all controls inside the GridPanel defined in my XML above. I have some SheerResponse code I am setting. This is the key code to setting information in the edit UI that can be accessed via your custom save action. You will note I am setting a NameValue collection for “FormKey” and “FieldsToSend.” The key and the values are just strings. If you take a look at the custom save action class at the top of the post you will see I set two public parameters of “FormKey” and “FieldsToSend.” The SheerResponse.SetDialogValue method pushes my name value collection to those properties. So when my save action fires off I can access FieldsToSend or FormKey and it has the string value of the namevalue collection.

7 comments:

nourestani said...

Hello,

How do you do the mapping, are you using webservice?

Mortaza

Todd said...

Mappings for what? I assume you are talking about mapping the field data to Salesforce and actually creating the Salesforce Web to Lead item? You can do it a few ways 1) Just use a rest call to the SF URL with your OID and SF field = value Query string. 2) Salesforce Webservice (requires username, password and token). I have done it both ways and both work great.

nourestani said...

Thank you for the reply.

I am more interested in the Webservice and meanwhile creating your forms in WFFM then I want to be able to do a mapping between the fields that i have created and the fields that are out there in SFDC. I am trying to implement this and if you could help and provide me anything, that would be great.

Thank you

Todd said...

You have a couple options. Hope this helps.
1- Post values to salesforce Web to Lead via Query string.
Create a URL like this. www.salesforce.com?oid=&retURL=&last_name=&first_name=

Note that "last_name" is the field name noted in the Salesforce Web To Lead. You can add as many of these as you want for each field in your form.

2- Use Salfesforce API
You will have to do a little digging for all your info. With a login to your SF instance you should be able to find where to download the WSDL for your strongly typed service. URL for the service is something like https://test.salesforce.com/services/Soap/c/27.0

Once you have all that you can do this.
SforceService service = new SforceService();
service.Url = Sitecore.Configuration.Settings.GetSetting("SalesforceURL");
LoginResult loginResults = service.login(Sitecore.Configuration.Settings.GetSetting("SalesforceUsername"), Sitecore.Configuration.Settings.GetSetting("SalesforcePWD"));

// the SF login returns the URL it wants us to post against.
service.Url = loginResults.serverUrl;
service.SessionHeaderValue = new SessionHeader();
service.SessionHeaderValue.sessionId = loginResults.sessionId;

Lead webToLead = new Lead()
{
FirstName = txtFirstName.Text,
LastName = txtLastName.Text,
Company = txtCompany.Text,
Email = txtEmail.Text,
Phone = txtTelephone.Text
}

SaveResult[] saveResults = service.create(new sObject[] { webToLead });


All this is documented by Salesforce as well. http://www.salesforce.com/us/developer/docs/api/index.htm

Hope that helps!

nourestani said...

Thank you so much and let me know if you need any help.

Mortaza

Umesh Wali said...

Good work!!

Anonymous said...

Nicely done.

https://woodenmask.wordpress.com/sitecore-wffm-customizing-send-mail-save-action/