Created
August 8, 2023 03:41
-
-
Save flashvnn/9072f8bf7505954d07ca1cfbd7ec6ad4 to your computer and use it in GitHub Desktop.
Ajax callback select2, radios field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\nh_phahe\Service; | |
use Drupal\Component\Utility\NestedArray; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Core\StringTranslation\StringTranslationTrait; | |
use Drupal\node\Entity\Node; | |
/** | |
* Form service support. | |
* | |
* @package Drupal\nh_phahe\Service | |
*/ | |
class FormService { | |
use StringTranslationTrait; | |
public function registerFormAlter(&$form, FormStateInterface $form_state) { | |
$options = []; | |
$field_ten_cha = $form_state->getValue('field_ten_cha'); | |
if ($field_ten_cha && $reference_id = NestedArray::getValue($field_ten_cha, [ | |
'0', | |
'target_id', | |
])) { | |
$query = \Drupal::entityQuery('node')->condition('type', 'pha_he'); | |
$query->condition('field_ten_cha', $reference_id); | |
$node_ids = $query->execute(); | |
$nodes = Node::loadMultiple($node_ids); | |
foreach ((array) $nodes as $node) { | |
$options[$node->id()] = $node->label(); | |
} | |
} | |
$form['con_fieldset'] = [ | |
'#type' => 'fieldset', | |
'#tree' => FALSE, | |
'#title' => $this->t('Danh sách con'), | |
'#prefix' => '<div id="phahe_con_wrapper">', | |
'#suffix' => '</div>', | |
]; | |
$form['con_fieldset']['con'] = [ | |
'#type' => 'radios', | |
'#required' => FALSE, | |
'#options' => $options, | |
]; | |
$form['field_ten_cha']['widget']['#ajax'] = [ | |
'callback' => [self::class, 'ajaxCallback'], | |
'wrapper' => 'phahe_con_wrapper', | |
'event' => 'select2:close', | |
]; | |
// Attach library | |
// $form['#attached']['library'][] = 'nh_phahe/register'; | |
} | |
public static function ajaxCallback($form, FormStateInterface $form_state) { | |
return $form['con_fieldset']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment