I’d like to ask how can I do some code before I build the form in Drupal 7?
Before defining a form I’d like to perform some code(I want to build an object), How can I do it?
The code i want to perform:
if (isset($_GET["team"])){$team = $_GET["team"];} else {$team=1; };
$myteam = new Team($team);
I define the form:
function teamform_nameform() {
$form['editteam']['team_city'] = array(
'#title' => t('Team city'),
'#type' => 'textfield',
'#description' => t(''),
'#required' => TRUE,
'#default_value' =>**$myteam->returnCity()**,
'#size' => 30,
);
$form['editteam']['submitContentChanges'] = array(
'#type' => 'submit',
'#value' => t('Save changes'),
'#submit' => array('teamform_editteam_submitContentChanges'),
);
}
I tried to use the following hook, but it doesn’t work. (i still can’t get access to variable $team and to the object $myteam (it’s written that they are undefined))
/**
* Implements hook_form_alter().
*/
function teamform_form_alter(&$form, &$form_state, $form_id) {
global $team;
if (isset($_GET["team"])){$team = $_GET["team"];} else {$team=2;};
global $myteam
$myteam = new Team($team);
}
$team is the team id which i get using method GET or if it’s not set than i assign the default value. $myteam is a object which i build based on the team_id.
Than I’d like to get access to the object in the function teamform_nameform(). In this function i use method returnCity() in order to return the city which the team belongs to; as a default value.
Than I’d like to make changes with the object. Specifically, when the user changes the city of the team and click submit button then i want to update the city in the object $myteam. Therefore i use the function:
function teamform_editteam_submitContentChanges($form, &$form_state){
$team_city=$form_state['values']['team_city'];
$myteam->updateTeamCity($team_city); //i got the error here. it's said that $myteam is undefined!
}
It looks like you want an object to persist across page loads, does that sound right? If that’s the case, you can store it in the session. Try something like this: