Score:1

Set nested value in storable config

cn flag

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?

Score:2
cn flag

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']);
Matt avatar
cn flag
That worked thanks!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.