1

I have a settings form that saves site wide configuration information My submit form function looks something like this

$data = [];
foreach ($groups as $key) {
  $data[$key] = $form_state->getValue($key);
  if (empty($data[$key])) {
    $data[$key] = [];
  }
}

$this->configFactory
  ->getEditable('my_config.settings')
  ->setData($data)
  ->save();

My issue is that in a callback I'd like to be able to directly set the value of a single configuration field that is nested in that data array without grabbing everything again and changing the data array and resetting it with ->setData

The data in my config array looks like this

[
    'num_campaigns'=> 4
    'campaigns'=> [
        'campaign_ids' => ['abc','def','ghi','jkl']
    ]
]

And my callback looks like this

  public function removeField(array $form, FormStateInterface $form_state){
    $config = $this->getConfig();
    $num_campaigns = $config['num_campaigns']-1;
    $config_factory = $this->configFactory->getEditable('my_config.settings');
    $config_factory->set('num_campaigns', $num_campaigns);
    $config_factory->set(['campaigns','campaign_ids',$num_campaigns], '')
    $config_factory->save();
    $form_state->setRebuild();
  }

My issue is that the set method accepts a string and not an array. If I can only supply a string how do I set the value of something that is nested down in my config array? Is using set even an option? Or do I have to resort to using setData?

1 Answer 1

2

The first parameter is a string with nested keys separated by dots. The second parameter is the value, which is not necessarily a string. It can also be an array:

$config->set('campaigns.campaign_ids', ['abc','def','ghi','jkl']);
1
  • That worked thanks!
    – Matt
    May 24 at 16:08

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.