How to include inline CSS in ajax form

| | 2 min read

In the near past, I had a requirement to add inline CSS to the content that comes after submitting the form. Let me explain the context a bit, I have a form, only on its successful submission, a block need to be displayed. If the submission failed, all I need is to return the form and error message back.

Important thing is CSS for block, ie., generated at random after checking some conditions.

Inline CSS into ajax replacing content

If you used to play with CSS, you wont be a stranger to drupal_add_css() command. drupal_add_css command is used to add a CSS file.
To include a CSS file, specify type as file

 drupal_add_css(drupal_get_path('module', 'example') . '/example.css', array('group' => CSS_DEFAULT, 'type' => 'file')); 

To include inline CSS, it changes to,

 drupal_add_css('body {background: #000;}', array('group' => CSS_THEME, 'type' => 'inline')); 

To include an external CSS file, use,

 drupal_add_css('http://example.com/css/reset.css', array('group' => CSS_THEME, 'type' => 'external')); 

To get all the CSS used so far, we can use drupal_add_css()
The following will output all the external, files and inline CSS's,

 $value = drupal_add_css(); 

For inline CSS you could it to the rear of the array.

Inline CSS comes as a key value pair,and its key will be a numeral.
To get the inline CSS, parse through the array $value.

 foreach ($value as $key=>$value) {
        if (is_numeric($key)) {
          $inline_css. = $value['data'];
        }
      } 

Now we have inline CSS stored in $inline_css. Last article I did a documentation on ajax_command_replace,
where as in this I'll brief you on ajax_command_add_css.

ajax_command_add_css can be used to include css to a content.

To include a file, use it as,

 ajax_command_add_css('folder/example.css'); 

To include inline css,

 ajax_command_add_css(''); 

As our CSS is stored in a string, let's implement it as,

 ajax_command_add_css(''); 

Drupal has had offered a lot of tricks and methods to do much complex tasks simpler. To add inline CSS through ajax_command_add_css is one of those.
To do apply inline CSS wont be much difficult after going through this. Lets hope some one will find this helpfull.