Populating the "Discount" Field in Gravity Forms

31 views Asked by At

I have a discount field in about 40 forms created on my site, and 10 user roles.

Initially, I had to set 10 discount fields based on the current user role... But I think I should be able to do it better.

So, I created an admin option for all of the user roles, and then decided to have just one single discount field in each form, that will be populated based on the role of the user viewing the form.

My problem now is how to populate that discount field with the value I have set in the admin option.

Here is my try;



?php

// Define the mapping of form IDs to product types and discount field IDs

$form_mappings = [

    4 => ['product_type' => 'vtu', 'discount_field_id' => 10],

    // Add more mappings for other form scenarios

];

// Get the current user's role

$current_user = wp_get_current_user();

$user_role = $current_user->roles[0];

?>

<script>

    jQuery(document).ready(function($) {

        // Function to calculate and set the discount value

        function setDiscountValue(formId) {

            // Get the mapping for the current form ID

            var mapping = <?php echo json_encode($form_mappings); ?>;

            var currentMapping = mapping[formId];

            // Check if the mapping exists for the current form ID

            if (currentMapping) {

                var productType = currentMapping.product_type;

                var discountFieldId = currentMapping.discount_field_id;

                // Retrieve the discount value based on user role and product type

                var discountSettings = <?php echo json_encode($discount_settings); ?>; // Make sure to set $discount_settings in your PHP code

                var discountValue = discountSettings[userRole][productType] || 0;

                // Set the calculated discount value to the field with the specified ID

                $('#' + discountFieldId).val(discountValue);

            }

        }

        // Loop through each form mapping and set discount values

        $.each(<?php echo json_encode($form_mappings); ?>, function(formId) {

            // Check if the form exists on the page

            if ($('#form-' + formId).length > 0) {

                // Call the function to set the discount value for each form

                setDiscountValue(formId);

                // Optionally, you can bind this to a form event like submit

                $('#form-' + formId).on('submit', function() {

                    // Call the function to set the discount value before submitting the form

                    setDiscountValue(formId);

                });

            }

        });

    });

</script>
0

There are 0 answers