Skip to main content

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.

Comments

Anonymous 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.
Anonymous 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!
Anonymous said…
Thank you so much and let me know if you need any help.

Mortaza
Anonymous said…
Nicely done.

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

Popular posts from this blog

Experience Profile Anonymous, Unknown and Known contacts

When you first get started with Sitecore's experience profile the reporting for contacts can cause a little confusion. There are 3 terms that are thrown around, 1) Anonymous 2) Unknown 3) Known. When you read the docs they can bleed into each other a little. First, have a read through the Sitecore tracking documentation to get a feel for what Sitecore is trying to do. There are a couple key things here to first understand: Unless you call " IdentifyAs() " for request the contact is always anonymous.  Tracking of anonymous contacts is off by default.  Even if you call "IdentifyAs()" if you don't set facet values for the contact (like first name and email) the contact will still show up in your experience profile as "unknown" (because it has no facet data to display).  Enabled Anonymous contacts Notice in the picture I have two contacts marked in a red box. Those are my "known" contacts that I called "IdentifyAs"

Excel XIRR and C#

I have spend that last couple days trying to figure out how to run and Excel XIRR function in a C# application. This process has been more painful that I thought it would have been when started. To save others (or myself the pain in the future if I have to do it again) I thought I would right a post about this (as post about XIRR in C# have been hard to come by). Lets start with the easy part first. In order to make this call you need to use the Microsoft.Office.Interop.Excel dll. When you use this dll take note of what version of the dll you are using. If you are using a version less then 12 (at the time of this writing 12 was the highest version) you will not have an XIRR function call. This does not mean you cannot still do XIRR though. As of version 12 (a.k.a Office 2007) the XIRR function is a built in function to Excel. Prior version need an add-in to use this function. Even if you have version 12 of the interop though it does not mean you will be able to use the function. The

Uniting Testing Expression Predicate with Moq

I recently was setting up a repository in a project with an interface on all repositories that took a predicate. As part of this I needed to mock out this call so I could unit test my code. The vast majority of samples out there for mocking an expression predicate just is It.IsAny<> which is not very helpful as it does not test anything other then verify it got a predicate. What if you actually want to test that you got a certain predicate though? It is actually pretty easy to do but not very straight forward. Here is what you do for the It.IsAny<> approach in case someone is looking for that. this .bindingRepository.Setup(c => c.Get(It.IsAny<Expression<Func<UserBinding, bool >>>())) .Returns( new List<UserBinding>() { defaultBinding }.AsQueryable()); This example just says to always return a collection of UserBindings that contain “defaultBinding” (which is an object I setup previously). Here is what it looks like when you want to pass in an exp

Security Config in IIS Express

I have gotten tired of always having to look this up or remember where it is at. That means it is time to post to my blog so I can find it easier and hopefully others can too. If you are having issues with IIS Express authentication errors (like the Unauthorized 401.2 error I always get) here is some help. I can never remember what the last setting was I had IIS Express set to for authorization. To change IIS Express for windows auth or anonymous auth you want to work with the applicationhost.config file. It can be found here …Documents\IISExpress\config. You want to change the settings in the following area of the config file. < authentication > < anonymousAuthentication enabled ="true" userName ="" /> < basicAuthentication enabled ="false" /> < clientCertificateMappingAuthentication enabled ="false" /> < digestAuthentication enabled ="false" />

WPF Localization - RESX Option

About a year ago I was building a WPF project in .Net 3.0 and Visual Studio 2005. I wanted to revisit this subject and see what has changed in .Net 3.5 and Visual Studio 2008. I will make a few of these posts to try and cover all the different options (RESX option, LocBaml option, Resource Dictionary Option). In this blog I will focus on using a resx file to localize an application. To show how the resx option is done I created a WPF form with three labels on it. The first label has is text set inline in XAML, the second has it text set via code behind from the resx file and the third has its text set via XAML accessing the resx file. The first thing that needs to happen to setup a project for localization is a small change to the project file. To make this change you will need to open the project file in notepad (or some other generic editor). In the first PropertyGroup section you need to add the follow XML node <UICulture>en-US</UICulture>. So the project file node w