Last Updated on January 21, 2024 by Neil Murray
To connect CF7 Skins Visual with WordPress in general, and Contact Form 7 in particular, both sides need to provide and receive data.
We use cf7sRequest() from src/visual/util/api.js as an AJAX post request.
This covers:
- saving data from CF7 Skins Visual to the WordPress database
- selecting a Template and loading it into both the CF7 Skins Visual UI & the CF7 Form tab
Data Exchange #
WordPress adds the window.cf7svisual global variable to the page using wp_localize_script as follows:
wp_localize_script( 'visual-lite', 'cf7svisual', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce( CF7SKINSVISUAL_OPTIONS ), // generate a nonce for security checking
'update' => 'cf7skins_visual_update', // post action for saving
...
));
which results in:
<script type='text/javascript'>
/* <![CDATA[ */
var cf7svisual = {"ajaxurl":"http:\/\/localhost\/wptheme\/wp-admin\/admin-ajax.php","nonce":"81efb08858","update":"cf7skins_visual_update","l10n":{"save":"Save","done":"Done","error":"Error"},"title":"Logic Checkbox","items":[]};
/* ]]> */
</script>
The variable can be accessed using JavaScript window.cf7svisual as an object that contains following properties:
ajaxurl– URL for AJAX post requestnonce– WordPress generated nonce for security checkingupdate– WordPress callback function to run after security checks.
The WordPress callback function
cf7skins_visual_update()is included insrc/dev/includes/admin-visual.php. This is the place where the Visual data is saved into the WP database.
cf7sRequest() #
This part of the Visual utility JavaScript function, placed in src/visual/util/api.js, handles data exchange from Visual to Contact Form 7 & WordPress or vice versa.
The function uses external module whatwg-fetch, a polyfill for JavaScript fetch and currently only support for post method. It returns fetched data using a JavaScript Promise.
Function parameters:
postData{object} – contains WordPress AJAX action name, form id, Visual data etc. as a post body forfetch.dataType{string} – returned data type: text, json.
It fetchs to window.cf7svisual.ajaxurl with fetchOption ( contains method, header, body (URI encoded postData) etc. ), then returns a promise data sent by WordPress in text or json data type.
let savedData = fetch( window.cf7svisual.ajaxurl, fetchOption )
.then( function( response ) {
// return as text or json
})
.then( function( data ) {
// return data from WordPress on success or throw error on failure.
})
.catch ( error => {
// error handling
});
return Promise.resolve( savedData );
Save Visual #
To save the Visual tree data ( RST treeData ), we need to click the Save Visual button. Using the general CF7 Save button will not save the Visual data.
At this stage we see advantages in the user being able to save changes they make in the CF7 Form tab and the CF7 Skins Visual Form tab separately. This may change as we get more feedback from users.
The function saveVisualForm() included in src/visual/index.js checks for both the window.cf7svisual variable and an input element with post_ID for CF7 form ID, before continuing with saving the Visual data.
if ( ! window.cf7svisual || ! document.getElementById('post_ID') ) {
console.error( 'Can not save! window.cf7svisual or post ID is not existed.' )
return
}
There are two methods of saving Visual data into WordPress:
- using the default CF7 form submit for a newly created form
- using AJAX for an edited form.
New Form
For a newly created form, the form does not have an ID. We simply append a hidden input text inside the CF7 form that contains the Visual treeData and submit as a normal form.
appendedInput.setAttribute('type', 'hidden')
appendedInput.setAttribute('name', 'cf7s-visual')
appendedInput.setAttribute('value', JSON.stringify(treeData))
CF7Form.appendChild(appendedInput)
CF7Form.submit() // submit CF7 form itself
Edited Form
An edited form is saved using cf7sRequest() that contains the WordPress callback function cf7skins_visual_update, WordPress nonce, form id, etc. After saving the data we update CF7 Form tab textarea.
const postData = {
action : 'cf7skins_visual_update',
form_id : form_id,
visual : JSON.stringify(treeData)
};
cf7sRequest( postData )
.then( ( data ) => {
window.cf7sAdmin.getTextarea().val( data ); // update CF7 textarea
} )
.catch( ( err ) => console.error( err ) );
Selecting Template #
Before doing AJAX, in WordPress we define the callback function visual_select_template found at admin.php that runs the select_template function.
add_action( 'wp_ajax_visual_select_template', array( &$this, 'select_template' ) );
The selecting template function is placed in Visual.componentWillMount() to put our AJAX function before the DOM is rendered.
Visual adds a click event for each select template anchor link. While selecting a template, Visual passes the callback function name and selected template name.
After security checking, WordPress runs the callback function that reads visual.json in the template directory and sends back to Visual to update the treeData and posts these parameters to cf7sRequest() with a json data type.
const tabTemplate = document.getElementById('tab-template');
tabTemplate && tabTemplate.addEventListener('click', (e) => {
const postData = {
action : 'visual_select_template',
template : e.target.dataset.value
};
cf7sRequest( postData, 'json' )
.then( ( updatedTree ) => {
this.mergeDefault( updatedTree ); // merge with default cf7sItems property
return !! updatedTree && this.setState( { treeData : updatedTree } ) // update treeData
} )
.catch( ( err ) => console.error( err ) );
})
}
Further Reading
- CF7 Skins Visual: Data Exchange Strategies
- AJAX in WordPress
- AJAX in Plugins
- Plugin API/Action Reference/wp ajax (action)
- WordPress Nonces
Notes
Add notes here