5

I'm trying to change the submit button text "Save and keep published", but with no luck. I'm using the standard hook_form_FORM_ID_alter().

function mymodule_form_node_news_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // This is the problem, what should I put here
  $form['actions']['publish']['#value'] == '';
}

This is what dpm() returns.

'publish' => array(7)
  '#value' => object Drupal\Core\StringTranslation\TranslatableMarkup(5)
    protected string -> string(18) "Save and keep published"
    protected translatedMarkup -> NULL
    protected options -> array(0)
    protected stringTranslation -> NULL
    protected arguments -> array(0)

How do I change text on the submission button in the node form?

  • $request = \Drupal::request() ; $url= Url::createFromRequest($request); if(isset($url->getRouteParameters()['node'])){ $form['submit']['#value'] = t('Search'); } – harsh_behl_0007 Apr 23 '16 at 8:37
10

In #value is a translatable string. You can override it with a simple text value:

if ( isset($form['actions']['publish']) ) {
   $form['actions']['publish']['#value'] = 'New Text';
}

Or you can put there a new translatable string with the t() function, if you want to translate the new string in different languages:

if ( isset($form['actions']['publish']) ) {
   $form['actions']['publish']['#value'] = t('New Text');
}

Edit: Answer the question in comments

What you see in dpm() is the result of t(), which is used in the original form in NodeForm.php:

$element['publish']['#value'] = t('Save and publish');

In D8 this is an object, which will result in the translated text when used in a string context. For the enduser you simply use it like a string value, but magically it will always be translated. You don't have to look into this object to find a way to change it. To set a new value you simply generate a new translatable object and put this into the place of the old one.

  • Thank you. I knew that this a proper way to that in D7, but I never thought it applies also to D8 because of those methods. Could you shed some light to those protected methods that appears in dpm()? Why this string was overriden in "string" method, but not eg. the translatedMarkup? What about the other methods? What if I'd like to override arguments for example? What should be the proper syntax? – David Apr 26 '16 at 10:36

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.