mercredi 25 mars 2020

Gravity forms pre-selected choices checkboxes field

I am using Gravity forms with one Radio Button and one Checkboxes field they both have same choices. What I need is when my user chooses a choice on Radio Button, this choice is automatically pre-selected on the Checkboxes field. He doesn't have to select it again.

I saw I have to use some filter, for example, the one below, but I cannot succeed to customize it in order to do what I need.

If someone could help me he will save my life.

<?php

# Make sure to replace {id} with your form's id
add_filter( 'gform_pre_render_{id}', 'my_populate_checkbox' );

function my_populate_checkbox( $form ) {

/**
* Loop through form fields
*
* Note we are using the `$field` array as a direct reference using `&`. 
* This means that changing its value will within the loop will 
* change the corresponding `$form` array item
*/
foreach( $form['fields'] as &$field ) {

# Make sure to change `1` to the ID of the checkbox field that you want to pre-populate
if( 1 === $field->id ) {

  /**
   * Loop through the choices for this checkbox
   *
   * Note again that we are passing `$choice` by reference in order to change the 
   * corresponding array item within the `$field` array
   */
  foreach( $field->choices as &$choice ) {

    /**
     * If this choice has a value of 'red' or 'blue', then make sure the checkbox is pre- 
   checked
     * by setting the `isSelected` parameter to `true`
     */

    if( 'red' === $choice['value'] || 'blue' === $choice['value'] ) {
      $choice['isSelected'] = true;
    }
   } # end foreach: $field->choices
   } # end if: $field->id equals 1
   } # end foreach: $form['fields']

    # return the altered `$form` array to Gravity Forms
   return $form;

    } # end: my_populate_checkbox



Aucun commentaire:

Enregistrer un commentaire