DBTNGExampleAddForm.php
2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* @file
* Contains \Drupal\dbtng_example\DBTNExampleAddForm
*/
namespace Drupal\dbtng_example;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Simple form to add an entry, with all the interesting fields.
*/
class DBTNGExampleAddForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormID() {
return 'dbtng_add_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = array();
$form['message'] = array(
'#markup' => $this->t('Add an entry to the dbtng_example table.'),
);
$form['add'] = array(
'#type' => 'fieldset',
'#title' => t('Add a person entry'),
);
$form['add']['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#size' => 15,
);
$form['add']['surname'] = array(
'#type' => 'textfield',
'#title' => t('Surname'),
'#size' => 15,
);
$form['add']['age'] = array(
'#type' => 'textfield',
'#title' => t('Age'),
'#size' => 5,
'#description' => t("Values greater than 127 will cause an exception. Try it - it's a great example why exception handling is needed with DTBNG."),
);
$form['add']['submit'] = array(
'#type' => 'submit',
'#value' => t('Add'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Confirm that age is numeric.
if (!intval($form_state->getValue('age'))) {
$form_state->setErrorByName('age', $this->t('Age needs to be a number'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Gather the current user so the new record has ownership.
$account = \Drupal::currentUser();
// Save the submitted entry.
$entry = array(
'name' => $form_state->getValue('name'),
'surname' => $form_state->getValue('surname'),
'age' => $form_state->getValue('age'),
'uid' => $account->id(),
);
$return = DBTNGExampleStorage::insert($entry);
if ($return) {
drupal_set_message(t('Created entry @entry', array('@entry' => print_r($entry, TRUE))));
}
}
}