Drupal 7: Show fields on a form based on another field and a database lookup - forms

I have a form I created in a custom module using the Form API. It is a fairly basic form with only 4 fields. It basically signs a user up for a job alert system. We are basing it only by email address with a few search parameters. We want people to be able to setup a search agent quickly and anonymously meaning they will NOT be creating a Drupal user account as we don't want them to have to deal with a password etc. They will just put in their email address, check off a few preferences and we will save the data.
Now the issue I need to deal with is allowing the user to edit their preferences later on and/or unsubscribe. Again this is not high security and it doesn't need to be. What I would like to do is initially ask ONLY for their email address in the form and allow them to submit it. I would then check the database to see if we already have an entry for that email address and if so, display the pre-filled form for them to edit or unsubsribe, other wise just show them the blank form. So I am just trying to figure out the best way to go about this. I'm thinking I just have one form with all of the fields including email address, but somehow only display the other fields besides the email address after a successful call to the database. I'm just tripping up on how to accomplish this.
EDIT:
I'm wondering if I can use Drupal's AJAX functionality to accomplish this? I tried this, but I couldn't get it to work. I put an Ajax attribute on my submit button with a wrapper ID and a callback function. I created a form element in my form with blank markup and used a prefix and suffix that created a wrapper div with the ID I used in my AJAX parameter. Then I am thinking in my callback function I can do the database lookup and then return the form elements I need either pre-filled or not into the wrapper div that was created, but when I do this, the form does submit via AJAX and I get the spinning wheel, but no matter what I return in my callback, it does not appear in my output wrapper div. Am I going about this the right way? I also made sure I have $form_state['rebuild'] = TRUE; on my original form.
Here is what I tried and it didn't work.
/**
* Implements hook_form().
*/
function _vista_form($form, &$form_state) {
$form = array();
$form_state['rebuild'] = TRUE;
$form['email'] = array(
'#type' => 'textfield',
'#title' => 'Email',
'#required' => TRUE,
);
$form['render_area'] = array(
'#type' => 'markup',
'#markup' => '',
'#prefix' => '<div id="job-agent-form">',
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#attributes' => array('class' => array('submit')),
'#ajax' => array(
'callback' => '_display_form',
'wrapper' => 'job-agent-form',
'method' => 'replace',
'effect' => 'fade',
),
return $form;
}
function _display_form($form, &$form_state) {
// there are other form elements that would go here also, I just added two for example
$type_options = array(
'VISTA-HealthCare-Partners-Government' => 'Vista Healthcare Partners',
'International' => 'International Locum Tenens',
'Permanent' => 'Permanent Physician',
'US-Locum-Tenens' => 'US Locum Tenens',
);
$form['job_type'] = array(
'#type' => 'checkboxes',
'#multiple' => TRUE,
'#title' => 'Type of Job',
'#options' => $type_options,
'#empty_option' => 'Choose a placement type',
'#empty_value' => 'all',
//'#default_value' => $type_selected,
);
$form['active'] = array(
'#type' => 'checkbox',
'#title' => 'Subscribe/Unsubscribe',
'#default_value' => 1,
);
return $form;
}

I would go for creating all fields in the form than use hook_form_alter() to hide the unneeded ones with ['#access'] = FALSE.

Related

Additional Form submit button with redirection

I have added additional submit button on node create page via form_alter:
$form['check_data'] = array(
'#type' => 'submit',
'#access' => TRUE,
'#value' => 'Check',
'#validate' => array('node_form_validate'),
'#submit' => array('node_form_submit', 'custom_redirect'),
);
So the button now validates the form and saves the node, but it doesn't redirect it afterwards:
function custom_redirect($form, &$form_state) {
$form_state['redirect'] = 'node/%nid/check';
}
Any ideas how to redirect it after submission?
in _form_alter add the following:
$form['actions']['check_data']['#submit'][] = 'custom_redirect';
and/or check does form_state have nid and use it from there, like
$form_state['nid'], $form_state['redirect'] = 'node/' . $form_state['nid'] . '/check';

CakePHP FormHelper multiple select does not remember settings

In my form I have a input field with multiple checkboxes.
This works as expected.
When for some reason (eg an obligated field in the form is empty upon submit) the form after submit is not posted, all other fields maintain there input except the field below, all checkboxes become unchecked.
What can I do to make this field remember it's settings?
$options = array(
'1' => 'one',
'2' => 'two',
'3' => 'three'
);
echo $this->Form->input('checkboxes',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $options,
'default' => array(1,2,3)
));
FormHelper uses the $this->request->data to fill the fields. You need to keep (or fill) your data in request data array and the cakephp will maintain your data.

Example of Zend Form with Collection Element using Forms not Fieldsets in Zend Framework2

I need a straight forward working example how I can include a collection element in Zend Form, I have seen some examples from Zend Framework 2 site and from previous posts in StackOverflow where most of them pointed to this link. But right now I am not using Fieldsets and staying with Forms, so in case if someone can direct me in the right way, how I can include a simple collection element when the user gets a page where the user can choose multiple choices from the shown collection form. Much better would be populating the collection form from database.
I have searched in the internet for quite a sometime now and thought I would post here, so that Zend profis can give their suggestions.
Just For Information:
Normally one can include a static dropdownbox in Zend Form in this fashion
$this->add(
array(
'name' => "countr",
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => "Countries",
'options' => array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
)
)
)
);
So I am expecting a simple example which could give me a basic idea how this can be done.
To be honest, I don't see your problem here. Since form collections extend Fieldset which extends Element, you can just add it to the form as a regular element. The view helpers will take care of the rendering recursively.
Step 1: Create a form collection (create an instance of Zend\Form\Element\Collection). If the elements have to be added dynamically in some way, I'd create a factory class for this purpose.
Step 2: Add it to the form. (For example using $form->add($myCollectionInstance).)
Step 3: Render it. Zend\Form\View\Helper\Collection is a pretty good view helper to render the whole form without any pain.
You can also create a new class extending Zend\Form\Element\Collection and use the constructor to add the fields you need. Thus, you can add it to the form using the array you've pasted in your question. Also, you could directly use it in annotations.
Hope this helps.
If you just want to fill in a select list with option values you can add the array to the select list in a controller:
$form = new MyForm();
$form->get('countr')->setOptions(array('value_options'=>array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
the array can be fetched from db.
this is a different example for using form collections in the simplest way.
In this example it creates input text elements in a collection and fills them in. The number of elements depends on the array:
class MyForm extends \Zend\Form\Form
{
$this->add(array(
'type' => '\Zend\Form\Element\Collection',
'name' => 'myCollection',
'options' => array(
'label' => 'My collection',
'allow_add' => true,
)
));
}
class IndexController extends AbstractActionController
{
public function indexAction
{
$form = new MyForm();
$this->addElementsFromArray($form, array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
//the above line can be replaced if fetching the array from a db table:
//$arrayFromDb = getArrayFromDb();
//$this->addElementsFromArray($form, $arrayFromDb);
return array(
'form' => $form
);
}
private function addElementsFromArray($form, $array)
{
foreach ($array as $key=>$value)
{
$form->get('myCollection')->add(array(
//'type' => '\Zend\Form\Element\SomeElement',
'name' => $key,
'options' => array(
'label' => $key,
),
'attributes' => array(
'value' => $value,
)
));
}
}
}
index.phtml:
$form->setAttribute('action', $this->url('home'))
->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form->get('myCollection'));
echo $this->form()->closeTag();

Zend: Form validation: value was not found in the haystack error

I have a form with 2 selects. Based on the value of the first select, it updates the values of the second select using AJAX. Doing this makes the form not being valid. So, I made the next change:
$form=$this->getAddTaskForm(); //the form
if(!$form->isValid($_POST)) {
$values=$form->getValues();
//get the options and put them in $options
$assignMilestone=$form->getElement('assignedMilestone');
$assignMilestone->addMultiOptions($options);
}
if($form->isValid($_POST)) {
//save in the database
}else {
//redisplay the form
}
Basically, I check if it is valid and it isn't if the user changed the value of the first select. I get the options that populated the second select and populate the form with them. Then I try to validate it again. However this doesn't work. Anybody can explain why? The same "value was not found in the haystack" is present.
You could try to deactivate the validator:
in your Form.php
$field = $this->createElement('select', 'fieldname');
$field->setLabel('Second SELECT');
$field->setRegisterInArrayValidator(false);
$this->addElement($field);
The third line will deactivate the validator and it should work.
You can also disable the InArray validator using 'disable_inarray_validator' => true:
For example:
$this->add( array(
'name' => 'progressStatus',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'disable_inarray_validator' => true,
),
));
Additionaly you should add you own InArray Validator in order to protect your db etc.
In Zend Framework 1 it looks like this:
$this->addElement('select', $name, array(
'required' => true,
'label' => 'Choose sth:',
'filters' => array('StringTrim', 'StripTags'),
'multiOptions' => $nestedArrayOptions,
'validators' => array(
array(
'InArray', true, array(
'haystack' => $flatArrayOptionsKeys,
'messages' => array(
Zend_Validate_InArray::NOT_IN_ARRAY => "Value not found"
)
)
)
)
));
Where $nestedArrayOptions is you multiOptions and $flatArrayOptionsKeys contains you all keys.
You may also add options to select element before checking for the form validation. This way you are insured the select value is in range.

In Drupal 7, how do I show a new form that can edit data selected from a different form?

I have a tableselect form that lists several items. When a user selects one or more items, and clicks the edit button, I want a new form to show up that lets them edit the items.
I have the new form structure being generated, but I can't get it to show up after the edit button is clicked.
Currently, nothing seems to happen. I know that the tableselect form is being submitted correctly, and the function to create the edit term form is working correctly. I tested it with drupal_set_message and var export.
So, how do I get the new form to show?
Here is my relevant code:
/**
* Generate form for listing terms
*/
function markit_form_terms_list()
{
$form = array();
$form['terms'] = array(
'#type' => 'fieldset',
'#title' => t('List of Terms'),
);
$header = array(t('Name'), t('ID'), t('SetID'));
$form['terms']['items'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#title' => t('Terms'),
'#options' => markit_get_array_terms(),//drupal_map_assoc($header, 'markit_get_array_terms'),
'#tree' => TRUE,
);
$form['terms']['submit'] = array(
'#type' => 'submit',
'#value' => t('Edit Term'),
'#submit' => array('markit_form_terms_list_submit'),
);
/*$form['terms']['delete'] = array(
'#type' => 'submit',
'#value' => t('Delete Term'),
'#submit' => 'markit_form_terms_delete'
);*/
return $form;
}
/**
* Generate form to edit the terms.
* #param <type> $form
* #param <type> $form_state
* #return string
*/
function markit_form_term_edit($form, $form_state)
{
$newform = array();
$newform['termstoedit'] = array(
'#type' => 'fieldset',
'#title' => t('Edit Term/s'),
);
foreach($form_state['values']['items'] as $row)
{
if($row!=0)//if a row is not selected, it will be 0. So don't select rows equal to 0.
{
$terminfo = markit_get_markterms($row);
drupal_set_message(var_export($terminfo,true));//['term_name']);
drupal_set_message($terminfo[0]['term_name']);
$newform['termstoedit'][$terminfo[0]['term_id']] = array(
'#type' => 'textfield',
'#title' => t('Term:'),
'#default_value' => $terminfo[0]['term_name'],
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
);
}
}
$newform['termstoedit']['submit'] = array(
'#type' => 'submit',
'#value' => t('Edit Term'),
'#submit' => array('markit_form_term_edit_submit'),
);
drupal_set_message(var_export($newform,true));
return $newform;
}
function markit_form_terms_list_submit($form,$form_state)
{
drupal_set_page_content(drupal_build_form('markit_form_term_edit', $form_state));
}
I believe I am not using the correct code in the markit_form_terms_list_submit function. I've tried several different things, but it hasn't worked yet. And the Google searches I've done haven't helped either. I also have searched the Drupal API and Drupal Form API sites extensively.
Anyway, I think that's all the info you might need in order to help me. Thanks in advance!
I believe you may have better luck if you have one form function with differing fields being shown depending on the output.
If you do this you will even be able to use the form ajax methods to auto update your form.
Have a look at this howto to see if you think the approach will work for you.