Trouble with Ninja Forms ninja_forms_submit_data hook - php

Could someone tell me what am I doing wrong with this Ninja Forms hook:
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
function my_ninja_forms_submit_data( $form_data ) {
foreach( $form_data[ 'fields' ] as $field ) {
if( 'test_page_url_1519171605789' == $field['key'] ){
$current_url = "my url - {$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$field[ 'value' ] = $current_url;
}
}
$form_settings = $form_data[ 'settings' ]; // Form settings.
$extra_data = $form_data[ 'extra' ]; // Extra data included with the submission.
return $form_data;
}
I am trying to modify the hidden form field with the key value "test_page_url_1519171605789" so that it contains a URL.

I was able to solve this issue by using this code instead:
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
function my_ninja_forms_submit_data( $form_data ) {
//Need to set the current URL as the previous page since
//REQUEST_URI was returning /wp-admin/admin-ajax.php
//instead of the form's actual URL.
$current_url = $_SERVER['HTTP_REFERER'];
foreach( $form_data[ 'fields' ] as $key => $field ) {
//I need to look for the field ID and not the field key
if( $key == '197' || $key == '195' || $key == '196' || $key == '179' ){
// Update the submitted field value with the URL to the previous page.
$form_data['fields'][$key]['value'] = $current_url;
}
}
// Form settings.
$form_settings = $form_data[ 'settings' ];
// Extra data included with the submission.
$extra_data = $form_data[ 'extra' ];
return $form_data;
}

Related

Form validations for non-required fields

I'm trying to add some form validations to a site I'm working on. I was able to get the validations to work on the fields that are required but as I'm trying to adjust the code for the non-required fields that still need to be validated when there is user-input I'm running into some issues.
This works pretty flawlessly if the field is required but when I make the field not required, the form doesn't submit and puts out an error message if I leave the field blank.
add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
$fields = $record->get_field( [
'id' => 'dot',
] );
if ( empty( $fields ) ) {
return;
}
$field = current( $fields );
if ( 1 !== preg_match( '/[1-9]{1}[0-9]{5,7}/', $field['value'] ) || $field['value'] == '123456' || $field['value'] == '12345678' ) {
$ajax_handler->add_error( $field['id'], 'Invalid DOT#' );
}
}, 10, 2 );

WooCommerce change order status using elementor forms

I am trying to build a form where when a user enters their order ID and unique serial code in the elementor form their order status is changed to completed. Heres the code i have written but i keep getting an error. The form has 2 fields 'a' & 'b'. A= order id and B= serial code.
add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
$fields = $record->get_field( [
'id' => 'b'
], ['cid' => 'a'
]);
if ( empty( $fields ) ) {
return;
}
$field = current( $fields );
if ( 1 !== strlen( $field['value'] ) < 13 ) {
$ajax_handler->add_error( $field['id'], 'Invalid Serial Code, Please enter the 13 Digit Code mentioned on your delivery letter' );
} else {
$output['result'] = get_post_meta( $field['cid'], $key = 'shp_tkn', $single = true );
}
if ($output == $field['id']){
$order = $field['cid'] ;
$order->update_status('completed');
} else {
$ajax_handler->add_error( $field['id'], 'Invalid Serial Code, Please try again' );
}
}, 10, 2 );
If anyone could tell me where I'm going wrong.

Display composite order data in WooCommerce admin Orders List column

My order has information that I want to call to view on my order page.
But this information is not stored as metadata, is there a way to get this information anyway?
Information that I want to get:
Where the information is stored in the code:
I tried some things but I am getting errors all the time, this is what I tried:
// ADDING 2 NEW COLUMNS WITH THEIR TITLES (keeping "Total" and "Actions" columns at the end)
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column_another', 20 );
function custom_shop_order_column_another($columns)
{
$reordered_columns = array();
// Inserting columns to a specific location
foreach( $columns as $key => $column){
$reordered_columns[$key] = $column;
if( $key == 'order_status' ){
// Inserting after "Status" column
$reordered_columns['my-column3'] = __( 'Wefact email','theme_domain');
$reordered_columns['my-column4'] = __( 'Wefact status','theme_domain');
}
}
return $reordered_columns;
}
// Adding custom fields meta data for each new column (example)
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_Another_content', 20, 2 );
function custom_orders_list_column_Another_content( $column, $post_id )
{
switch ( $column )
{
case 'my-column3' :
// Get custom post meta data
$my_var_one = get_post_meta( $post_id, 'WeFact_email', true );
if(!empty($my_var_one))
echo $my_var_one;
// Testing (to be removed) - Empty value case
else
echo '<small>(<em>no value</em>)</small>';
break;
case 'my-column4' :
// Get custom post meta data
$wfInvoiceID = (int) get_post_meta( $post_id, '_wefact_invoice_id', true);
if (isset($wfInvoiceID)) :
$invoice = new WeFactInvoice();
$wfInvoice = $invoice->showByID($wfInvoiceID);
if ($wfInvoice['status'] == 'success') :
$status = [
"0" => "Concept factuur",
"1" => "Wachtrij factuur",
"2" => "Verzonden",
"3" => "Deels betaald",
"4" => "Betaald",
"8" => "Creditfactuur",
"9" => "Vervallen",
];
if(!empty($wfInvoiceID))
echo $status[$wfInvoice['invoice']['Status']];
// Testing (to be removed) - Empty value case
else
echo '<small>(<em>no value</em>)</small>';
break;
endif;
}
}
Try the following revisited code (using WC_Data method get_meta() on the WC_Order Object):
// ADDING 2 NEW COLUMNS WITH THEIR TITLES (keeping "Total" and "Actions" columns at the end)
add_filter( 'manage_edit-shop_order_columns', 'add_custom_wefact_shop_order_columns', 20 );
function add_custom_wefact_shop_order_columns( $columns ) {
$reordered_columns = array();
// Inserting columns to a specific location
foreach( $columns as $key => $column ){
$reordered_columns[$key] = $column;
if( $key == 'order_status' ){
// Inserting after "Status" column
$reordered_columns['wefact-email'] = __( 'Wefact email', 'theme_domain');
$reordered_columns['wefact-status'] = __( 'Wefact status', 'theme_domain');
}
}
return $reordered_columns;
}
// Adding custom fields meta data for each new column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_wefact_shop_order_columns_content', 20, 2 );
function custom_wefact_shop_order_columns_content( $column, $post_id ) {
global $post, $the_order;
$order = is_a($the_order, 'WC_Order') ? $the_order : wc_get_order($post_id);
if ( 'wefact-email' === $column ) {
$wefact_email = $order->get_meta('WeFact_email'); // Get order custom field
echo empty($wefact_email) ? '<small>(<em>no value</em>)</small>' : $wefact_email;
}
elseif( 'wefact-status' === $column ) {
$wfInvoiceID = $order->get_meta('_wefact_invoice_id'); // Get order custom field
$wfInvoiceID = empty($wfInvoiceID) ? $order->get_meta('_order_wefact_invoice_id') : $wfInvoiceID; // Get order custom field
$value_output = '';
if ( ! empty($wfInvoiceID) && class_exists('WeFactInvoice') ) {
$invoice = new WeFactInvoice();
$wfInvoice = $invoice->showByID($wfInvoiceID);
if ($wfInvoice['status'] == 'success') {
$status = [
"0" => "Concept factuur",
"1" => "Wachtrij factuur",
"2" => "Verzonden",
"3" => "Deels betaald",
"4" => "Betaald",
"8" => "Creditfactuur",
"9" => "Vervallen",
];
if( isset($wfInvoice['invoice']['Status']) && isset($status[$wfInvoice['invoice']['Status']]) ) {
$value_output = $status[$wfInvoice['invoice']['Status']];
}
}
}
echo empty($value_output) ? '<small>(<em>no value</em>)</small>' : $value_output;
}
}
Code goes in functions.php file of the active child theme (or active theme). It should work.

Validate at least one field to be filled in, Gravity forms

I have been trying to create a custom validation hook for Gravity Forms plugin.
The validation checks that at least one field has been filled in from a set of fields.
Check out the code below, I just can't get it too work. I think it is something to do with the variables for the inputs, even if a field is filled in, the error still shows on each field?
add_filter( 'gform_field_validation_2', function ( $result, $value, $form, $field ) {
if ( $field->type == 'number') {
$a = rgar( $value, $field->id . '10' );
$b = rgar( $value, $field->id . '12' );
$c = rgar( $value, $field->id . '13' );
$d = rgar( $value, $field->id . '14' );
$e = rgar( $value, $field->id . '15' );
$f = rgar( $value, $field->id . '17' );
$g = rgar( $value, $field->id . '18' );
$h = rgar( $value, $field->id . '20' );
$i = rgar( $value, $field->id . '21' );
$j = rgar( $value, $field->id . '22' );
$k = rgar( $value, $field->id . '23' );
if ( !empty($a) || !empty($b) || !empty($c) || !empty($d) || !empty($e) || !empty($f) || !empty($g) || !empty($h) || !empty($i) || !empty($j) || !empty($k) ) {
$result['is_valid'] = true;
$result['message'] ='';
} else {
$result['is_valid'] = false;
$result['message'] = 'Please select a quantity of materials to order';
}
}
return $result;
}, 10, 4 );
I think you maybe should use a field of type "radio buttons".
Anyway, if your form has several "number" fields and you need to validate that at least one of them has been filled, then you should use the gform_validation filter since you're validating the whole form, not just a single field.
TIP: Add a custom css class to each field in the group to identify them. for example "validate-quantity".
add_filter('gform_validation_2', 'quantity_validation', 1, 4);
function quantity_validation($validation_result) {
if ($validation_result['is_valid']) {
$valid=false;
$form = $validation_result['form'];
foreach( $form['fields'] as &$field ) {
if ( strpos( $field->cssClass, 'validate-quantity' ) === false ) {
continue;
}
$field_value = rgpost( "input_{$field['id']}" );
if (!empty($field_value)) {
$valid=true;
break;
}
}
if (!$valid) {
$field["failed_validation"] = true;
$field["validation_message"] = 'Please select a quantity of materials to order';
$validation_result['form'] = $form;
}
}
return $validation_result;
}
So heres a working version (Thanks for the gform_validation hint Francisco R) - Went down a slightly different route, but works perfectly, incase anyone interested in future!
add_filter( 'gform_validation_2', 'custom_validation_2' );
function custom_validation_2( $validation_result ) {
// array of field IDs to be checked
$field_ids = array (10, 12, 13, 14, 15, 17, 18, 20, 21, 23, 22);
// get the form object from the validation result
$form = $validation_result['form'];
// counter to store how many fields have a value > 0 submitted
$number_of_fields = 0;
// loop through all the fields to be sure one has a value > 0
foreach ( $field_ids as $input ) {
// the rgpost string we are going to check
$input_id = 'input_' . intval( $input );
// the value that was submitted
$input_value = rgpost ( $input_id );
if ( $input_value > 0 ) {
// if any field in the array has a value, we can just continue
$number_of_fields++;
} // end if
else {
// no value for this input, so continue without incrementing the counter
continue;
} // end else
} // end foreach
// check the $number_of_fields and if it is 0 return a validation error
if ( $number_of_fields == 0 ){
// set the form validation to false
$validation_result['is_valid'] = false;
// mark all the fields with a validation error
foreach( $form['fields'] as &$field ) {
// add a validation error to *all* the inputs if none were submitted > 0
if ( in_array( $field->id, $field_ids ) ) {
$field->failed_validation = true;
$field->validation_message = 'Please select a quantity of materials to order from one or all of these fields.';
} // end if
} // end foreach
} // end if
// assign modified $form object back to the validation result
$validation_result['form'] = $form;
return $validation_result;
}
It looks you should change your if clause to:
if ( empty($a) || empty($b) || empty($c) || empty($d) || empty($e) || empty($f) || empty($g) || empty($h) || empty($i) || empty($j) || empty($k) ) {
to validate if at least one option is selected.
To skip not targeted fields add the following code before complex if above:
$target_fields = array('name_1', 'name_2');
if (!in_array($field, $target_fields)) {
$result['is_valid'] = true;
$result['message'] = '';
}

Wordpress - Validating custom fields through backend

First off, I'm using advanced custom fields plugin, and I'm using a repeater. I have a custom post type that triggers when pressing "publish" when creating a new post, what it does, is that it adds a row to my repeater field.
Basiclly it takes the info from other fields and comes up with the proper information that the row created must have by making some calculations.
this is my function:
function investment_save($post_id)
{
$post = get_post();
$poststat = get_post_status($post_id);
$fecha = current_time(d-M-Y);
$fecha2 = "Inversión ".$fecha;
if($poststat == "publish" && !have_rows('datos_especificos'))
{
remove_action( 'save_post', 'investment_save' );
$my_post = array(
'ID' => $post_id,
'post_title' => $fecha2,
);
wp_update_post( $my_post );
$fech = get_field('fecha_de_inicio_de_la_inversion');
$sald = get_field('monto_de_la_inversion');
$tasa = get_field('tasa_de_interes');
$cap = get_field('uso_de_interes');
$elsald0 = $tasa/12*0.01*$sald;
$elsald=number_format($elsald0,2);
if($cap=="pagar")
{
$cap2=$elsald;
$cantr=0;
}else{
$cap2=0;
$cantr=$elsald;
}
$sf = $sald+$cantr;
$field_key = "datos_especificos";
$value = get_field($field_key, $post_id);
$value[] = array("fecha" => $fech,
"saldo" => $sald,
"inversion_en_el_periodo" => "0",
"interes_causado_en_el_periodo" => $elsald,
"cantidad_pagada" => $cap2,
"cantidad_reinvertida" => $cantr,
"saldo_final" => $sf);
update_field( $field_key, $value, $post_id );
}
}
add_action( 'save_post', 'investment_save' );
This works properly, however, I have a new task in which everytime I press update, I must check if $cr+$cp equal $icelp in all rows, if they not, i must adjust the values from them, so this is the kind of code I'd like to use:
$sum = $cp + $cr;
if($sum>$icelp)
{
$dif=$sum-$icelp;
if($cp>=$cr)
{
$cp=$cp-$dif;
}else
{
$cr=$cr-$dif;
}
}
if($sum<$icelp)
{
$dif=$icelp-$sum;
if($cp>=$cr)
{
$cr=$cr+$dif;
}else
{
$cp=$cp+$dif;
}
}
Ive tried using an"else", also using an "if", but I just can't make it work. Please Someone help me I've been breaking my head for days

Categories