'CF7 Downloading file with multi form page
I am not a developer so please don't close this question, please. In contact form 7 I try to download a file after making a lead.
That's ok with :
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( 'MyformID-1' == event.detail.contactFormId ) {
window.open('https://www.example.com/file-1.pdf', '_self');
}
}, false );
</script>
(I put this code on the concerned page only)
But on some page I have 2 or 3 form which have one different file to download each time. It runs with duplicate the all script :
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( 'MyformID-1' == event.detail.contactFormId ) {
window.open('https://www.example.com/file-1.pdf', '_self');
}
}, false );
</script>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( 'MyformID-2' == event.detail.contactFormId ) {
window.open('https://www.example.com/file-2.pdf', '_self');
}
}, false );
</script>
I think it is possible to make all this into one <script> but I don't know how.
I've made several tests without success, so here I am.
I also tried the code shown here with no success:
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( 'MyformID-1' == event.detail.contactFormId ) {
window.open('https://www.example.com/strong.pdf', '_self');
}
if ( 'MyformID-2' == event.detail.contactFormId ) {
window.open('https://www.example.com/green.pdf', '_self');
}
if ( 'MyformID-3' == event.detail.contactFormId ) {
window.open('https://www.example.com/orange.pdf', '_self');
}
}, false );
</script>
Solution 1:[1]
You can do it like this:
let filenames = {
['MyformID-1']: 'some.pdf',
['MyformID-2']: 'files.pdf',
['MyformID-3']: 'to.pdf',
['MyformID-4']: 'b.pdf',
['MyformID-5']: 'processed.pdf'
};
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (filenames[event.detail.contactFormId]) {
window.open(`https://www.example.com/file-${filenames[event.detail.contactFormId]}`, '_self');
}
}, false );
Explanation:
- we have
filenamesas key-value pair of files, containing the supported pairs of (contact form id; filename) - we can use a single listener
- if the
contactFormIdis supported - then we redirect to a link
- specified with a string template
- where we pass the filename associated to the contact form id as a template literal
We could also resolve this with a regular expression that would look like ^MyformID-[0-9]*$ (I'm not a regexp specialist, so if there is a typo, I would welcome any observations), but I think it's important to make sure that you understand the solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
