Tuesday, 2 December 2014

Passing default values to data form add In

Blackbaud CRM 

In one of my project, I wanted to add a custom action “Add membership” in action group in left hand 
side, see below image






 If you see in above image, first thing to take the values from this OOB Opportunity page to my Add Membership form. First thing, I had made a expression view data form spec to get the fields from Opportunity page. The values which I needed to pass from this page to Add Membership Add In forms are mentioned below in a form of form field.

<common:FormMetaData>
    <common:FormFields>
      <common:FormField FieldID="PROSPECTID" Caption="Prospect Id" Description="Constituent ID" DataType="Guid"  />
      <common:FormField FieldID="RESPONSEDATE" Caption="Response Date" DataType="Date" Description="Opportunity Response Date"  />
      <common:FormField FieldID="MEMBERSHIPPROGRAM" Caption="Membership Program"  DataType="Guid" />
      <common:FormField FieldID="OPPORTUNITYLEVEL" Caption="Opportunity Level"  DataType="Guid" />
      <common:FormField FieldID="ASKAMOUNT" Caption="Ask Amount "  DataType="Money" />
    </common:FormFields>
  </common:FormMetaData>
  <AlterExistingPages xmlns="bb_appfx_pagedefinition">
    <AlterPages>
      <AlterPage PageID="8b97a047-e267-4e9f-822d-f74cbf1447e5">
        <AddPageExpressionForms>
          <PageExpressionForm DataFormInstanceID="87b33727-dcd1-4dfc-a4da-bad2440adcd3"/>
        </AddPageExpressionForms>
       </AlterPage>
    </AlterPages>
  </AlterExistingPages>
  <common:DataFormExtension DataFormInstanceID="fb0f139d-5242-4375-a579-fbb829e0515f"  RenderStyle="AfterParent" TabCaption="Parent Information" />

If we see in above lines, there are 5 fields included in the form fields which I wanted to pass into Add Membership form and after this I have added Alter existing page in which I have added this expression view data form into Opportunity page and also made this expression view data form as an extension of OOB expression view data form.


After this, next step is to pass these values in Membership Add form. So I used below mentioned code

<AlterPage PageID="8b97a047-e267-4e9f-822d-f74cbf1447e5">
        <AlterPageActionGroups>
          <AlterPageActionGroup PageActionGroupID="08ce3a00-5bc8-475e-bd68-5c5216993845">
            <AlterActions>
              <AddAction>
                <Action ID="14430078-F027-4E5E-8943-A89B24204768" Caption="Add membership" ImageKey="RES:newitem">
                  <common:ShowAddDataForm DataFormID="2852e35e-9b16-4f98-906c-51b7740e1ab4">
                    <common:PostActionEvent>
                      <common:GoToPage>
                        <common:SpecificPage PageID="51dec945-6a5f-4c40-ad4a-dc3ff36cddb4" />
                      </common:GoToPage>
                    </common:PostActionEvent>
                    <common:FormDefaultValues>
                      <common:DefaultValue FieldID="DATE">
                        <common:Value>
                          <common:PageExpressionField>RESPONSEDATE</common:PageExpressionField>
                        </common:Value>
                      </common:DefaultValue>
                      <common:DefaultValue FieldID="BILLTOCONSTITUENTID">
                        <common:Value>
                          <common:PageExpressionField>PROSPECTID</common:PageExpressionField>
                        </common:Value>
                      </common:DefaultValue>
                      <common:DefaultValue FieldID="MEMBERSHIPAMOUNT">
                        <common:Value>
                          <common:PageExpressionField>ASKAMOUNT</common:PageExpressionField>
                        </common:Value>
                      </common:DefaultValue>
                      <common:DefaultValue FieldID="COMMENTS">
                        <common:Value>
                          <common:PageContextID/>
                        </common:Value>
                      </common:DefaultValue>
                    </common:FormDefaultValues>
                  </common:ShowAddDataForm>
                </Action>
              </AddAction>
            </AlterActions>
          </AlterPageActionGroup>
        </AlterPageActionGroups>
      </AlterPage>


In above code, you could see that I have called showadddataform and this form is basically a Membership Add form data form instance id and using default value tags to pass the values. See yellow highlighted area above. I have used some fields from Membership add form like DATE field in Membership add form contains the RESPONSE DATE from opportunity expression view data form, also I passed PROPSECTID to membership add form into BILLTOCONSTITUENTID. I wanted to use similar field data type to pass the values.

Now its turn to discuss the Membership Add In spec, how these values receive at this level. So I made a Membership Add In spec.

<DataFormAddInSpec
       xmlns="bb_appfx_dataformaddin"
       xmlns:common="bb_appfx_commontypes"
       ID="39dfabf1-10d3-407f-961a-ddc9a4e9ca25"
       Name="Membership AddIn Custom"
       Description="An addin for the Membership Dues Add Data Form data form"
       Author="Blackbaud Professional Services"
       DataFormInstanceID="2852e35e-9b16-4f98-906c-51b7740e1ab4"
       >

       <DataFormAddIn AssemblyName="Blackbaud.CustomFx.EventCustomization.Catalog" ClassName="Blackbaud.CustomFx.EventCustomization.Catalog.MembershipAddIn" />

</DataFormAddInSpec>

In Add IN class, see the below code how I got these values.

'Add Membership form default values'
    'Mapping of DATE (Add Membership form) ---> RESPONSEDATEOpportunity page)
    'Mapping of BILLTOCONSTITUENTID(Add Membership form) ---> PROSPECTID(Opportunity page)
    'Mapping of MEMBERSHIPAMOUNT(Add Membership form) ---> ASKAMOUNT(Opportunity page)
    'Mapping of COMMENTS(Add Membership form) ---> ContextId (Opportunity page)
    Private Sub OnInit()
        ' Get Oppertunity Id from Comments field and set it on local variable opportunityId
        ' COMMENT field value set from default value tag and PageContextID set in COMMENT Field
        'which is on Opportunity page

        If Me.COMMENTS.Value <> String.Empty Then
            opportunityId = Guid.Parse(Me.COMMENTS.Value)
            Me.COMMENTS.Value = String.Empty
        End If
        LoadTrackField()
        If (Me.BILLTOCONSTITUENTID.Value <> Guid.Empty) Then
            LoadProgramAndLevel()
        End If

        'This method is called when the UI model is created to allow any initialization to be performed.
    End Sub


If we see above code, we found that based on Membership Add form fields, some business logic implemented. Please see the comments also in green above code snippet. So everything has been done on OnInit event.

For saving the data from Add In , I used below mentioned code

Private Sub MODEL_Saved(sender As Object, e As AppFx.UIModeling.Core.SavedEventArgs) Handles MODEL.Saved
        ' now we should save our custom field value to the database
        ' use Me.MODEL.GetRequestContext to send a request via theappfx
        ' web service to save our dataform extension
        If Me.TRACKTYPECODEID.Visible = True Then
            Dim connection = Me.MODEL.GetRequestContext().OpenAppDBConnection
            'Insert Comp Track Type code under Opportunity Id'
            USR_USP_INSERTMEMBERSHIPTRACKCODE.ExecuteNonQuery(connection, opportunityId, New Guid(Me.MODEL.RecordId), Me.TRACKTYPECODEID.Value, Me.TRACKCOMMENTS.Value)
        End If

    End Sub

    Private Sub MODEL_Saving(sender As Object, e As AppFx.UIModeling.Core.SavingEventArgs) Handles MODEL.Saving
        ' when the form is saving the field we added to the
        ' fields collection will raise an error as it does
        ' not exist in the form definition
        ' let's move the field value to a variable
        Try
            Me._tracktypecodeid.Value = Me.MODEL.Fields("TRACKTYPECODEID").ValueObject
            Me._trackcomments.Value = Me.MODEL.Fields("TRACKCOMMENTS").ValueObject
            ' now remove the field from the fields collection to
            ' prevent field not in form definition error message
            If (Not e.Cancel) Then
                Me.MODEL.Fields.Remove("TRACKTYPECODEID")
                Me.MODEL.Fields.Remove("TRACKCOMMENTS")
            End If
        Catch ex As Exception

        End Try


    End Sub

We would use “Model_Saved” event to save the data into the database, means after normal execution of Membership add form then it will enter into Saved event and we can manage our save criteria.


How to set the field properties dynamically when opening any batch

Blackbaud CRM 

To set the batch field properties dynamically when loading any batch, we need to use AfterLoad event of batch entry handler. Please see the below code snippet

Private Sub BatchCommitmentUpdateHandler_AfterLoad(sender As Object, e As EventArgs) Handles Me.AfterLoad
        With Me.FieldChangedHandlers
            'Disable fields if STATUSCODE is Unqualified
            If DirectCast(Me.DefaultFields, Blackbaud.AppFx.UIModeling.Core.UIModelFieldCollection).Item("STATUSCODE").ValueObject.ToString() = "0" Then
                DirectCast(Me.DefaultFields, Blackbaud.AppFx.UIModeling.Core.UIModelFieldCollection).Item("ASKDATE").Enabled = False
                DirectCast(Me.DefaultFields, Blackbaud.AppFx.UIModeling.Core.UIModelFieldCollection).Item("RESPONSEDATE").Enabled = False
                DirectCast(Me.DefaultFields, Blackbaud.AppFx.UIModeling.Core.UIModelFieldCollection).Item("ASKAMOUNT").Enabled = False
            End If

        End With
    End Sub

If you see  above code , I have added a condition that when Status code = “0” then all the below mentioned 3 fields are enable. So we can get the field from “Me” object rather than “e” .

Set the value into the batch model in web event handler

Blackbaud CRM 

I have a scenario that using web event handler, I just made a batch extension for “Revenue Update Batch” . In this batch. If we select REVENUE form search list then it will capture the extension field from data base and set the data into the batch. So for this, see below lines

Private Sub BatchCommitmentUpdateHandler_AfterLoad(sender As Object, e As EventArgs) Handles Me.AfterLoad
        With Me.FieldChangedHandlers
            If FieldIsDefined("REVENUEID") Then
                .Add("REVENUEID", AddressOf GetBenefitDetails)
            End If
        End With
    End Sub


Private Sub GetBenefitDetails(ByVal e As FieldEventArgBase)

        Dim ID = DirectCast(GetValueFromFieldID(e.Model, e.Field.Name, Guid.Empty), Guid)

        If ID.Equals(Guid.Empty) Then Return
        Dim request As New DataFormLoadRequest() With { _
          .FormID = New System.Guid(DATAFORMID_VIEWBENEFITINFO), _
          .RecordID = ID.ToString, _
          .IncludeMetaData = True}

        Dim reply As DataFormLoadReply = Nothing
        Try
            ' DataFormLoad is called to retrieve data from a feature represented by DATAFORMID_FOODITEMINFO. 
            reply = Blackbaud.AppFx.Server.DataFormLoad(request, Me.RequestContext)
        Catch ex As ServiceException When _
                ex.DataFormErrorInfo IsNot Nothing AndAlso _
                ex.DataFormErrorInfo.ErrorCode = DataFormErrorCode.RecordNotFound
            ' The food item doesn't exist
            Return
        End Try
        Dim processedRows As Generic.List(Of Blackbaud.AppFx.XmlTypes.DataForms.DataFormItem)
        Dim collectionValue As New Blackbaud.AppFx.XmlTypes.DataForms.DataFormItem
        If reply Is Nothing Then Return
        Using BatchGridRowUIModel.CreateChangeSuppressor(e.Model)
            '  Once the data is retrieved, the DataFormItem object, which represents the data payload retrieved
            '  from the database, is used within a call to TrySetValuesFromDFI which sets the matching form fields
            '  from the DataFormItem to the batch row. 
            '  The batch row is represented by e.Model.

          Dim benefitList = DirectCast(reply.DataFormItem.Values, Blackbaud.AppFx.XmlTypes.DataForms.DataFormFieldValueSet)
            TrySetValueForFieldID(e.Model, "PROJECTNAME", benefitList.Item("PROJECTNAME").Value)

            Dim benefitArray = DirectCast(benefitList.Item("BENEFITS").Value, Blackbaud.AppFx.XmlTypes.DataForms.DataFormItemArrayValue)
            If benefitArray IsNot Nothing Then
                processedRows = New Generic.List(Of Blackbaud.AppFx.XmlTypes.DataForms.DataFormItem)
                For Each row As Blackbaud.AppFx.XmlTypes.DataForms.DataFormItem In benefitArray.Items
                    collectionValue = New Blackbaud.AppFx.XmlTypes.DataForms.DataFormItem
                    collectionValue.Values.Add("ID", row.Values("ID").Value)
                    collectionValue.Values.Add("BENEFITID", row.Values("BENEFITID").Value)
                    collectionValue.Values.Add("QUANTITY", row.Values("QUANTITY").Value)
                    collectionValue.Values.Add("UNITVALUE", row.Values("UNITVALUE").Value)
                    collectionValue.Values.Add("TOTALVALUE", row.Values("TOTALVALUE").Value)
                    collectionValue.Values.Add("DETAILS", row.Values("DETAILS").Value)
                    collectionValue.Values.Add("SEQUENCE", row.Values("SEQUENCE").Value)
                    collectionValue.Values.Add("TRANSACTIONTOTALVALUE", row.Values("TRANSACTIONTOTALVALUE").Value)
                    collectionValue.Values.Add("BENEFITCURRENCYID", row.Values("BENEFITCURRENCYID").Value)
                    collectionValue.Values.Add("TRANSACTIONCURRENCYID", row.Values("TRANSACTIONCURRENCYID").Value)
                    collectionValue.Values.Add("BASECURRENCYID", row.Values("BASECURRENCYID").Value)
                    processedRows.Add(collectionValue)
                Next
                Dim dataFormItemArrayValue As New Blackbaud.AppFx.XmlTypes.DataForms.DataFormItemArrayValue(processedRows.ToArray)
                Dim dataFormItemValue As New Blackbaud.AppFx.XmlTypes.DataForms.DataFormFieldValue("BENEFITS", dataFormItemArrayValue)
                TrySetValueForFieldID(e.Model, "BENEFITS", dataFormItemValue.Value)
            End If


In above code you would see that after changing REVENUEID, it will cause a handler to invoke and calling any Viewdataform taking REVENUE ID and fetches the extension fields and then it will start to set the standalone field like in above yellow highlighted area . If there will be any collection field then it will use green highlighted area . In this way we can set values in batch model .

Register event for Collection field in web event handler

Blackbaud CRM 

In last post I have mentioned how to register any event for any field in web event handler. I have a scenario to play with collection fields. I have 5 fields in single collection. And for instance, if I change 3rd field and based on this field change other field will have an impact . So in this case I need to register an event which will handle this. See below lines
Private Sub BatchCommitmentUpdateHandler_AfterLoad(sender As Object, e As EventArgs) Handles Me.AfterLoad
        With Me.FieldChangedHandlers
            '' If Commitment lookup id is selected then it will get the commitment details from the DATAFORMID_COMMITMETINFO
            ''form and load all single values along with the collection values
If FieldIsDefined("XMLSTANDARDMETRIC") Then .Add("XMLSTANDARDMETRIC\AMOUNT", AddressOf StandardMetricAmountValidation)        End With
    End Sub

Private Sub StandardMetricAmountValidation (ByVal e As FieldEventArgBase)
‘ Implement the custom logic here
End Sub

Now, whenever user will change 3rd field which is AMOUNT column in collection “XMLSTANDARDMETRIC” then it will enter into the method “StandardMetricAmountValidation” and in this method we can use custom implementation.



Add Events for form field on web event handler

Blackbaud CRM 

I have made a web event handler, in this web event handler, i need to grab the event of any field. For instance if use “Enhance Event Handler” . In this event handler, I want to change any field value or want to do any sort of change whether to select data from database, anything I want then the first question arises in my mind how I can handle the vent handler. See below lines taken from web event handler

Private Sub BatchCommitmentUpdateHandler_AfterLoad(sender As Object, e As EventArgs) Handles Me.AfterLoad
        With Me.FieldChangedHandlers
            '' If Commitment lookup id is selected then it will get the commitment details from the DATAFORMID_COMMITMETINFO
            ''form and load all single values along with the collection values
            If FieldIsDefined("CONSTITUENTID") Then
                .Add("PRIMARYRECORDID", AddressOf GetConstituentExtensionData)
            End If
        End With
    End Sub

Private Sub GetConstituentExtensionData (ByVal e As FieldEventArgBase)
‘ Implement the custom logic here
End Sub

Now if you debug the batch event handler whenever you change any constituent, it will push the implementation into the “GetConstituentExtensionData” method. And in this method you can do anything you want.
There is another event “CellChanged” event in web event handler, using this event, you can also accomplish this thing but according to it will cause extra overhead on implementation because this event will trigger when user will change any event and check for every field. So the best way to define the event in webevent handler is the above one.