I need to change the label of a custom content type programmatically. I've looked around but I couldn't find a solution. This is my custom form:

class GroupContentForm extends ContentEntityForm {

   * {@inheritdoc}
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

    $entity->set('label', 'kkkkk');
    $status = parent::save($form, $form_state);

    $form_state->setRedirect('entity.group_content.canonical', ['group_content' => $entity->id()]);


What do I need to do to change the label? $entity->set('label', 'kkkkk'); causes an error as the field label doesn't exists, the same happens with title and _title


It's not clear what entity type you have. In the question you ask for the label of a content type, which would be the entity node, then the label field is title. In the question title it is a more general question about the label of an entity and in the code you redirect to a group_content entity route, which would suggest this is another entity type.

In this case, if you don't know the entity type, you could use this generic code to get the label field name and set the label with it:

$label_field = $entity->getEntityType()->getKey('label');
$entity->set($label_field, 'New label');

How about using hook_entity_presave?

 * Implements hook_entity_presave().
function MY_CUSTOM_MODULE_entity_presave(EntityInterface $entity) {
  $type = $entity->getEntityTypeId();
  if ($type == 'node') {
    // Add more logic based on your needs.
    $entity->set('title', 'kkkkk');
  • I think that set the titles for all nodes, I only need it in my custom form. – Nicola Peluchetti Sep 14 at 18:30
  • Yes, you need to define the specific content type in code. If you want to just alter the form label and not to alter the title of actual entity, them hook_form_alter() might be better way. – KalleVu Sep 14 at 19:04

If you are trying to update a node you can use setTitle(), like this:

$entity->setTitle('My custom title');

For other entity types you can use:

$entity->setLabel('My custom title');

I also see that you don't save the entity, make sure to save the entity after setting the title:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.