MdMasud

WordPress, Laravel, Flutter

Tag: Gravity Form

  • How to Disable Weekends, Specific Dates and Use Date Ranges in Gravity Forms

    How to Disable Weekends, Specific Dates and Use Date Ranges in Gravity Forms

    If you have used a Gravity Forms Date field and wanted to block weekends, disable certain dates, or only allow a selected range of dates, you may have found the official documentation a bit limiting.

    Gravity Forms provides examples for each of these individually, but not how to combine them. In this post, I’ll show you how to do just that, with clear examples and a complete working script.

    Step 1: Use the gform_datepicker_options_pre_init filter

    This Gravity Forms filter allows you to customise the jQuery UI Datepicker used by date fields. You need to target your form ID and field ID:

    gform.addFilter('gform_datepicker_options_pre_init', function(optionsObj, formId, fieldId) {
      // Your logic goes here
      return optionsObj;
    });

    Step 2: Define your allowed date ranges

    We’ll define specific ranges during which dates should be selectable.

    var ranges = [
      { start: new Date('09/25/2025'), end: new Date('10/05/2025') },
      { start: new Date('11/10/2025'), end: new Date('11/20/2025') }
    ];

    Step 3: Disable specific dates

    You may want to block specific public holidays or unavailable days. Format these as dd/mm/yyyy.

    var disabledDays = [
      '26/09/2025',
      '29/09/2025',
      '25/12/2025',
      '01/01/2026',
      '05/01/2026'
    ];

    Step 4: Disable weekends

    Gravity Forms uses jQuery UI Datepicker under the hood, which includes a built-in function to block weekends:

    var noWeekend = jQuery.datepicker.noWeekends(date);
    if (!noWeekend[0]) return noWeekend;

    Step 5: Combine all conditions in a single function

    Full Working Example

    Here is the complete code including form and field checks:

    gform.addFilter('gform_datepicker_options_pre_init', function(optionsObj, formId, fieldId) {
      if (formId == 12 && fieldId == 16) {
    
        var ranges = [
          { start: new Date('09/25/2025'), end: new Date('10/05/2025') },
          { start: new Date('11/10/2025'), end: new Date('11/20/2025') }
        ];
    
        var disabledDays = [
          '26/09/2025',
          '29/09/2025',
          '25/12/2025',
          '01/01/2026',
          '05/01/2026'
        ];
    
        optionsObj.minDate = ranges[0].start;
        optionsObj.maxDate = ranges[ranges.length - 1].end;
        optionsObj.firstDay = 1;
    
        optionsObj.beforeShowDay = function(date) {
          var inRange = ranges.some(function(range) {
            return date >= range.start && date <= range.end;
          });
          if (!inRange) return [false];
    
          var noWeekend = jQuery.datepicker.noWeekends(date);
          if (!noWeekend[0]) return noWeekend;
    
          var formatted = ('0' + date.getDate()).slice(-2) + '/' +
                          ('0' + (date.getMonth() + 1)).slice(-2) + '/' +
                          date.getFullYear();
    
          if (disabledDays.indexOf(formatted) !== -1) return [false];
    
          return [true];
        };
      }
    
      return optionsObj;
    });

    Optional: Hide Dates from Other Months

    By default, the datepicker shows days from the previous and next months to fill out the calendar grid. To hide those days for a cleaner look, you can use the following CSS:

    .ui-datepicker td.ui-datepicker-other-month {
      visibility: hidden;
    }

    This hides the content but keeps the grid layout intact. If you prefer to completely remove those cells, you can use display: none, but it may affect layout consistency.

    Wrapping Up

    Gravity Forms makes it easy to add date pickers, but combining rules for weekends, specific dates, and ranges requires a bit of manual work. With the example above, you now have full control over which dates can be selected in your form.

    If you’re working on a more complex booking or survey system, this kind of control can be essential.

  • How I Automatically Routed Service Requests to the Right Branch in WordPress Using Gravity Forms, ACF, and Postcode Matching

    How I Automatically Routed Service Requests to the Right Branch in WordPress Using Gravity Forms, ACF, and Postcode Matching

    One of the most rewarding things about working with WordPress is finding elegant ways to connect the front end with real-world business logic. Recently, I built a feature for a client that automatically routes customer service requests to the correct branch of the company — based entirely on the postcode entered in a Gravity Form.

    Here’s a breakdown of how I did it using Gravity Forms, Advanced Custom Fields (ACF), and some clean PHP logic.

    The Problem: Which Branch Covers This Area?

    The client has multiple branches across the UK, each covering a specific set of postcode areas — like EH12, AB10, G1, etc. When a customer submits a service request through the form on their website, the business needs that request to be automatically forwarded to the branch responsible for that postcode.

    Manual routing wasn’t an option. It had to be smart, scalable, and easy to manage.

    The Stack

    • WordPress (custom theme)
    • Gravity Forms for form handling
    • Advanced Custom Fields (ACF) to attach postcode coverage info to taxonomy terms
    • Custom PHP logic to handle the postcode matching and data routing

    The Data Structure

    Each branch is stored as a custom taxonomy term (location) in WordPress. Each term has an ACF repeater field called postcode_area_coverage, and inside that repeater, a subfield named code holds the outward postcode areas like EH12, G1, AB10.

    So the structure looks like this:

    location (taxonomy term)
    └── postcode_area_coverage (repeater)
    ├── code: EH1
    ├── code: EH2
    └── code: EH12

    The Gravity Form

    The form collects the usual user details, including a postcode field. Behind the scenes, I validate the format of the postcode, extract the outward part (everything before the space), and match it against the postcode coverage of each branch.

    Once matched, I automatically store the matched branch in a hidden Gravity Forms field. That field can then be used to:

    • Route notifications
    • Display confirmation messages
    • Track analytics

    Extracting the Outward Code from a Full Postcode

    if (preg_match('/^([A-Z]{1,2}[0-9][0-9A-Z]?)/', strtoupper(trim($postcode)), $matches)) {
        $outward = $matches[1]; // e.g. "EH12" from "EH12 5AB"
    }

    This snippet takes the full UK postcode submitted in the form and extracts the outward code (first part). That’s what I use to match against each branch’s coverage.

    Matching the Postcode to a Branch via ACF Repeater

    $terms = get_terms(['taxonomy' => 'location', 'hide_empty' => false]);
    foreach ($terms as $term) {
        $coverage = get_field('postcode_area_coverage', 'location_' . $term->term_id);
        foreach ($coverage as $row) {
            if (strtoupper($row['code']) === $outward) {
                return $term->term_id; // Match found
            }
        }
    }

    Here, I loop through each location taxonomy term, check their ACF postcode coverage, and find a match with the user’s outward postcode. Once matched, I return that branch’s ID.

    Updating a Gravity Form Field After Submission

    GFAPI::update_entry_field($entry['id'], self::LOCATION_SELECTED_FROM_POSTCODE, $branch_id);

    After finding the correct branch, I updated a hidden field in the submitted Gravity Form entry so it stores which branch should handle the request. This value is later used to route notifications.

    At the End

    • The business now handles customer requests faster and more efficiently.
    • Postcode coverage can be updated by non-technical users directly in the WordPress admin.
    • The system is scalable — just add a new location with postcode areas, and it’s instantly supported.

    It’s always fun to bridge the gap between user input and smart business logic. This was a great example of how custom taxonomy, ACF, and Gravity Forms can work together to create something genuinely useful — with no need for heavyweight plugins or complex integrations.

  • How to Keep Dropdown Submenu Open After Gravity Form AJAX Submit

    While working on a WordPress site, I embedded a Gravity Form inside a dropdown submenu of the navigation menu. The submenu appears on hover, and inside it, users can submit an enquiry form via Gravity Forms using AJAX.

    Everything worked fine, until the form was successfully submitted.

    Good : If validation failed, the form stayed open and errors were visible.

    Bad : But when the form successfully submitted, the confirmation message would briefly flash — and the submenu would immediately disappear, making it look like nothing happened.

    This wasn’t a great user experience, especially if users didn’t realise their form had gone through.

    Why It Happens

    When Gravity Forms submits via AJAX, it dynamically replaces the form’s content with the confirmation message. This causes a DOM update that disrupts the hover state of the submenu, especially if it’s tied to :hover CSS.

    So, the submenu disappears — not because of an error, but because the browser no longer sees the user as “hovering” during or right after the form update.

    The Solution

    The fix is to manually reapply a class to keep the submenu open when the form is successfully submitted, then remove that class when the user moves the mouse away.

    You don’t need any complex JavaScript frameworks — just a few lines of jQuery and a little CSS.

    jQuery(document).ready(function($) {
     var menuItem = $('#menu-item-1798'); // ID of the parent menu item
    
     // When the form is successfully submitted via AJAX
     $(document).on('gform_confirmation_loaded', function(event, formId) {
      if (formId === 5) { // Replace with your actual form ID
       menuItem.addClass('keep-open');
      }
     });
    
     // When user moves their mouse out of the menu item, close it
     menuItem.on('mouseleave', function() {
      if (menuItem.hasClass('keep-open')) {
       menuItem.removeClass('keep-open');
      }
     });
    });

    Optional CSS

    Add proper style to your stylesheet to ensure the menu stays visible when the keep-open class is active.

    The Output

    With this small enhancement:

    • The submenu remains open after a successful Gravity Form submission.
    • Users can clearly see the confirmation message.
    • The menu closes cleanly once the user moves away.

     It works beautifully without any plugin overhead or redesigns.

    Have you run into a similar problem? Got a cleaner approach ? Drop your thoughts in the comments!