使用Analytics跟踪AJAX表单提交

时间:2018-09-21 16:51:48

标签: forms google-analytics google-tag-manager dynamic-forms

所以这是我花了无数个小时试图弄清楚的一个...

我正在在force.com上建立的网站上工作,需要使用分析跟踪表单提交。唯一的问题是表单是动态的,只是为您提供一个弹出对话框进行确认。

关于如何为此页面实现跟踪表单提交,我最好的选择是什么?

({
    doInit: function(component, event, helper) {
        // Prepare a new record from template
        component.find("leadRecordCreator").getNewRecord(
            "Lead", // sObject type (entityApiName)
            null, // recordTypeId
            false, // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.newLead");
                var error = component.get("v.newLeadError");
                if (error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                    return;
                }
                
                component.set("v.simpleNewLead.LeadSource", "GreenLight Interest");
            })
        );
    },
    handleSaveLead: function(component, event, helper) {
                                // Get and set zipcode value
        var zipCodeInput = component.get("v.zipcode");
        if (zipCodeInput) {
                        component.set("v.simpleNewLead.PostalCode", zipCodeInput.toString());
        }

        var errorMessage = 'Complete this field.';
        var isValidEmail = true; 
        var emailField = component.find("leadEmail");
        var emailFieldValue = emailField.get("v.value");
        var regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;  
        
        // Validate email field
        if(emailFieldValue){   
            if(emailFieldValue.match(regExpEmailformat)){
                emailField.set("v.errors", [{message: null}]);
                $A.util.removeClass(emailField, 'error');
                $A.util.addClass(emailField, 'inputBorder');
                isValidEmail = true;
            }else{
                $A.util.addClass(emailField, "error");
                $A.util.removeClass(emailField, 'inputBorder');
                emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);
                isValidEmail = false;
            }
        }else{
            $A.util.addClass(emailField, "error");
            $A.util.removeClass(emailField, 'inputBorder');
            emailField.set("v.errors", [{message: errorMessage}]);
            isValidEmail = false;
        }
        if (
            component.get("v.simpleNewLead").FirstName &&
            component.get("v.simpleNewLead").LastName &&
            component.get("v.simpleNewLead").Email &&
            component.get("v.simpleNewLead").MobilePhone &&
            component.get("v.simpleNewLead").Company &&
            component.get("v.simpleNewLead").PostalCode &&
            component.get("v.simpleNewLead").PostalCode.length >= 5
        ) {
            component.find("leadRecordCreator").saveRecord(function(saveResult) {
                if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                    $A.get('e.force:refreshView').fire();

                    // Display success message
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        title: "Success!",
                        message: 'Thank you.',
                        key: 'info_alt',
                        type: 'success'
                    });
                    toastEvent.fire();                    
                } else if (saveResult.state === "INCOMPLETE") {
                    // handle the incomplete state
                    console.log("User is offline, device doesn't support drafts.");
                } else if (saveResult.state === "ERROR") {
                    // handle the error state
                    console.log('Problem saving contact, error: ' +JSON.stringify(saveResult.error));
                } else {
                    console.log('Unknown problem, state: ' + saveResult.state + ',error: ' + JSON.stringify(saveResult.error));
                }
            });
        } else {
            // Add required field error for zip code field. If blank
            if (!zipCodeInput) { 
                var zip = component.find("zip");
                zip.set("v.errors", [{message: errorMessage}]);
                $A.util.removeClass(zip, "inputBorder");
                $A.util.addClass(zip, "error");
            }

            // Add required field error for other field. If blank
                                                var leadFields = component.find("leadField");
            var i = 0;
            for (i = 0; i < leadFields.length; i++) {
                var value = leadFields[i].get("v.value");
                if(value){
                    $A.util.removeClass(leadFields[i], "error");
                    $A.util.addClass(leadFields[i], "inputBorder");
                    leadFields[i].set("v.errors", []);
                }else{
                    leadFields[i].set("v.errors", [{message: errorMessage}]);
                    $A.util.removeClass(leadFields[i], "inputBorder");
                    $A.util.addClass(leadFields[i], "error");
                }
            }
        }
    },
    
    handleZipChange : function(component, event, helper) {
        // Validate zip code field lenght. Must be equal to or greator than 5
        helper.removeErrorMessage(component, event, "zip");
        var zip = component.find("zip");
        var zipInput = component.get("v.zipcode");
        console.log('zipInput>>>'+zipInput);
        var regPostalCode = /^[0-9]*$/gm; 
        var isNum = regPostalCode.test(component.get("v.zipcode"));
        var islessthan5digit = (component.get("v.zipcode").length < 5);
        console.log('isNum>>'+isNum);
        console.log('islessthan5digit>>'+islessthan5digit);
        
        if(!isNum || islessthan5digit) {
            zip.set("v.errors", [{message: "Zip Code should be 5 digits"}]);
            $A.util.removeClass(zip, "inputBorder");
            $A.util.addClass(zip, "error");
        }
        else{
            console.log('in else>>'); 
        }
    },
})
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:attribute name="newLead" type="Object"/>
    <aura:attribute name="simpleNewLead" type="Object"/>
    <aura:attribute name="newLeadError" type="String"/>
    <aura:attribute name="zipcode" type="Integer" />

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <force:recordData aura:id="leadRecordCreator"
                      fields="FirstName, LastName, Email, MobilePhone, PostalCode, Company"
                      targetRecord="{!v.newLead}"
                      targetFields="{!v.simpleNewLead}"
                      targetError="{!v.newLeadError}" />
    
    <!-- Display a header -->
    <div class="slds-box">
        
        <!-- Display Lightning Data Service errors -->
        <aura:if isTrue="{!not(empty(v.newLeadError))}">
            <div class="recordError">
                <ui:message title="Error" severity="error" closable="true">
                    {!v.newLeadError}
                </ui:message>
            </div>
        </aura:if>
        
        <!-- Display the new lead form -->
        <div class="slds-form--stacked slds-box">
            <div class="slds-grid slds-gutters slds-align_absolute-center">
                <div class="slds-col">
                    <div class="slds-form slds-form_horizontal slds-size--9-of-12 ">
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">First Name</label>
                            <div class="slds-form-element__control">
                                <ui:inputText aura:id="leadField" value="{!v.simpleNewLead.FirstName}" class="inputBorder"/>
                            </div>
                        </div>
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">Last Name</label>
                            <div class="slds-form-element__control">
                                <ui:inputText aura:id="leadField" value="{!v.simpleNewLead.LastName}" class="inputBorder"/>
                            </div>
                        </div>
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">Email</label>
                            <div class="slds-form-element__control slds-size--12-of-12">
                                <ui:inputEmail aura:id="leadEmail" value="{!v.simpleNewLead.Email}" class="inputBorder"/>
                            </div>
                        </div>
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">Phone</label>
                            <div class="slds-form-element__control">
                                <ui:inputPhone aura:id="leadField" value="{!v.simpleNewLead.MobilePhone}" class="inputBorder"/>
                            </div>
                        </div>
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">Zip Code</label>
                            <div class="slds-form-element__control">
                                <!--<ui:inputText aura:id="leadField" value="{!v.simpleNewLead.PostalCode}" class="inputBorder"/>-->
                                <!-- <ui:inputNumber  aura:id="zip" value="{!v.zipcode}" class="inputBorder" change="{!c.handleZipChange}" format="#####"/> -->
                                <ui:inputText  aura:id="zip" value="{!v.zipcode}" class="inputBorder" change="{!c.handleZipChange}" />
                            </div>
                        </div>
                        <div class="slds-form-element">
                            <label class="slds-form-element__label" for="input-id-01">Company</label>
                            <div class="slds-form-element__control">
                                <ui:inputText aura:id="leadField" value="{!v.simpleNewLead.Company}" class="inputBorder"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <lightning:button label="Submit" onclick="{!c.handleSaveLead}" variant="brand" class="slds-m-top--medium slds-align_absolute-center"/>
        </div>
    </div>
</aura:component>

1 个答案:

答案 0 :(得分:0)

因为您可以控制代码,所以最简单的选择可能是将事件(如果需要,还可以添加其他数据)推送到ajax调用的成功回调中。如果我正确阅读了代码,则将其放在saveResult.state === "SUCCESS"开头的if句中,并将其修改为:

    ...
    if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                        $A.get('e.force:refreshView').fire();

                        // Display success message
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            title: "Success!",
                            message: 'Thank you.',
                            key: 'info_alt',
                            type: 'success'
                        });
                        toastEvent.fire();   
                        dataLayer.push({'event':'ajaxSuccess'})                 
                    } 
...

dataLayer.push({'event':'ajaxSuccess'})行意味着您现在拥有一个可在触发器中使用的GTM事件。这种工作方式是GTM覆盖dataLayer数组的“ push”方法,以添加一个函数来扫描新附加的对象中的“事件”键,更新GTM的内部数据模型,然后使用该触发器触发所有具有触发器的标签事件。

同样,如果验证失败,您可以添加错误事件,或者向数据层推送添加其他键/值对,以在GTM中获取其他变量。