Validazione di un form Drupal 7
Sto creando per la prima volta un modulo e all'interno sto mettendo un form. Voglio farci la validazione.
Non capisco perche' non mi funziona. Dove sbaglio?
<?php
// $Id$
/**
* Implements hook_help().
*/
function findacontractor_help($section='') {
$output .= t('findacontractor_help');
return $output;
}
/**
* Implements hook_menu().
*/
function findacontractor_menu() {
$items['findacontractor-page'] = array(
'title' => 'Find a Contractor',
'page callback' => 'findacontractor_page',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_page().
*/
function findacontractor_page() {
return drupal_get_form('findacontractor_myform');
}
function findacontractor_myform($form_state) {
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#size' => 30,
'#maxlength' => 64,
'#description' => t('Enter the name for this group of settings'),
);
// Acknowledgement
$form['disclaimer'] = array(
'#type' => 'checkbox',
// '#id' => 'disclaimer',
'#name' => 'disclaimer',
'#title' => t('I have read and Acknowledged the Bradford White Disclaimer.'),
'#description' => t(''),
);
// Address
$form['address'] = array(
'#type' => 'textfield',
// '#id' => 'address',
'#name' => 'address',
'#title' => t('Address (optional)'),
'#size' => 26,
'#maxlength' => 100,
'#required' => FALSE,
'#description' => t(''),
);
// City
$form['city'] = array(
'#type' => 'textfield',
// '#id' => 'city',
'#name' => 'city',
'#title' => t('City (required)'),
'#size' => 18,
'#maxlength' => 50,
'#attributes' => $onchange_array,
//'#required' => TRUE,
'#description' => t(''),
);
// State
$state = drupal_map_assoc(
array('Select One', 'ALBERTA', 'AK', 'AL', 'AR', 'AZ', 'BRITISH COLUMBIA', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MANITOBA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NEW BRUNSWICK', 'NEWFOUNDLAND', 'NH', 'NJ', 'NM', 'NOVA SCOTIA', 'NV', 'NY', 'OH', 'OK', 'OR', 'ONTARIO', 'PA', 'PRINCE EDWARD ISLAND', 'QUEBEC', 'RI', 'SASKATCHEWAN', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WI', 'WV', 'WY')
);
$form['state'] = array(
'#type' => 'select',
// '#id' => 'state',
'#name' => 'state',
'#title' => t('State (required)'),
'#default_value' => variable_get('Select One', ""),
'#options' => $state,
//'#required' => TRUE,
'#description' => t(''),
);
// Zip code
$form['zip'] = array(
'#type' => 'textfield',
// '#id' => 'zip',
'#name' => 'zip_code',
'#title' => t('Zip Code (required)'),
'#size' => 7,
'#maxlength' => 7,
//'#required' => TRUE,
'#description' => t(''),
);
// longitude
$form['longitude'] = array(
'#type' => 'hidden',
'#name' => 'longitude',
'#value' => '',
);
// latitude
$form['latitude'] = array(
'#type' => 'hidden',
'#name' => 'latitude',
'#value' => '',
);
// submitbutton
$form['submitbutton'] = array(
'#type' => 'submit',
// '#id' => 'submitbutton',
'#name' => 'submit',
'#title' => t('submitbutton'),
'#value' => t('Find Nearby Contractors'),
'#description' => t(''),
);
$form['#validate'][] = 'findacontractor_myform_validate';
return $form;
}
function findacontractor_myform_validate($form, &$form_state) {
if ($form_state['values']['name'] == '') {
form_set_error('', t('You must select a name for this group of settings.')
);
}
}
Risposte
o meglio, credo che funzioni
o meglio,
credo che funzioni ma non mi scrive
You must select a name for this group of settings.
Il codice funziona. Puoi
Il codice funziona. Puoi decommentare la riga
$form['#validate'][] = 'findacontractor_myform_validate';non serve in quanto Drupal cerca di default le funzioni [FORM_ID]_validate e [FORM_ID]_submit.
OK, innanzitutto grazie per
OK, innanzitutto grazie per la risposta.
Credo di aver capito. Ma rimangono dei dubbi.
ho tolto:
$form['#validate'][] = 'findacontractor_myform_validate';perche' in effetti non serve.
Io pero' vorrei che da qualche parte uscisse la frase
"You must select a name for this group of settings."
che pero' non appare. Come faccio a farla apparire?
ho "debuggato" in questa maniera:
function findacontractor_myform_validate($form, &$form_state) {
if ($form_state['values']['name'] == '') {
form_set_error('', t('You must select a name for this group of settings.'));
echo("test");
}
}
function findacontractor_myform_submit($form, &$form_state) {
drupal_set_message(t('Your form has been saved.'));
echo("testSubmit");
}
infatti "test" compare, che significa che come dici tu viene richiamato. Solo che non scrive la frase.
Mentre con il submit non compare "testsubmit". Li' faccio qualche errore?
La hook_page la faccio bene? Faccio bene a richiamare solo la form?
Mi viene un dubbio; se ad
Mi viene un dubbio; se ad esempio inserisci:
function findacontractor_page() {drupal_set_message('Questo messaggio si vede?');
return drupal_get_form('findacontractor_myform');
}
quando visiti la pagina del form, vedi un messaggio?
Se no, controlla che nel tuo tema (page.tpl.php) sia stampata la variabile $messages.
Il submit viene eseguito solo se la funzione di validazione non restituisce errori e subito dopo effettua una redirezione (a meno che $form_state['redirect'] non sia settato FALSE): per questo non riesci a vedere il buffer di output a cui è stato inviato l'echo.
Non leggo 'Questo messaggio
Non leggo 'Questo messaggio si vede?'
page.tpl.php del mio modulo?
e $form_state['redirect'] dove si trova?
Il file page.tpl.php è
Il file page.tpl.php è all'interno della directory del tuo tema. Controlla che da qualche parte ci sia un'istruzione del genere:
<?phpprint $messages;
?>
se non c'è prova ad aggiungerla e riprova. $form_state è il secondo argomento passato alla funzione di submit.
Sono un po' confuso. Non ho
Sono un po' confuso.
Non ho trovato print $messages; da nessuna parte e se provo a metterlo mi da errore.
1) siccome il thema e' complesso ed anche per motivi di usabilita'
potrei mettere print $messages; in un file tpl.php del mio modulo?
Se si come si fa'?
2) come si fa ad impostare $form_state?
ho seguito questo link http://drupal.org/node/751826 ma non trovo la spiegazione da nessuna parte.
Grazie ancora
Altra domanda: a cosa serve
Altra domanda: a cosa serve // $Id$ ? Cosa rappresenta esattamente?
adesso sto facendo un passo
adesso sto facendo un passo in piu'
Nella parte verde
•Questo messaggio si vede?
•Your form has been saved.
•Questo messaggio si vede?
Nella parte rossa
Error message
•Warning: Missing argument 1 for t(), called in D:\WebServer\sites\all\modules\findacontractor\findacontractor.module on line 69 and defined in t() (line 1406 of D:\WebServer\includes\bootstrap.inc).
•Notice: Undefined variable: string in t() (line 1426 of D:\WebServer\includes\bootstrap.inc).
•Notice: Undefined variable: string in t() (line 1434 of D:\WebServer\includes\bootstrap.inc).
•Warning: Missing argument 1 for t(), called in D:\WebServer\sites\all\modules\findacontractor\findacontractor.module on line 69 and defined in t() (line 1406 of D:\WebServer\includes\bootstrap.inc).
•Notice: Undefined variable: string in t() (line 1426 of D:\WebServer\includes\bootstrap.inc).
•Notice: Undefined variable: string in t() (line 1434 of D:\WebServer\includes\bootstrap.inc).
Che significa?
Scusami l'invazione del
Scusami l'invazione del forum, ho risolto il problema dei messaggi.
sotto city avevo messo
'#description' => t(),
invece di
'#description' => t(''),
come ti ho riportato. Non so come mai
Vediamo un pò: 1) $messages è
Vediamo un pò:
1) $messages è una variabile che il sistema mette a disposizione e che utilizzano tutti i temi per mostrare i messaggi. L'usabilità può essere migliorata magari scegliendo opportunamente la posizione e la formattazione dell'elemento.
2) $form_state['redirect'] può essere impostato all'interno della funzione di sumbit del form, settandolo o ad un url specifico o a FALSE per impedire la redirezione.
3) l'elemento // $Id$ veniva utilizzato dal repository CVS e rimpiazzato con la versione del codice e l'utente che effettuava il commit. E' un elemento obsoleto con il passaggio del repository di Drupal a GIT.
ps ti conviene eliminare tutti i riferimenti a '#description' => t('') se non usi descrizioni da tradurre per l'elemento.
Grazie, funziona tutto e ora
Grazie, funziona tutto e ora capisco.
Ho un altra domanda che penso continui questo argomento:
come si usa
function theme_findacontractor_myform($form) {drupal_set_message(t('Your theme works'));
}
la scritta Your theme works non appare.
Esattamente vorrei definire l'html fra i campi ma nache il resto della pagina che non contiene solo la form.
Qual'e' la strada migliore?
se ho capito bene dal tuo
se ho capito bene dal tuo punto 2) per mostrare i risultati dovrei fare cosi':
/**
* Implements hook_menu().
*/
function findacontractor_menu() {
$items['findacontractor-page'] = array(
'title' => 'Find a Contractor',
'page callback' => 'findacontractor_page',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['findacontractorresults-page'] = array(
'title' => 'Show Contractors',
'page callback' => 'findacontractor_results_page',
'access arguments' => array('show content'),
'type' => MENU_CALLBACK,
);
return $items;
}
oltre che
function findacontractor_myform_submit($form, &$form_state) {$form_state['redirect'] = "findacontractorresults-page";
}
e quindi
function findacontractor_results_page() {return "Hello, World!";
}
solo che mi da
The requested page could not be found.
Il redirect funziona, quindi immagino che il problema sia nell' hook_menu().
Dove sbaglio?
Prova a cambiare l'access
Prova a cambiare l'access argument da array('show content') a array('access content'). Poi ogni volta che modifichi un elemento dell'hook_menu ricordati di ripulire la cache di sistema.
Quando dici la cache di
Quando dici la cache di sistema intendi ripulire la cache del browser, giusto?
dunque mi sto intoppando. Non
dunque mi sto intoppando. Non ho mai trovato cosi' difficile affrontare una nuova piattaforma.
ti ripropongo il codice:
<?php
// $Id$
/**
* Implements hook_help().
*/
function findacontractor_help($section='') {
$outputHelp = t('findacontractor_help');
return $outputHelp;
}
/**
* Implements hook_perm().
*/
function findacontractor_perm() {
return array('access content');
}
/**
* Implements hook_theme().
*/
function findacontractor_theme() {
return array(
'findacontractor_form' => array(
'arguments' => array('form' => NULL),
)
);
}
/**
* Implements hook_menu().
*/
function findacontractor_menu() {
$items['findacontractor-page'] = array(
'title' => 'Find a Contractor',
'page callback' => 'findacontractor_page',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['findacontractorresults-page'] = array(
'title' => 'Show Contractors',
'page callback' => 'findacontractor_results_page',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_page().
*/
function findacontractor_page() {
return drupal_get_form('findacontractor_myform');
}
function findacontractor_results_page() {
return "Hello!";
}
function findacontractor_myform($form_state) {
// Acknowledgement
$form['disclaimer'] = array(
'#type' => 'checkbox',
'#id' => 'disclaimer',
'#name' => 'disclaimer',
'#title' => t('I have read and Acknowledged the Bradford White Disclaimer.'),
);
// Address
$form['address'] = array(
'#type' => 'textfield',
'#id' => 'address',
'#name' => 'address',
'#title' => t('Address (optional)'),
'#size' => 26,
'#maxlength' => 100,
'#required' => FALSE,
);
// City
$form['city'] = array(
'#type' => 'textfield',
'#id' => 'city',
'#name' => 'city',
'#title' => t('City (required)'),
'#size' => 18,
'#maxlength' => 50,
);
// State
$state = drupal_map_assoc(
array('Select One', 'ALBERTA', 'AK', 'AL', 'AR', 'AZ', 'BRITISH COLUMBIA', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MANITOBA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NEW BRUNSWICK', 'NEWFOUNDLAND', 'NH', 'NJ', 'NM', 'NOVA SCOTIA', 'NV', 'NY', 'OH', 'OK', 'OR', 'ONTARIO', 'PA', 'PRINCE EDWARD ISLAND', 'QUEBEC', 'RI', 'SASKATCHEWAN', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WI', 'WV', 'WY')
);
$form['state'] = array(
'#type' => 'select',
'#id' => 'state',
'#name' => 'state',
'#title' => t('State (required)'),
'#default_value' => variable_get('Select One'),
'#options' => $state,
);
// Zip code
$form['zip'] = array(
'#type' => 'textfield',
'#id' => 'zip',
'#name' => 'zip',
'#title' => t('Zip Code (required)'),
'#size' => 7,
'#maxlength' => 7,
);
// latitude
$form['latitude'] = array(
'#type' => 'hidden',
'#name' => 'latitude',
'#value' => '',
);
// longitude
$form['longitude'] = array(
'#type' => 'hidden',
'#name' => 'longitude',
'#value' => '',
);
// submitbutton
$form['submitbutton'] = array(
'#type' => 'submit',
'#id' => 'submitbutton',
'#name' => 'submit',
'#title' => t('submitbutton'),
'#value' => t('Find Nearby Contractors'),
);
return $form;
}
function theme_findacontractor_myform($form) {
$form['disclaimer']['#description'] = t('Ciao');
$output = drupal_render($form);
return $output;
}
function findacontractor_myform_validate($form, &$form_state) {
if ($form_state['values']['disclaimer'] != 1) {
form_set_error('', t('Please read the Bradford White Disclaimer, then check that you have Acknowledged it.'));
}
if (Trim($form_state['values']['city']) == NULL) {
form_set_error('', t('Please enter your City.'));
}
if ($form_state['values']['state'] == 'Select One') {
form_set_error('', t('Please select your State.'));
}
if (Trim($form_state['values']['zip']) == NULL) {
form_set_error('', t('Please enter your Zip Code.'));
}
}
function findacontractor_myform_submit($form, &$form_state) {
$form_state['redirect'] = "findacontractorresults-page";
$disclaimer = $form_state['values']['disclaimer'];
$address = Trim($form_state['values']['address']);
$city = $form_state['values']['city'];
$state = $form_state['values']['state'];
$zip = $form_state['values']['zip'];
$output = "";
$output .= "disclaimer " . $disclaimer . " ";
$output .= "address " . $address . " ";
$output .= "city " . $city . " ";
$output .= "state " . $state . " ";
$output .= "zip " . $zip . " ";
$output .= t('the form was submitted successfully');
drupal_set_message($output);
}
non funzionano:
1) findacontractorresults-page, in quanto mi da The requested page could not be found.
2) non funziona il thema.
Mi puoi dare una mano a capirci meglio? Fondamentale e' il punto 1 altrimenti non posso andare avanti ma anche il 2 e' importante.
Grazie, e scusami per il disturbo
Ciao, allora: + per la cache
Ciao, allora:
+ per la cache intendo quella del sito, la puoi pulire cliccando su "Svuota tutte le cache" in Amministrazione » Configurazione » Sviluppo » Prestazioni
+ (1) sicuro dipende dalla cache interna, il codice mi pare scritto bene. Drupal salva nella cache interna i path creati dai moduli, all'attivazione del modulo o forzando il flush della cache stessa. Se aggiungi un path dopo l'attivazione del modulo, prima di usarlo devi fare questa operazione.
ps in function findacontractor_myform_submit($form, &$form_state) manca il redirect $form_state['redirect'] = 'findacontractorresults-page';
+ (2) in findacontractor_theme() l'id del tuo form è findacontractor_myform e non findacontractor_form, prova:
function findacontractor_theme(){return array(
'findacontractor_myform' => array(
'arguments' => array('form' => NULL),
);
}
Aggiornamento: ora che ho
Aggiornamento:
ora che ho disabilitato la cache funziona (1). Mi domando come si recuperano i valori disclaimer etc... ?
Pensavo che lo facesse con
$disclaimer = $form_state['values']['disclaimer'];
in
function findacontractor_results_page
invece niente.
2) continua a non funzionare :(
Scusate come si fanno a
Scusate come si fanno a recuperare i valori in findacontractor_results_page?
In pratica io vorrei che una volta fatto il submit i valori venissero ripresi e mostrati su una nuova pagina usando il metodo post. Credo che sia la strada migliore, ma se qualcuno ha un idea migliore puo' dirmela?
nessuno mi risponde :(
nessuno mi risponde :(
Comunque blackice78 grazie,
Comunque blackice78 grazie, puoi considerare risolto. Sposto su un altro post
Ciao, purtroppo riesco a
Ciao, purtroppo riesco a risponderti solo ora. La variabile $form_state è visibile nelle funzioni di validazione e submit. Un metodo potrebbe essere salvare i dati su db e poi estrarli in findacontractor_results_page.