Muhammad Qasim Muhammad Qasim - 7 months ago 51
PHP Question

Drupal 7 FAPI- Adding form elements in validate or submit handlers

Is it possible to add additional form elements in the validate or submit functions in drupal 7 module? The following code works and image is displayed on the form:

function test1_form($form, &$form_state)
{
$form['image']=array(
'#markup'=>'<img src="sites/all/modules/create_ad/th.jpeg"><br/>', //replace with your own image path
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
}


but when I try to display image after submission in submit function like following, it doesn't work:

function test1_form($form, &$form_state)
{
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
}

function test1_form_submit($form,&$form_state)
{
$form['image']=array(
'#markup'=>'<img src="sites/all/modules/create_ad/th.jpeg"><br/>', //replace with your own image path
);
}


Any positive help is welcome. Thanks.

Answer

You could follow the multi-step form methodology to add additional fields to your form after submission.

Here is a blog post that talks about one approach for multi-step and can give you some insight.

Basically, on your submit function you store your values and set the form to be rebuilt. Then in your form function you check for those stored values and add the new fields if present.

Example:

<?php
function test1_form($form, &$form_state)
{
        if (isset($form_state['storage']['show-image'])){
            $form['image']=array(
                '#markup'=>'<img src="sites/all/modules/create_ad/th.jpeg"><br/>', //replace with your own image path
            );
        }

     $form['submit'] = array(
                 '#type' => 'submit',
                 '#value' => 'Submit',
     );
}

function test1_form_submit($form,&$form_state)
{
    $form_state['rebuild'] = TRUE;
    $form_state['storage']['show-image'] = true;
}
Comments