Skip to content
Advertisement

How to change which choice in a Gravity Forms radio button field is selected using PHP as part of a gform_pre_submission

My PHP skills are not good but I learn by code example because I am not familiar with the syntax, but in this case I can not find a code example that works.

I want to set a Product Option Radio Button Field’s selected value during a gform_pre_submission add_action based on another field’s value. I’ve tried something like this (there are other functions and variables are defined elsewhere in advance, this is an abstract) but this approach isn’t working for me and I am wondering what I am missing:

add_action( 'gform_pre_submission_FORMIDhere', 'select_radio_button' );

function select_radio_button( $form) {

  foreach( $form['fields'] as &$field ) {
    
    if( 53 === $field->id ) {
     
      foreach( $field->choices as &$choice ) {  
      echo($aag_kg_nummorn.' / /'.$choice['value']);
        if( $aag_kg_nummorn == $choice['value'] ) {
            echo('Bingo!');
          $choice['isSelected'] = true;  // <- THIS line doesn't work for me
        }
      } 
    } 
  } 
  return $form;
}

Thank you for helping me in advance.

Advertisement

Answer

There are a couple of things I want to point out before answering

  1. You should be modifying $_POST instead of the field, I can see you already figured this out.
  2. gform_pre_submission is an action, not a filter, so returning the form here doesn’t do anything.

The Answer

Say you have a product option field that has the ID of 2, and it has 3 options

First Option|1

Second Option|2

Third Option|3

Then the code will look like

add_action( 'gform_pre_submission_FORMIDhere', 'select_radio_button' );

function select_radio_button( $form ) {

   $_POST['input_2'] = 'New Option|6';

}

I assume you are using this with a payment form that utilizes one of the gravityforms payment add-ons like stripe or Paypal, some of these add-ons (like PayPal Checkout) sends the total value to the payment gateway using JS before this action is fired, so the total value sent to the payment gateway will be the value of the option the user has already selected, but the total value on the entry will use the value you set in the code.

If you need help on how to override this from the JS side as well so you can send the overridden value to the payment gateway, I can write that in a separate answer.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement