Can you add a field to a form that cannot be deleted by users?

I am creating an add-on and it adds a setting as a checkbox (on or off). If this setting is turned on, I need the form to contain a specific field with a value and I do not want this field to be editable by an admin user.

At first I thought I could just add the field on gform_pre_render and prepoluate its value with gform_field_value_%field_name% but if I do this then the value isn’t present in the entries table.

If I add the field using the GFAPI on gform_after_save_form then the user is able to delete this field while editing the form. I could keep re-adding the field but this would break previous entries as the field’s ID would be different once re-created.

I’ve discovered that I can hack something together by using wp_die() on gform_before_delete_field but then the behaviour of the edit page gets really wobbly and the user could potentially lose progress on their form, and I would hate for that to happen, even if it’s a user problem.

So what is the best way to add a field dynamically, where the field is present in the entries table when customers fill the form, and that cannot be deleted by an admin user (unless my setting is set to off)?

Instead of using gform_pre_render to add the field, try using gform_form_post_get_meta. If you’d like to exclude the field when the form editor is rendered, you could include a check against GFCommon::is_form_editor().

That sounds like a great idea but I had no idea if hiding a field would be possible. I currently just re-add the field if it doesn’t exist but it breaks older entries as the field ID no longer matches.

I don’t know where GF keeps the info it posts when saving edits on a form, but if a field isn’t rendered, will GF still keep it when saving?

Hmmm it seems like unsetting a form from the $form['fields'] array breaks the admin and the editor can no longer save. How would you go about hiding a field? I’m trying to see if I can add some CSS to the fields on the admin side of things but that doesn’t seem to be stored in the $form object.

Sorry for the triple reply but I figured something that will work for me and wanted to show the solution in case it helps someone else. I ended up going this route:

add_filter( 'gform_field_css_class', ( $classes, $field, $form ) {
    if( ! \GFCommon::is_form_editor() )
        return $classes;

    if( $field['inputName'] == 'YOUR_FIELD_NAME' ) {
        $classes .= ' hidden';

    return $classes;
}, 10, 3 );

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.