Score:-2

Form submission field not available in form action

in flag

I have the following form submission handler.

function mymod_form_submit(&$form, FormStateInterface $form_state) {
  $ka_selected = $form_state->getValue('ka_types');
  \Drupal::state()->set('ka_types', $ka_selected);
  return $ka_selected;
}

It returns the ka_types field value. I want to use $ka_selected in custom action code.

public function execute(ContentEntityInterface $entity = NULL) {
    //Read all the fields from entity
    $comment = $entity->get('comment_body')->getValue();
    $file_uri = file_create_url($entity->field_attachment->entity->getFileUri());
    $file_name = $entity->field_attachment->entity->getFileName();
    $ka = $entity->ka_selected->entity->getValue(); **//error thrown here**
    dd($ka);
}

I am able to read other view entities but not just this field.

How can I use the value of $ka_selected in my custom action?

Rainer Feike avatar
in flag
Could you please clarify - I think there's no hook_form_submit in Drupal 9? And why do you store your value in a state and later expect it in the entity?
Jiah avatar
in flag
Drupal 9 has hook_form_submit and I can dump the selected values there perfectly. Just those values are not getting passed on to the execute method in the custom action
apaderno avatar
us flag
Drupal has never used [`hook_form_submit()`](https://api.drupal.org/api/drupal/9.1.x/search/hook_submit_form). A form submission handler isn't a hook. What stored in a form element isn't necessarily an entity field. I could use add a form element in an entity edit form and its value won't end in an entity field.
apaderno avatar
us flag
Also, a form submission handler doesn't return any value. Even if it were to return a value, that value would be discarded from Drupal.
Score:0
in flag

Alright, I am able to figure out the answer from the below link: https://www.drupal.org/forum/support/module-development-and-code-questions/2021-07-04/read-view-row-entities-and-create-a#comment-14154305

public function execute(ContentEntityInterface $entity = NULL) {
    //Read all the fields from entity
    $comment = $entity->get('comment_body')->getValue();
    $file_uri = file_create_url($entity->field_attachment->entity->getFileUri());
    $file_name = $entity->field_attachment->entity->getFileName();
    $ka = \Drupal::state()->get('ka_types');
    dd($ka);
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.