2

I'm looking for a way to programmatically change the settings of an input filter and activate it in Drupal 7. Let's take the Footnotes module as an example: It adds a new input filter that can be activated on input formats. I can navigate to admin/config/content/formats/2 to edit my "Full HTML" input format and there activate the Footnote filter and configure it. But how can I achieve that programmatically?

My first guess was to load the input format using filter_format_load(), change some values and then do a filter_format_save(). But in the object that I get from filter_format_load(), there are no input filters, i.e. $format->filters doesn't exist.

I can get all available filters using filter_list_format() and I believe I could change some values there. But then again, I can't find a way to save those settings.

1 Answer 1

7

If you read the API page for the functions you mentioned in your question, you can easily see that there is a bug(or a feature) that it does not load populate $filter->filters indeed.

For a workaround, you could do something like this, with the help of filter_list_format()

$format_id = 'full_html';
$filter_id = 'your_filter';

First, load the format object

$format = filter_format_load($format_id);

Now, since we do not have the $filter->filters populated, we do so by loading the currently enabled filters.

$filters = filter_list_format($format_id);
foreach ($filters as $filter_id => $filter_opts) { //Convert to an array, which is expected by the save function.
  $filters[$filter_id] = (array) $filter_opts;
}

You can now make changes in the filter that you are interested in.

$filters[$filter_id]['status'] = TRUE; //Enable. 
$filters[$filter_id]['settings']['something'] = 'foobar';

Inject filters to the format we have already loaded.

$format->filters = $filters;

Save!!

filter_format_save($format);
3
  • Thanks a lot for the quick and interesting answer! Actually I thought about that, too. But in line 219 of filter.module I read that "Programmatic saves may not contain any filters" -- but it seems that's not really true. ;)
    – yotka
    Commented Sep 6, 2015 at 13:47
  • Two corrections though: $format_id would be numeric and the status would need to be set to 1/0, not TRUE/FALSE.
    – yotka
    Commented Sep 6, 2015 at 13:49
  • @AyeshK - this answer saved me a ton of time! Thank you so much for sharing! A tiny update - $filters[$filter_id]['status'] = TRUE; status accepts only integer values now so I used $filters[$filter_id]['status'] = 1; to enable the filter. Cheers!
    – oksana-c
    Commented Feb 15, 2017 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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