我在Drupal 8中创建了List(文本)类型的字段“汽车”
0|Lambo
1|MER
2|BMW
3|Aston
4|Range Rover
5|Limo
我已选择“-无-” 作为默认值,并且我没有通过单击drupal编辑设置中的复选框来将此字段设为必填字段,我希望通过JQuery将该字段设为必填字段。
我尝试了Jquery代码:-
jQuery('#edit-field-secondary-waste-type').prop('required', true);
预期结果是必须填写该字段,但实际上该字段不起作用,并且表单以默认值“无” 保存。
答案 0 :(得分:1)
这是答案:-
重要说明-我们没有在字段设置中使用Drupal8的内置必需复选框字段,因为在这里我们讨论的是辅助表单,该表单默认情况下是隐藏的,并在某些情况下显示。
所以
在Drupal8中,可以使用JQuery方法来设置“文本”字段,但“选择”字段和“上传文件”与jQuery不兼容。
这是解决方案之一:-
您可以让他们在“验证”功能中检查验证
这是我的代码:-
在要与您的字段名称一起放置的代码字段名称中,例如,我使用了随机值
public static function node_content_type_xyz_form_validate(array $form, FormStateInterface $form_state){
$primary = $form_state->getValue('field_name')[0]['value'];
$reset_text_fields=[];
//in my case this was the condition**
if($primary < 4){
$form_state->setValue('field_secondary_waste_type',$reset_text_fields);
}
// here is the validation**
else{
$empty=[];
$value_of_secondary_waste_type = $form_state->getValue('field_secondary_waste_type')[0]['value'];
if($value_of_secondary_waste_type == null){
$form_state->setErrorByName('field_secondary_waste_type', t('Secondary Waste Type is required.'));
}
if(($value_of_secondary_waste_type == 1) || ($value_of_secondary_waste_type == 2) || ($value_of_secondary_waste_type == 3 ) || ($value_of_secondary_waste_type == 5)){
$value_of_pcpg = $form_state->getValue('field_secondary_pcpg_facility_ty')[0]['value'];
if($value_of_pcpg == null) {
$form_state->setErrorByName('field_secondary_pcpg_facility_ty', t('Secondary Facility Type is required.'));
}
}
if($value_of_secondary_waste_type == 0){
$value_of_residual = $form_state->getValue('field_secondary_residual_facilit')[0]['value'];
if($value_of_residual == null ){
$form_state->setErrorByName('field_secondary_residual_facilit', t('Secondary Facility Type is required.'));
}
}
if($value_of_secondary_waste_type == 4){
$metal = $form_state->getValue('field_secondary_metal_facility_t')[0]['value'];
if($metal == null){
$form_state->setErrorByName('field_secondary_metal_facility_t', t('Secondary Facility Type is required.'));
}
}
$variable= $form_state->getValue('field_secondary_permit_pdf')[0]['fids'];
if($value_of_secondary_upload_permit == $empty){
$form_state->setErrorByName('field_xyz', t('Secondary Permit PDF is required.'));
}
}
}
谢谢 库沙尔·阿格劳瓦尔(Kushal Agrawal) kushalagrawal.1996@gmail.com