Skip to content

Instantly share code, notes, and snippets.

@alfredo-wpmudev
Last active May 11, 2024 21:15
Show Gist options
  • Save alfredo-wpmudev/c680a8d1632cafda108ce8a18496dc76 to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/c680a8d1632cafda108ce8a18496dc76 to your computer and use it in GitHub Desktop.
Getting ACF field data from user profile then filling the data in the form
<?php
/*
Plugin Name: Forminator Pro Autofill Data from User ACF Fields
Version: 1.0
Description: Forminator Pro Autofill Data from User ACF Fields
Author: Alfredo Galano Loyola
Author URI: https://wpmudev.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
if (!defined('ABSPATH')) {
exit;
}
// No need to do anything if the request is via WP-CLI.
if (defined('WP_CLI') && WP_CLI) {
return;
}
if (!class_exists('WPMUDEV_Forminator_Autoload_Data_ACF')) {
class WPMUDEV_Forminator_Autoload_Data_ACF
{
/**
* $list_forms used to define the forms and the fields related to the code
*/
private $list_forms = array(
1049357 => [ 'date-1' => 'date-1', 'radio-1' => 'radio-2', 'select-1' => 'select-1', "phone-1" => "phone-1", "text-1" => "address","html-1"=>"upload-1"],
);
private $new_belt_rank = "select-2";
/**
* $form_id current form ID
*/
private $form_id = null;
private static $_instance = null;
public static function get_instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new WPMUDEV_Forminator_Autoload_Data_ACF();
}
return self::$_instance;
}
private function __construct()
{
$this->init();
}
public function init()
{
// Do some checks here
if (!defined('FORMINATOR_VERSION') || FORMINATOR_VERSION < '1.12' || !class_exists('Forminator_API')) {
return;
}
// Setting the hooks
add_filter('forminator_render_form_markup', array($this, 'prepare_form_markup'), 1, 6);
add_action('wp_footer', array($this, 'acf_autofil_js'), 9999);
add_action("wp_ajax_student_get_data", array($this, 'student_get_data'), 10);
}
public function prepare_form_markup($html, $form_fields, $form_type, $form_settings, $form_design, $render_id)
{
if ('custom-form' != $form_type){
return $html;
}
$this->form_id = $form_settings['form_id'];
return $html;
}
public function acf_autofil_js()
{
if ( isset($this->list_forms[$this->form_id])){
?>
<script>
jQuery(document ).ready(function() {
user_id = "<?php echo get_current_user_id();?>";
nonce = "<?php echo wp_create_nonce("form_acf_fill_data");?>";
form_id = "<?php echo $this->form_id;?>";
new_belt_rank ="<?php echo $this->new_belt_rank;?>";
//List of the Rank Belts in the Second Select Field
var belt_array = ["two", "8th-Kup-(Yellow-Belt)", "7th-Kup-(Yellow-Belt-with-Green-Strip)", "6th-Kup-(Green-Belt)", "5th-Kup-(Green-Belt-with-Blue-Strip)", "4th-Kup-(Blue-Belt)", "3rd-Kup-(Blue-Belt-with-Red-Strip)", "2nd-Kup-(Red-Belt)", "1st-Kup-(Red-Belt-with-Black-Strip)", "Black-Belt-1st-Dan-Poom", "Black-Belt-2nd-Dan-Poom", "BBlack-Belt-3rd-Dan-Poom"];
jQuery.ajax({
type : "post",
dataType : "json",
url : "<?php echo admin_url( 'admin-ajax.php' );?>",
data : {action: "student_get_data", user_id : user_id, nonce: nonce, form_id:form_id},
success: function(response) {
if(response.type == "success"){
console.log(response);
jQuery.each( response.data, function(i, n){
console.log( "Forminator Field: " + i + ", ACF Value: " + n );
if ( i.startsWith( 'radio' ) || i.startsWith( 'checkbox' ) ) {
jQuery(`#forminator-module-${form_id} [name="${i}"]`).filter(`[value="${n}"]`).prop( 'checked', true );
}else if ( i.startsWith( 'select' ) ) {
// For Select fields we need to trigger `change`
jQuery( `#forminator-module-${form_id} [name="${i}"]` ).val(n).trigger('change');
let index_current_belt = jQuery( `#forminator-module-${form_id} [name="${i}"]` )[0].selectedIndex;
jQuery( `#forminator-module-${form_id} [name="${new_belt_rank}"]` ).val(belt_array[index_current_belt]).trigger('change');
}else if(i.startsWith( 'html' )){
setTimeout(() => {
jQuery(`#${i} div`).append(n);
}, 300);
}
else {
// For another fields
jQuery( `#forminator-module-${form_id} [name="${i}"]` ).val(n).trigger('change');
}
});
}
else {
console.log(response);
}
}
});
});
</script>
<?php
}
}
function student_get_data() {
// nonce check for an extra layer of security, the function will exit if it fails
if ( !wp_verify_nonce( $_REQUEST['nonce'], "form_acf_fill_data")){
return;
}
$user_id = get_current_user_id();
$acf_fields = [];
$result = [];
$result['type'] = "error";
$result['data'] = $acf_fields;
//Checking if the UserID matches and if logged in at same time if the form is allowed and to get the field data.
if ($user_id == $_REQUEST['user_id'] && isset($this->list_forms[$_REQUEST['form_id']])){
foreach ($this->list_forms[$_REQUEST['form_id']] as $forminator_field => $acf_field) {
if($acf_field!=="upload-1"){
$acf_fields[$forminator_field] = get_field( $acf_field, 'user_'.$user_id);
}else{
$upload = get_field('upload-1', 'user_'.$user_id);
$acf_fields[$forminator_field] = ' <img src="'.$upload["sizes"]["thumbnail"].'" class="center"> ';
}
}
//If $acf_fields length is bigger than 0 then it has the student data.
if(count($acf_fields) > 0){
$result['type'] = "success";
$result['data'] = $acf_fields;
}
}
// Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
// don't forget to end your scripts with a die() function - very important
die();
}
}
add_action('plugins_loaded', function () {
return WPMUDEV_Forminator_Autoload_Data_ACF::get_instance();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment