Pass URL parameters to a fixed url that opens via modal [SOLVED]

Problem Context:

In Softr Studio, when working with tables or list blocks, there are situations where you need to open a modal window with a custom URL. Softr Studio typically allows URLs to be mapped from Airtable fields or entered manually. However, there are cases where:

  • The URL cannot be mapped to an Airtable field because it’s not at the record level.
  • You need to dynamically pass parameters, like the current record ID from the parent window, to the modal URL.

Challenges:

  1. Custom URL Requirement: Sometimes, the URL you want to open via a modal isn’t directly mapped to a specific Airtable field. It might be a fixed URL or dynamically constructed.
  2. Accessing Parameters: Softr Studio doesn’t directly support passing parameters from a top bar action button to a modal URL. This means you need a workaround to inject parameters dynamically.
  3. Cross-Domain Issues: If you’re embedding external forms or content, passing parameters directly from the main window URL to the modal window URL can be complex due to security restrictions (cross-domain policies).

Solution Overview:

To address these challenges, the script automates the process of:

  • Reading Parameters: It first retrieves a parameter named “recordId” from the main parent window URL.
  • Updating Modal URL: Checks if the modal URL already includes the “id” parameter. If not, it adds the “id” parameter with the value obtained from the parent window.
  • Opening Modal: Finally, it opens the modal window with the updated URL, ensuring that necessary parameters are passed internally within the same domain.

How It Works:

  1. Parameter Retrieval: The script looks for a parameter named “recordId” in the URL of the main parent window.
  2. URL Parameter Check: It then inspects the modal URL that Softr Studio is opening. If the “id” parameter isn’t already included, it appends it with the value from “recordId”.
  3. Opening Modal: This ensures that when the modal opens, it contains the necessary “id” parameter. This approach simplifies passing parameters internally within the same domain, avoiding complex cross-domain issues.

Customization:

  • Parameter Name: You can customize the parameter name from “id” to fit your specific use case.
  • Parent Window Parameter: Change “recordId” to match the parameter you’re using in the main parent window URL.

This script provides a robust solution for dynamically managing and passing parameters to modal URLs within Softr Studio, enhancing flexibility and functionality in your applications.


<script>

// Function to update iframe URL based on recordId parameter from parent window
function updateIframeUrl(recordId) {
    const iframe = document.querySelector('#sw-modal .sw-modal-iframe');
    if (iframe) {
        const currentUrl = iframe.src;
        
        // Check if URL already contains 'id' parameter
        const urlParams = new URLSearchParams(currentUrl.slice(currentUrl.indexOf('?') + 1));
        if (!urlParams.has('id')) {
            // Update URL with 'id' parameter from recordId
            const newUrl = new URL(currentUrl);
            newUrl.searchParams.set('id', recordId); // Add 'id' parameter with recordId value
            
            // Log the URLs and actions
            console.log(`Current URL: ${currentUrl}`);
            console.log(`New URL: ${newUrl.toString()}`);
            
            // Update iframe source
            iframe.src = newUrl.toString();
        } else {
            console.log(`Current URL already has 'id' parameter: ${currentUrl}`);
        }
    } else {
        console.error('Iframe element not found inside modal.');
    }
}

// Function to handle modal opening and update iframe URL
function handleModalOpen() {
    const recordId = getParameterByName('recordId', window.location.href);
    if (recordId) {
        updateIframeUrl(recordId);
    } else {
        console.error('RecordId not found in parent window URL.');
    }
}

// Mutation Observer setup to monitor modal opening
const observer = new MutationObserver((mutationsList, observer) => {
    mutationsList.forEach(mutation => {
        // Check for class attribute changes in modal element
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
            const modal = document.getElementById('sw-modal');
            if (modal && modal.classList.contains('is-open')) {
                handleModalOpen(); // Handle URL update when modal opens
            }
        }
    });
});

// Function to get parameter value from URL
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// Wait for the DOM content to be fully loaded before setting up the observer
document.addEventListener('DOMContentLoaded', () => {
    const modal = document.getElementById('sw-modal');
    if (modal) {
        observer.observe(modal, { attributes: true });
    } else {
        console.error('Modal element not found.');
    }
});



</script>
1 Like

Thanks so much @acjnas. Great information! I see the code references the current url (parent) but where in the code would I specify the new Url? In my scenario, I’m directing the user to a non-modal page but willing to use the modal option if I can get it to function as needed.

Since my sample relies on opening the URL via a modal, the URL is entered in the button properties to open the modal.

Thank you @acjnas I’ve just started coding in softr and wanted to confirm. Is it here:

Thanks again

That is the observer that watches for when the sw-modal element is open and check if parameter exists on url, if it does not exist, script will add it to modal url.

the url I’m directing to is “https://www.abc.life/community-service-calendar?recordId=”. Would I place this in the code somewhere and if so where?

Thanks so much

The url has beed added to the properties of the softr action button that opens the modal.

@acjnas I’m trying to solve for the second challenge you mention in your original post - adding a parameter to the URL of a top-bar button. I’m using the code exactly as constructed, because the parameter I need is the recordId. Still, it’s not working. I’m not sure if this has something to do with the updates made a few weeks ago, or am I just missing something?

Hello @acjnas how is it going,

I’m trying to achieve similar workaround but grabbing a ‘us’ value from the DOM rather than the current URL.

Do you know if your script works until this day? Just like @skmcnair I begun from your exact script to check if it was still working in the first place, I suspect is outdated though.

I’m opening a form from fillout thru a modal, the button addresses a url that’s constructed in airtable thru a formula and has already two dynamic parameters, then, i want to add a third url parameter (from softr) that’s gonna change depending in the logged-in user (i want to know who filled the form without directly asking it in the form).

Any help will be highly appreciated,
Thanks,

Yes you can pass any parameter present in the user session, as url parameter to your fill out form url.

I am guessing you want to pass the ‘user_rec_id’ to your form to know who filled the form.

If you need express help with the custom code to address your use case, you can DM. me