Skip to main content
Gravity FormsWordPress

Gravity Forms – Calcolo automatico data di scadenza in base a input utente

Questa funzione vi permetterà di calcolare in automatico la data di scadenza in base al numero di mesi selezionati

Questa funzione, leggermente più lunga del solito, vi permetterà di calcolare un data di scadenza in Gravity Forms utilizzando la data iniziale impostata dall’utente e il numero di mesi fra quanto “scadrà”

Per fare ciò e necessario convertire la data iniziale in numero utilizzabile e successivamente sommargli il valore di selezione dei mesi

Ecco la funzione da inserire nel file function.php del proprio tema di wordpress

è sufficiente modificare la parte finale della funzione con:

‘form_id’ => 2, // ID della form
‘target_field_id’ => 13, //ID Campo dove scrivere la data di scadenza
‘source_field_id’ => 7, //ID Campo da dove prendere la data iniziale
‘modifier’ => array(
type’ => ‘field’,
inputId’ => 15, //ID campo da dove prendere i mesi di scadenza
modifier’ => ‘+{0} month’, // Calcola automatico in base al valore in mesi


class GW_Populate_Date {

protected static $is_script_output = false;

public function __construct( $args = array() ) {

// set our default arguments, parse against the provided arguments, and store for use throughout the class
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'target_field_id' => false,
'source_field_id' => false,
'format' => '',
'modifier' => false,
'min_date' => false,
'enable_i18n' => false,
) );

$this->_field_values = array();

if( ! $this->_args['form_id'] || ! $this->_args['target_field_id'] ) {
return;
}

// time for hooks
add_action( 'init', array( $this, 'init' ) );

}

public function init() {

// make sure we're running the required minimum version of Gravity Forms
if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
return;
}

if( $this->_args['source_field_id'] ) {
add_action( 'gform_pre_submission', array( $this, 'populate_date_on_pre_submission' ) );
add_filter( 'gform_pre_render', array( $this, 'load_form_script' ) );
add_filter( 'gform_register_init_scripts', array( $this, 'add_init_script' ) );
add_filter( 'gform_enqueue_scripts', array( $this, 'enqueue_form_scripts' ) );
} else {
add_filter( 'gform_pre_render', array( $this, 'populate_date_on_pre_render' ) );
}

}

public function enqueue_form_scripts( $form ) {
if( $this->is_applicable_form( $form ) ) {
wp_enqueue_script( 'moment', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js' );
add_filter( 'gform_noconflict_scripts', function( $scripts ) {
$scripts[] = 'moment';
return $scripts;
} );
}
}

public function populate_date_on_pre_render( $form ) {

if( ! $this->is_applicable_form( $form ) ) {
return $form;
}

foreach( $form['fields'] as &$field ) {
if( $field['id'] == $this->_args['target_field_id'] ) {

$key = sprintf( 'gwpd_%d_%d', $form['id'], $field['id'] );
$value = $this->get_modified_date( $field );

$field['allowsPrepopulate'] = true;
$field['inputName'] = $key;

$this->_field_values[ $key ] = $value;

add_filter( "gform_field_value_{$key}", array( $this, 'set_field_value' ), 10, 3 );

}
}

return $form;
}

public function set_field_value( $value, $field, $name ) {
if( isset( $this->_field_values[ $name ] ) ) {
$value = $this->_field_values[ $name ];
}
return $value;
}

public function populate_date_on_pre_submission( $form ) {

if( ! $this->is_applicable_form( $form ) ) {
return;
}

foreach( $form['fields'] as &$field ) {
if( $field['id'] == $this->_args['target_field_id'] ) {

$timestamp = $this->get_source_timestamp( GFFormsModel::get_field( $form, $this->_args['source_field_id'] ) );
$value = $this->get_modified_date( $field, $timestamp );

if( $value ) {
$_POST[ "input_{$field['id']}" ] = $value;
}

}
}

}

public function get_source_timestamp( $field ) {

$raw = rgpost( 'input_' . $field['id'] );
if( is_array( $raw ) ) {
$raw = array_filter( $raw );
}

list( $format, $divider ) = $field['dateFormat'] ? array_pad( explode( '_', $field['dateFormat' ] ), 2, 'slash' ) : array( 'mdy', 'slash' );
$dividers = array( 'slash' => '/', 'dot' => '.', 'dash' => '-' );

if( empty( $raw ) ) {
$raw = date( implode( $dividers[ $divider ], str_split( $format ) ) );
}

$date = ! is_array( $raw ) ? explode( $dividers[ $divider ], $raw ) : $raw;

$month = $date[ strpos( $format, 'm' ) ];
$day = $date[ strpos( $format, 'd' ) ];
$year = $date[ strpos( $format, 'y' ) ];

$timestamp = mktime( 0, 0, 0, $month, $day, $year );

return $timestamp;
}

public function get_modified_date( $field, $timestamp = false ) {

if( ! $timestamp ) {
$timestamp = current_time( 'timestamp' );
}

// Always respect the passed format; it may conflict with the Date format but this is used at the user's discretion.
if( $this->_args['format'] ) {
$format = $this->get_format();
}
else if( GFFormsModel::get_input_type( $field ) == 'date' ) {

list( $format, $divider ) = $field['dateFormat'] ? array_pad( explode( '_', $field['dateFormat' ] ), 2, 'slash' ) : array( 'mdy', 'slash' );
$dividers = array( 'slash' => '/', 'dot' => '.', 'dash' => '-' );

$format = str_replace( 'y', 'Y', $format );
$divider = $dividers[ $divider ];
$format = implode( $divider, str_split( $format ) );

}

if( $this->_args['modifier'] ) {

$modifier = $this->_args['modifier'];

if( is_array( $modifier ) ) {
$key = sprintf( 'input_%s', str_replace( '.', '_', $modifier['inputId'] ) );
$value = gf_apply_filters( array( 'gwpd_get_field_value', $this->_args['form_id'], $modifier['inputId'] ), intval( rgpost( $key ) ), $modifier['inputId'] );
$modifier = $value > 0 ? sprintf( str_replace( '{0}', '%d', $modifier['modifier'] ), $value ) : false;
}

if( $modifier ) {
$timestamp = strtotime( $modifier, $timestamp );
}

}

if( $this->_args['min_date'] ) {
$min_timestamp = strtotime( $this->_args['min_date'] ) ? strtotime( $this->_args['min_date'] ) : $this->_args['min_date'];
if( $min_timestamp > $timestamp ) {
$timestamp = $min_timestamp;
}
}

if( $this->_args['enable_i18n'] ) {
$date = strftime( $format, $timestamp );
} else {
$date = date( $format, $timestamp );
}

return $date;
}

public function get_format( $should_convert = null ) {

if ( $should_convert === null ) {
$should_convert = $this->_args['enable_i18n'];
}

$format = ! $this->_args['format'] ? 'Y-m-d' : $this->_args['format'];
if ( $should_convert ) {
$format = $this->date_format_to( $format, 'strf' );
}

return $format;
}

public function load_form_script( $form ) {

if( $this->is_applicable_form( $form ) && ! has_action( 'wp_footer', array( __CLASS__, 'output_script' ) ) ) {
add_action( 'wp_footer', array( __CLASS__, 'output_script' ), 21 );
add_action( 'gform_preview_footer', array( __CLASS__, 'output_script' ), 21 );
}

return $form;
}

public static function output_script() {
?>

is_applicable_form( $form ) ) {
return;
}

$args = array(
'formId' => $this->_args['form_id'],
'targetFieldId' => $this->_args['target_field_id'],
'sourceFieldId' => $this->_args['source_field_id'],
'modifier' => $this->_args['modifier'],
// Keep the format in the `date()` format for JS.
'format' => $this->get_format( false ),
);

$script = 'new GWPopulateDate( ' . json_encode( $args ) . ' );';
$slug = implode( '_', array( 'gw_populate_date', $this->_args['form_id'], $this->_args['target_field_id'] ) );

GFFormDisplay::add_init_script( $this->_args['form_id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );

}

public function is_applicable_form( $form ) {

$form_id = isset( $form['id'] ) ? $form['id'] : $form;

return $form_id == $this->_args['form_id'];
}

/**
* Convert date/time format between `date()` and `strftime()`
*
* Timezone conversion is done for Unix. Windows users must exchange %z and %Z.
*
* Unsupported date formats : S, n, t, L, B, G, u, e, I, P, Z, c, r
* Unsupported strftime formats : %U, %W, %C, %g, %r, %R, %T, %X, %c, %D, %F, %x
*
* @param string $format The format to parse.
* @param string $syntax The format's syntax. Either 'strf' for `strtime()` or 'date' for `date()`.
*
* @return bool|string Returns a string formatted according $syntax using the given $format or `false`.
* @link http://php.net/manual/en/function.strftime.php#96424
* @link https://gist.github.com/mcaskill/02636e5970be1bb22270
*
* @example Convert `%A, %B %e, %Y, %l:%M %P` to `l, F j, Y, g:i a`, and vice versa for "Saturday, March 10, 2001, 5:16 pm"
*/
function date_format_to( $format, $syntax ) {
// http://php.net/manual/en/function.strftime.php
$strf_syntax = [
// Day - no strf eq : S (created one called %O)
'%O', '%d', '%a', '%e', '%A', '%u', '%w', '%j',
// Week - no date eq : %U, %W
'%V',
// Month - no strf eq : n, t
'%B', '%m', '%b', '%-m',
// Year - no strf eq : L; no date eq : %C, %g
'%G', '%Y', '%y',
// Time - no strf eq : B, G, u; no date eq : %r, %R, %T, %X
'%P', '%p', '%l', '%I', '%H', '%M', '%S',
// Timezone - no strf eq : e, I, P, Z
'%z', '%Z',
// Full Date / Time - no strf eq : c, r; no date eq : %c, %D, %F, %x
'%s'
];

// http://php.net/manual/en/function.date.php
$date_syntax = [
'S', 'd', 'D', 'j', 'l', 'N', 'w', 'z',
'W',
'F', 'm', 'M', 'n',
'o', 'Y', 'y',
'a', 'A', 'g', 'h', 'H', 'i', 's',
'O', 'T',
'U'
];

switch ( $syntax ) {
case 'date':
$from = $strf_syntax;
$to = $date_syntax;
break;

case 'strf':
$from = $date_syntax;
$to = $strf_syntax;
break;

default:
return false;
}

$pattern = array_map(
function ( $s ) {
return '/(? sprintf( '%stype-%s', $prefix, $field->type ),
'date_type' => sprintf( '%sdateType-%s', $prefix, $field->dateType ),
'date_format' => sprintf( '%sdateFormat-%s', $prefix, $field->dateFormat ? $field->dateFormat : 'mdy' )
);
break;
case 'time':
$classes = array(
'type' => sprintf( '%stype-%s', $prefix, $field->type ),
'time_format' => sprintf( '%stimeFormat-%s', $prefix, $field->timeFormat ? $field->timeFormat : 'mdy' )
);
break;
}

if( $classes ) {
$current_classes = explode( ' ', $field->cssClass );
$classes = array_unique( array_merge( $current_classes, $classes ), SORT_REGULAR );
$field->cssClass .= ' ' . implode( ' ', $classes );
}

}

return $form;
} );

add_filter( 'gform_replace_merge_tags', function ( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
$merge_tag = '{gv_now_timestamp}';
if ( strpos( $text, $merge_tag ) === false ) {
return $text;
}
$local_timestamp = GFCommon::get_local_timestamp( time() );
//$local_date = date_i18n( 'Y-m-d', $local_timestamp, true );
return str_replace( $merge_tag, $local_timestamp, $text );
}, 10, 7 );

// Sezione che permette il funzionamento del calcolo della data in base alla selezione del dropdown
new GW_Populate_Date( array(
'form_id' => 2,
'target_field_id' => 13,
'source_field_id' => 7,
'modifier' => array(
'type' => 'field',
'inputId' => 15,
'modifier' => '+{0} month',
),
) );

Leave a Reply

Rispettiamo la tua privacy!

Su questo sito utilizziamo strumenti nostri o di terze parti che memorizzano piccoli file (cookie) sul tuo dispositivo. I cookie sono normalmente usati per permettere al sito di funzionare correttamente (cookie tecnici), per generare statistiche di uso/navigazione (cookie statistici). Abilitando questi cookie, ci aiuti ad offrirti una esperienza migliore con noi.

Privacy & Cookie Policy