I'm on hook_form_alter
for the config edit form. The code runs for all fields, but it's critical that the code figures out the name of the field it is on.
When I load the formobject, I can see the field_name
perfectly when I print_r
the array. But I can't figure out how to pull it out. Something like $name=$field['field_name']
The field name is 'field_plan_purpose' I need to get that in a variable in the code.
My code minus all of things I've tried:
$field = $form_state->getFormObject()->getEntity();
print '<pre>';
print_r($field);
print '</pre>';
Here is the top part of the array that gets printed:
Drupal\field\Entity\FieldConfig Object
(
[deleted:protected] =>
[fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
(
[id:protected] => node.field_plan_purpose
[field_name:protected] => field_plan_purpose <--- HOW DO I GET THIS
[entity_type:protected] => node
[type:protected] => text_long
[module:protected] => text
[settings:protected] => Array
(
)
[cardinality:protected] => 1
[translatable:protected] => 1
[locked:protected] =>
[persist_with_no_fields:protected] =>
[custom_storage] =>
[indexes:protected] => Array
(
)
[deleted:protected] =>
[schema:protected] =>
[propertyDefinitions:protected] => Array
(...
As you can see, 'field_name' is in there. Does anyone know how I can pull that out and reference it directly?
A few things I've tried:
// print_r($field->getEntityKey('#field_name'));
// getEntityType()->getKey('field_name')
// $field['field_name'] $field['field_name:protected']
// $field['id']
// $field->getKey('field_name')
// $field->definition['field_name'];
// print_r($field->definition);
EDITED ******* SOLUTION
/**
* Implements hook_form_alter().
*/
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$field = $form_state->getFormObject()->getEntity();
$field_name = $field->getName();
print $field_name;
}