Page 1 of 1

Appgini: Pass default values for form fields from URL parameters

Posted: 2023-07-29 16:42
by rngoda
Hi all,
If you are looking for solution on how to pass default values to a form field from specific URL parameters, this is a perfect hack for you in pure JS.

I had a situation where a visitor can click a product link that redirects to a contact form. I would like to pass value via link to a field on that form, so he/she don't have to enter this choice again. This by default is not supported by Appgini, Appgini currently supports the option for filterer_fieldname which is used for non autofill lookup fields. So today we shall look at how to achieve this for other plain text input fields.

So I came up with this solution to be implemented in table_name-dv.js in hooks folder , lets start adding code (table_name replace with your actual table name)

1.

Code: Select all

// Function to get URL parameter by name
  function getURLParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
    const results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  }
The above function is used to get URL parameter by name, so we can pass in the parameter name and it will return the value present.

2.

Code: Select all

// Get the value of the "quote_number" parameter from the URL
const quoteNumberValue = getURLParameter('quote_number');
  // Set the value of the input field if the parameter is present in the URL
  if (quoteNumberValue) {
    document.getElementById('quote_number').value = quoteNumberValue;
  }
The above code calls our getURLParameter function to get the URL parameter value for quote_number and we assign it to a variable named quoteNumberValue Then if a value is found, we use JS to assign that URL parameter value to our form input value, my form field is called: quote_number so I have assigned that value to it.

That is it , remember to replace quote_number with your actual field name in Appgini
The above code will pick the value from a URL parameter and set it to our input field.

So if your URL looks like orders_view.php?addNew_x=1&quote_number=QT-001 the quote_number field will be automatically be pre filled with the value: QT-001

Hope it saved someone!!