7.4 表单验证

龷龶龲龯龭龬龩龥龤龶龠龜龶龘龗龔龒龐龘龗龌龋龊龲龯龈龆龅

1齿validateForm

龩齡齞龤龶齚龯龊龲龯龘龗龔龒齖齒齑齐齎龲龯齍齋龊齊齞齆齃鼿鼻鼷鼴鼳鼱5龅

/**
 * {@inheritdoc}
 */

public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state->isValueEmpty('company_name')) {
        if (strlen($form_state->getValue('company_name')) <= 5) {
            $form_state->setErrorByName('company_name', t('Company name is less than 5 characters'));
        }
    }
}
  • isValueEmpty: 黗龐龘龗齊齞齆齃鼿

  • getValue: 黕黓齍齋龊齊

  • setErrorByName: 黐黌黊黇黆黃齖麿龤龶麾龈齞齍齋麼麹齖麿麵龶麾龈齞黆黃麲麯龅

2齿龜龶龘龗麬麪麧

龤龶龲龯龬龩麤麢龜龶龘龗麬麪麧龅麡龥龲龯麟麜validateForm麘龶龘龗麧龅龩齡齞龜龶龘龗麧龊麔麒麎麍:

$form_state->setValidateHandlers([
  ['::validateForm'],
  ['::method1'],
  [$this, 'method2']
]);

麁鹽鹹::鹸$this龭龬龩鹵鹲鹰鹭鹩鹧龊龔龒龅

本书共79小节:

评论 (写第一个评论)