0

Dupal 8.x

I have a custom form field where the value could be zero for radio elements:

$yes_no_options = [
  '1' => t('Yes'),
  '0' => t('No'),
];

$form['config_name'] = [
  '#options' => $yes_no_options,
  '#default_value' => $config->get('config_name') ?: 1,
];

$config->get('config_name') is either equal to 0, or 1. This value gets passed to my .module file to be used in hook_node_access_records(), so 0 and 1 would be preferred.

I could do some converting in the .module file but I am curious if there is a worth while way to allow the 0 value when comparing?

Also wondering the pertinence of worrying about a default value comparison in the form field? If the default value can be set in the hook() maybe this isn't necessary and should just write '#default_value' => $config->get('config_name'),?

  • If you include a config file with your module you can include default config values - that would have the same effect as your 2nd outcome. You could cast to boolean to achieve your 1st outcome (and/or the 2nd actually) – Clive Nov 29 '18 at 8:11
  • BTW 16 years as a professional dev and I’ve never heard the term “Elvis operator” until now - something new every day :) – Clive Nov 29 '18 at 8:13
  • Well I can't claim it en.wikipedia.org/wiki/Elvis_operator :) I'll give casting to boolean a try. – Prestosaurus Nov 29 '18 at 8:27

Your Answer

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

Browse other questions tagged or ask your own question.