In this article, Nicolas explains how to block form submissions based on a member's plans.
- You'll want to add the following code to the Footer or <Body> section of any page that has a form. 4:10 in the video above.
- Add
data-msx-form="protected"
attribute to your form. 3:30 in the video. - Configure the
formRules
object to handle error messages and redirect settings for visitors. 4:30 in the video. - You can prevent some people from seeing the form at all by using gated content to show/hide the form. This is recommended for any form with actual inputs. It's not a very good user experience to complete a form and get an error only when you're ready to submit the form.
<script>
const formRules = {
groups: {
visitor: {
errorMessage: 'please sign up',
redirectTo: '/sign-up',
},
free: {
errorMessage: 'please upgrade to a paid plan',
redirectTo: '/pricing',
},
}
};
const hasPaidPlans = ({ plans }) =>
!!plans?.find((plan) => {
return plan.status === 'ACTIVE' && plan.type === 'SUBSCRIPTION';
});
function handleForms({ forms, groupType }) {
forms.forEach((form, formIndex) => {
let config = formRules["groups"][groupType];
const submitBtn = form.querySelector(
'button[type="submit"], input[type="submit"], a[type="submit"]'
);
submitBtn.addEventListener('click', (e) => {
if (groupType !== 'paid') {
// block form from submitting and redirect
e.preventDefault();
alert(config.errorMessage);
window.location.href = config['redirectTo'];
return;
} else {
console.log('do paid member');
}
});
form.addEventListener('submit', (e) => {
// do things for paid members here
e.preventDefault();
// if you want to reload current page, uncomment line below
// window.location.reload();
// Ucomment below you want to submit form data normally (using form actions or webflow redirect settings)
//form.submit()
});
});
}
window.$memberstackDom.getCurrentMember().then(({ data: member }) => {
const forms = document.querySelectorAll('[data-msx-form="protected"]');
if (forms && forms.length) {
let groupType = "visitor"
if(member) {
const plans = member?.['planConnections'];
groupType = hasPaidPlans({ plans }) ? 'paid' : 'free';
}
console.log({ groupType });
handleForms({ forms, groupType });
}
});
</script>
Comments
0 comments
Please sign in to leave a comment.