Deployment Issue with Heroku I have a Drupal project on heroku and it works fine, until a dyno restart.
After that, the Css and Js on the Drupal site stop working.
Whenever that happens, I have to do a flush cache to get the site working. From my understanding, flushing cache creates files that Drupal uses for Css and Js. Since the storage system on Heroku is ephemeral, after dyno every restart I lose that file. Thus, I am forced to do a cache flush to get that file again and make everything on the site work. Is there a way around this?
Is there a way to change the folder location of the temporary file that is created?

I eventually got the site working by disabling caching. But better approach to this problem is, creating the site on your local instance first.
You need to create and install Drupal on your local system. If you install it directly on Heroku, it creates some temporary file on Heroku, which Heroku discards after every dyno restart. Even settings.php loses all the changes made to it(during installation) after dyno restart. (I installed my site directly on Heroku, so I got through this issue by adding changes to settings.php manually)
Once you create the Drupal site on your local instance (using the GUI), you will have some files in sites/default/files, as well as some changes in settings.php (hash salt, database setting etc). Now, you can track all these files and push it to Heroku.
The site should work fine, except you won't be able to store any public files, you will need S3 bucket for that.
Hope this helps who encountered similar issue!


Video Embed Field: Check All My Videos on existance? My question on drupal.org did not have an answer:
To check if YouTube video exists in all my nodes?
Please yow to do these?

the quickest solution is to query the DB and export all youtube video IDs.
After you can write a custom PHP script to check if the video exists.
Here is an example of the code you could use: https://stackoverflow.com/a/21069917

A more Drupalistic approach is to write a custom module which do the same thing. For example it could implement a drupal cron task or a batch procedure to verify each Youtube field content using the code suggested before.

I hope this suggestion will be helpful.


Webform 5.x lookup validation via data table lookup I want to block/validate a new entry based on another submitted form

e.g.

If a site number has been used I want to block any new entry that wants to use that number?

Is this possible?

If so How?

Thanks all

Webform elements support unique value validation, which I should be able to address your requirement. If not, you may need to write a custom form alter hook with a custom validate callback.


Getting a custom field to appear correctly in Rules using entity form module I have written a custom field widget called foo which is inserted into an entity form to provide an autocomplete to another web service. I am trying to get the field data to be sent in an email via Rules. I am able to get the entityform tokens using List, text and the standard widgets to show in the email body and the list. However the form field defined in custom widget "foo" appears [entityform:field_foo] rather than [entityform:field-foo] which means that the send email rule in Rules appears to ignore it.

From my understanding, I believe that I need to create declare a  token using hook_token_info():

function MYMODULE_token_info() {
  $info['types']['foo'] = array (
    'name' => t('Foo'),
    'description' => t('Tokens related to the foo widget'),
    'needs-data' => 'entityform'
  );
  $info['tokens']['foo']['organisation'] = array (
    'name' => t('Janet'),
    'description' => t('Custom foo widget field'),
    'type' => 'entityform'
  );
  return $info;
}

and then declare hook_tokens():

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  if ($type == 'entityform' && !empty($data['entityform'])) {
    $elementform = $data['entityform'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'field-foo':
           $replacements[$original] = str_replace('_', '-', $name);
           break;
      }
    }
  }
  return $replacements;
}

The other avenue I was exploring was whether this token needs declaring to Rules via hook_rules_data_info() but I cannot see why so I have not explored it further as the entity form appears to be pushing it through to Rules, just not creating the token so that the email can see it.

I have managed to find a work around using hook_tokens(). Through viewing the $data array, I was able to find the field and write some code which manipulated the incorrect field and created the token correctly for Rules by walking through the field array.

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
 $replacements = array();
 $sanitize = !empty($options['sanitize']);
  if ($type == 'entityform' && !empty($data['entityform'])) {
    $elementform = $data['entityform'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
       case 'field-foo':
         $name = str_replace('-', '_', $name);
         $field = $elementform->name
         $replacements[$original] = $field[und][0]['value'];
         break;
      }
    }
  }
  return $replacements;
}

I would be happy to learn if there is a better way of achieving this goal in Drupal.


How to use the view_mode in hook_preprocess_flag? I'm using Drupal 7 and Flag.

I try to modify the output of my flags according to the view mode with preprocess_flag :

function mytheme_preprocess_flag(&$variables) {
  $variables['full'] = $variables['view_mode'] == 'full';
  if ($variables['full']) {
...
  }
}

But i have an error : Notice : Undefined index: view_mode dans publiu_preprocess_flag().

Do you know how to use the view_mode in hook_preprocess_flag ?

view_mode key is not in variables object, which you get as argument. You can check for the same, by printing variables object.

print '<pre>';
print_r($variables);
print '</pre>';

However if u still want to get view mode, you can use somewhat like below.

function bartik_preprocess_flag(&$variables) {
  $arg_1 = arg(1);
  if( isset($arg_1) && !empty($arg_1) ) {
    $menu_obj = menu_get_object();
    $menu_obj_content = $menu_obj['content'];
    foreach($menu_obj_content as $menu_key=>$menu_val) {
      $node_view_mode = $menu_val['#view_mode'];
      break;
    }
    print $node_view_mode;
  }
}

Here node_view_mode will return "View Mode" of current node.


How do I filter a view for untranslated content? I have a site with many lessons in English, with the option to translate them into Japanese. There is a team of translators working to translate the lessons, but they need an easy way to see which lessons have not yet been translated.

Is there some way to filter or create a view that only shows content that has not yet been translated to a target language?

You could use the following 2 views filters
Content: Revision translation affected (!= False)
Content: Default translation (= True)

for more details go to a more complete answer How to create a list of untranslated content in views?


How do I programmatically validate reCaptcha? In Drupal 7, I use the Commerce_Checkout_Redirect module which uses custom validation functions. It uses the following code.

// Use the username as order email.
// Email validation for the username form element
if (variable_get('commerce_checkout_redirect_username_as_order_email', FALSE)) {
  $form['name']['#title'] = t('Email');
  $form['actions']['continue_button']['#limit_validation_errors'] = array(array('name'));
  $form['actions']['continue_button']['#validate'][] = 'commerce_checkout_redirect_username_as_order_email_form_validate';
}

The validation function is the following.

function commerce_checkout_redirect_username_as_order_email_form_validate($form, &$form_state) {...}

The form ID is user_login, the reCaptcha is enabled for this form and it is shown, but it is ignored by the validation process when users submit the form.

How can I "force" the validation of the reCaptcha inside a custom validation function?

I figured out myself. The only thing i had to do is to add in #limit_validation_errors element another array with captcha_response.
So the right syntax is

$form['actions']['continue_button']['#limit_validation_errors'] = array(array('name'),array('captcha_response'));


Setting author when creating a new node via Cron I'm creating a new node using hook_cron(). It all works except the node author is always set as anonymous (uid = 0). How can I assign a user to the new node, with say uid 21 for example?

Below is the node creation code that I have in a function that gets called within hook_cron().

$node = new stdClass();
$node->type = $type;
$node->title = "Some node title";
$node->language = LANGUAGE_NONE;
$node->uid = 21;
node_object_prepare($node);

$node->body[$node->language][0]['value'] = '';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'html_text';

$node->field_quote[$node->language][0]['value'] = $some_value;
$node->field_quote[$node->language][0]['format'] = 'plain_text';

$node = node_submit($node);
node_save($node);

Even though I state $node->uid = 21;, it always results in an anonymous author.

You have two options.

Either set the uid after the node_object_prepare call and before node_save, or you can set $node->name to the username of the user that should be the author.

The reason is that node_submit will set the uid of the node based on the value of $node->name if set and node_object_prepare will always set author to the current user.


adding a background image to a Drupal site I have a high-resolution white-paper texture background that I want to add to my Drupal site with the default Bartik theme.

I've looked at several posts across the web on how to do this with no clear answer.

I also haven't been able to find a Drupal module to do this. Most of the advice I've read is to modify the theme's CSS files.

But it's not clear which CSS file I should edit.  Colors.css, style.css?

I'm almost certain that the line I need to add is

 background-image: url("/images/papertexture.jpg").

But I'm not sure where to add the CSS.

You can try the background image module

  This is an api module that provides tools to add background images to
  html elements using the css "background" property. A basic settings
  page is supplied as well as functions to easily add the "background"
  property to the page.


how to add html/ccs element s inside drupal mail function I am developing function that send a email to user..,and i want to add some html.css styleing to the email how can i achive that folllwing is my code i tried

function zgcrons_mail ($key, &$message, $params) {
  switch ($key) {
  case 'mymail':
    // Set headers etc
    $message['to'] = $usermail;
    $message['subject'] = t('Your Donation Statues ');
    $message['body'][] = '

&nbsp;
                follow on Twitter |
                friend on Facebook

                Copyright &copy; 2012 Zealous Good, All rights reserved.

';
  break;
  }
}
drupal_mail('zgcrons', 'mymail',$usermail, $language, $params = array('username' =>'John Potato'), $from = NULL, $send = TRUE);

Your way will work if you enable the html format for email in your website. By using http://drupal.org/project/htmlmail or http://drupal.org/project/mimemail that will help you format the email in html and choose which method that will use for sending email.


How to pay with site credit in Commerce? I would like to allow users to pay for products with site credit.

A field keeps track of how much credit a user has with us, and if they have enough of it to pay for an order they should have that option. Even better would be if they could dump the last bit of credit onto an order and pay the rest the regular way.

I have a few ideas; I'm just wondering if there's a standard or best practice in this situation. Thanks in advance.

Edit: Some of the ideas:

Using Rules, add a payment method if the user has more credit than the order total. If this payment method is selected, no validation is needed. The user clicks through and credit is deducted.
Add a checkbox to the checkout pane called ~"use site credit". If checked, subtract the user's credit from the price (up to the order total). This has the advantage that a user can pay with credit even if they don't have enough for the whole order, but seems much harder to do.
At the calculate price stage, automatically subtract credit from the order appropriately. Add some notification informing the user that this has been done.

I may update this more as I explore options further

you can use user-points module with Commerce userpoints. they work nice togather.


View with entityreference: make exposed filter autocomplete I have two content types A and B. B has an entity reference to A.
When creating a view to list all nodes from type A, I want to use some exposed filters. One filter would be to give all nodes from type A that have a reference to a certain node of type B.
The exposed filter I get is a textfield that needs a nid. I made it autocomplete (via form_alter), but now the value that gets saved is "node title (nid)".

Anyone having the same problem, and knows how to fix it?

EDIT:
I found this patch for entity_reference, but it doesn't seem to work.
http://drupal.org/node/1492260

The patch I added to the initial question did the trick: http://drupal.org/node/1492260
The only thing you need to know is that you need to enable a checkbox on the fieldsettings of the field on you content type.


What is x-speed-cache-key? What is its purpose? Our drupal site was pentested.  The pentest report labeled an action involving the header X-Speed-Cache-Key as a security concern.

The finding stated:

  Arbitrary parameters supplied to the query string are returned to the user unencoded in the X-Speed-Cache-Key response header.

I'm not familiar with caching or with the header x-speed-cache-key. For a Drupal site functionality should the x-speed-cache-key function as stated in the finding? Is this a valid security concern for Drupal? Is the x-speed-cache-key header provided by a module, or is it a part of Drupal core?

Best I can find on Google is that this header (and its companion header 'X-Speed-Cache') are added by a web server level module called "Speed Booster" touted as part of the Drupal Platform 'BOA': https://groups.drupal.org/node/173219 and https://omega8.cc/features .

The purpose of the header seems to be nothing more than a debug header to check which key has been used to retrieve the cached version in Speed Booster.

You probably want to contact your hosting company to see if they can disable that header.


no description and image title in insert module I am using insert module in drupal 6.

How come I have no description and image title just like this https://www.drupal.org/files/images/insert-module.png

Solution
Enable the insert in content type.
admin/content/node-type/news/fields/field_image2


Rotating Banner Module Shrinks Banner Image When It Should Not I am using drupal 7.23,
and the module Rotating Banner https://drupal.org/project/rotating_banner
I have the banner size set to " The banner will shrink to fit the page. "
Unfortunately it is shrinking the banner when there is no change in page size.

All I have to do is load the page. The banner is initially fully expanded to the max size of the screen, but as it rotates, it will change to have a very small width.
This appears to be random, in that it just happens with enough image rotations.

Here is the css for the regular image before it becomes travel size

Here is the css for the image after it smalls down

It appears that the internal code for the module thinks the screen size shrunk down big time, but I don't know why....
I would appreciate anyones advice on this matter....

Thanks so much,

david

I think the module is a bit buggy.
I changed it to not have the dynamic size setting, but went with static
but just didn't put in a height/width.
Since I am using bootstrap with drupal I surrounded the image with a

...

Which then forces the image to dynamically respond properly.
So, a hack.


Drupal 7 rewrite is removing get parameters from query string I've recently upgraded a site to the latest release of Drupal 7. The site has a view that retrieves a url with query string parameters from the database and then uses the Drupal rewrite functionality to add a class to the link like so:  View

The issue is, since the upgrade the rewrite now removes the query string parameters. If I modify the view to display a simple link the parameters are there and it works fine. However, the rewrite applies styling to present a button rather than a simple link. I can't find any settings to resolve the issue so I suspect the upgrade overwrote a modification to the Drupal core made by the original developer of the site. Any idea how I can address this issue?

It turns out that there was a bug in the latest release that in /modules/contrib/link/link.module that was causing the query strings to be stripped from the URL in the token. I replaced the code in this file with the code from the pre-upgrade version and it began behaving as expected again. This, of course, is not a resolution to the issue, but at least the source of the problem has been identified. For more info, see the original bug report.

I later found that there is a patch for this issue in the dev version (7.x-1.x-dev) of this module. Download this module and replace it in your install and you should be all set.


Images in CKEditor don't retain size I can't seem to figure out how to retain image sizes in CKEditor.  When an image is sized, and the content is saved, and then edited again, I want the size to stay the same as set originally.

Is there a way to configure this?  If not, I can write JavaScript, so is there an implementation I could approach?

You are looking for Insert module, using this module you can retain the sizes with the help of image cache.

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain text areas.
Insert images using ImageCache presets
Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
Per-field insert configuration


How to show content type with only related taxonomy item? I have a menu that is taxonomy like so:

A
subterm(A1)##
subterm(A2)##
subterm(A3)##

Suppose A is menu and I linked a taxonomy vocabulary to menu A.

And suppose that on content type X field taxonomy term type is A1.

How to show content type with only related taxonomy item
like for taxonomy menu subterm (A1) with content type X related to that term?

Download and install Views Module and enable the Taxonomy term view.


Force users to add Organic Groups content only to their group(s) When a group member try to add group content, how come this user can still choose to witch group this content belongs to?? I was expecting that group members adding content could only add content for their specific group, not for all groups...
In the event a member is part of several groups then there should be a way to detect from witch group the edit content as been trigger and then only modify the content for that specific group ..

Anyone have such experience to share ?

Thanks,

At admin/og/og (D6) you can uncheck the setting "Audience checkboxes". From the description "Show each group that the user is a member of as a checkbox in the "Audience" section. This enables the member to place her post into multiple groups. If unchecked, simplify the user interface by omitting the checkboxes and assuming user wants to post into the current group. This simplification only applies to new nodes, and not to edits of existing nodes. Group administrators always see checkboxes."


populate checkbox value in text area I am a drupal newbie and am having the following problem:

In my custom content type page, I have multiple check boxes and a text area, among other fields. What I want is that, I would like the values of the checked check-boxes to be pasted inside the text area. The checkboxes are created as a multi-value field (field type = list, widget = check-box). Basically what I want is, every time the user checks/unchecks one of the checkboxes, the text area should re-populate with values of all the checkboxes that are currently selected.

I tried using the dependency fields module, but it did not solve my problem. Have anyone encountered this need before?

Based on what I read, it seems this might be possible using hook_node_presave, however I am not sure where to add this. I am using a template called norma, so I edited its template.php and added a function like so:

function norma_node_presave($node)
{
 print_r($node);
 exit;
}

However, nothing has happened... :(

Any pointers on how to solve this is very much appreciated...

hook_node_presave($node) should be included in a custom module and not in your theme !

Look at Creating Drupal 7.x modules if you want to try so.

In your hook do something like that :

function norma_node_presave($node){

  $value = array();
  foreach( $node->field_checkbox['und'] as $checkbox){
    $value[] = $checkbox['value'];
  }

  $node->field_textfield['und'][0]['value'] = implode('<br>', $value);
}


How to confirm that drush-based cron is being called from crontab? I don’t know whether this is a docksal-specific question or a general cron one, but likely the latter.

I’ve set up a crontab for docksal (see https://blog.docksal.io/running-scheduled-events-with-docksal-43fc69d7b29b):

0 */3 * * * drush --root="/var/www/docroot" core-cron

My question is how tell if it’s actually working. I don’t see anything logged in at /admin/reports/dblog. I also tried enabling the syslog module, but I’m not seeing a syslog file at /var/log as described, using fin bash and cding to that directory.

I don't whether I should expect to see something, but would prefer I did. Otherwise it's like trying to check if the refrigerator light has gone off when you've closed the door.

It sounds like you've answered your own question. Viewing the admin DB log reports or running something like fin drush wd-show --type=cron should show cron execution entries. If you're not seeing those logs, it most likely means the crontab config isn't working.

You should check drush --root="/var/www/docroot" core-cron works correctly when manually executed in the container where crontab is configured (e.g. perhaps the crontab user doesn't have drush available in its path or drush can't find the DB config) & the /var/log/ dir (it will depend on the Linux distro the Docksal image is based on) for cron logs to confirm that its firing.


If I use node_save() to create a new node, do I need to manually escape user input? I am writing a custom module for Drupal 6 that programmatically creates a node using node_save().

The various custom node fields come from user input - is it necessary to manually escape these fields, or will node_save() take care of that for me?

If by escaping you mean using check_plain() or similar functions, then no; escaping is done when outputting something, not when saving it in the database, or in Drupal persistent variables.

Imagine what would happen if you call check_plain() on a node containing "&"; that character would be escaped to "&amp;" that it would be converted in &amp;amp; when Drupal would show the node content. The result is that "&" would be shown as "&amp;" and that is not what it would be expected.

In Writing secure code, you can read the following text:

  Use check functions on output to prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into HTML.

  Use check_plain() or theme('placeholder') for plain text.
  Use check_markup() or filter_xss() for markup containing text.
  Use the t() function with "@" or "%" placeholders to construct safe, translatable strings.

  See how to handle text in a secure fashion for more details.

As you see, the page about writing secure code doesn't say to escape the text being saved, but only text being output, when the text has been entered from users, in a way or in another. An example of text entered from a user is the username or the signature associated to user accounts, the node title, or the node body.

About SQL injection, you just need to use placeholders in you queries; Drupal database functions escapes the content of the placeholders, which would not be possible if you write a query like the following one, for example:

$query = db_query("SELECT * FROM {node} WHERE title = '$title'");

The "Writing secure code" reports:

  Use the database layer correctly. For example, never concatenate data directly into SQL queries, like this:

<?php
 db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
?>

  Instead, use proper argument substitution with db_query:

<?php
 db_query("SELECT foo FROM {table} t WHERE t.name = '%s' ", $_GET['user']);
?>

  If you have to accommodate a variable number of arguments in your SQL, create an array of placeholders. Don't do this:

<?php
 db_query("SELECT t.s FROM {table} t WHERE t.field IN (%s)", $from_user);
?>

  Instead, do this:

<?php
 $placeholders = implode(',', array_fill(0, count($from_user), "%d"));
 db_query("SELECT t.s FROM {table} t WHERE t.field IN ($placeholders)", $from_user);
?>


How the get all the child menu's Node IDs? I've a very simple task to do in Drupal 8, but I've hard time to find the proper way to do that.

I have a simple menu like this (all basic pages).

Company

Organization
Values
Terms

Services
Team

And when we go to Company page, I want to display all three sub-pages content in there.

How do I get the sub page node ID from the current menu? In Drupal 7, I'd go with something like menu tree data, and parse the URL to get the node ID; I'm sure we can do something similar with Drupal 8, but I can't find a way.

I think you're approach is just from the wrong end, the menu is just a list of links and not meant to control content.
What you want to do is:

Make "Company" as a views > page or a views blocks within etc.
Make a taxonomy reference for the sub pages or make them separate entity or content type,  in order to specify your sub pages in views.
Create view_mode like teaser to format their subpage display.


Where does Feeds cache the source and how do I disable this cache feature? I've found out that Feeds caches the sources. Even when I change the content of the source, emptying the imported items and reimport, it imports the old items.

Where does Feeds store this cache and how do I disable this cache feature?

I need to disable this caching feature because I am dealing with sources which change often.

I've posted this issue on Drupal before. Basically it's a problem that they are working on.

http://drupal.org/node/1156062


Print view field direct in views-view-fields.html.twig Is it posible to print all view field direct in views-view-fields.html.twig and sciping to use views-view-field.html.twig?

In my blog view I have a lot views-view-field.html.twig for every field type and this is just one view.

So is this posible and is this recomend?

Yes, that is possible, this is the most basic fields twig:

{% for field in fields -%}
    {{ field.content }}
{%- endfor %}

Then you loose most field configuration from views and can put in your own html structure.

You don't need to skip the field twigs for single fields, simply delete you own twigs and let the core twigs take over again.


Exporting Taxonomies to code I'm looking for a way to export Taxonomy vocabs and their associated terms. So far I've found and tested:

Taxonomy Export -- Exports to code using features but doesn't import.

http://drupal.org/node/755986 -- My brief testing with this patch showed mixed results.

Does anyone have any other module suggestions or code solutions? I could write it all into a hook_install and then use hook_update to update but it doesn't seem like an elegant solution especially for 500+ terms.

Also might want to take a look at Taxonomy CSV import/export or Taxonomy import/export via XML


URL alias in page.tpl.php I try to make link 'Mobile version' on site page site.com/page. This link leads to this page but on subdomain m.site.com/page.
I use page.tpl.php. I try to write this.

<a href="http://m.site.com/<?php print drupal_get_path_alias();?>">Mobile version

<?php print drupal_get_path_alias();?> prints nothing. What's wrong? Maybe there is some more elegant and right way to solve this?

Your code only work for Drupal 7. As you are using Drupal 6, please pass the current url as argument.

print drupal_get_path_alias($_GET['q']);


How to include the Title field of a content type inside of a Group? When creating a new content, is it possible to have the field Title inside a Group defined by me?

There is only one way I'm aware of to do this. But since this solution is structural, it may not make sense to use it since the goal here is more for admin-usability.

You could use the Automatic Nodetitles module ("ANT") create a new CCK field for the title, put it in the fieldgroup that you like, and configure ANT to populate the true title field from that new custom CCK field.


Views - how to create a chart AND a table from the same filter selection I know how to create a chart using Views and I also know how to create a table. How do I used the same set of filters to create both but on the same page I am looking at?

I have embedded views inside views as well but that doesn't seem to do the job. Anyone got any idea?

I can do that in the following ways:
a. Create View page to generate table with exposed filter
b. Clone the view page (table), and change the title name and the path
c. Change the cloned page from Table to Chart, set the field for the chart setting to display, then save
d. Open the original table page view, the add footer -> global view -> select the view chart that you created in (b)

Now you have table with filter on top, and the chart below (also with the same exposed filter). The chart follows the results of the filter on the table.
I use CSS to hide the filter for the chart on the footer.


Renaming the name of a field in a View I've set up a View which displays the latest posts of a custom content type. Its fields are the usual, such as image, summary and title.

Though I would like the name of title that the View displays to be different than the original.

So for example the name of the title in the content type is Location of Project. Rather, I would like to have the View title only display Location. The titles' output would continue to show the same information, for example Canada.

Couldn't find a way to achieve this using the Views config. Any help would be appreciated.

There is an option in Field configuration to Create a label. It's usually just at the top of the options.

You have to tick it to enable it. Once you tick it an input field appears where you can enter a different label for your field.

To get to the field configuration just click on the desired field under Fields area in your Views.


Does Quick Edit function work for embedded entities? I have a view which creates a block of User data related to the author of the node. The view display is a view mode of the User entity.
I see my entity when the block is placed on the node page; but there is no quick edit functionality. Is this expected behavior?

It does work, for Nodes, when set to Show: Content | Full Content.
However, it does not work for Users. Fairly expected as when you go to a user page, ex: /user/1 there is no quick edit feature there to begin with.


How to use tables that are claimed by other modules in drupal? How to use tables that are claimed by other modules in drupal?

I have a table in my database named "dictionary" used by a module for translation .
now i want to use that table in views to show all data of that table.
Is there any method by which i can use that table?

You can expose information from other modules/"orphan" database tables from your own module by using hook_views_data in case nobody is exposing that table to views then you would "claim" it with all the consequences. If the table is already exposed to views but you want ton enhance the integration, you can use then hook_views_data_alter for adding fields, altering filters, etc.

You can find an example of how to implement a hook_views_data in the views documentation.


Remove subject field from comments Is it possible to remove the subject field on comment forms?  I find it to be kind of useless and redundant, since the subject of the comment is usually the title of the article being read, at least for me anyway.

You can turn it off in the UI at admin/structure/types/manage/type-name with the "Allow comment title" checkbox:


Entity form Submissions automatic numbering over 1000 I have reach an entity form submission count that has hit 1,000.

The problem I have is the URL is '/entityform/1,000' - notice the comma. This screws up the link to the url. I have searched and cannot find how to remove the comma when entityform creates the link.

I have check alias patterns, module settings and every where else I can look within the drupal/module configuration.

Can someone help me figure out where to make this update?

Thank you!

Okay after searching it was probably the 12 forum post I found another module that helps with this issue.

Install this module along with Pathauto.
https://www.drupal.org/project/pathauto_entity

The URL Alias is: [entityform:type:label]/[entityform:entityform-id]

Hopefully that helps someone.
Peace


How can I speed up drupal's node_save() function? I am having a lot of trouble with the inefficiency of node_save().  But is node save my problem? That's ultimately what I am trying to find out.

I created a loop with 100,000 iterations. I created the bare minimum for the node object to be valid and save correctly. Here is the node save code:

$node = new stdClass();
        $node->type = "test_page";

        node_object_prepare($node);

        $node->uid = 1;
        $node->title = $node_title;
        $node->status = 1;
        $node->language = LANGUAGE_NONE;
        if($node = node_submit($node)){
            node_save($node);
}

Here are the results:

100,000 nodes were saved, each using node_save().
It took 5196.22 seconds to complete.
That is ONLY 19 saves a second.

To say the least, that is not acceptable, especially when this person is getting around 1200 individual insert queries per second, and this person is getting 25,000 inserts per second.

So, what's going on here? Where is the bottleneck? Is it the with the node_save() function and how it's designed?

Could it be my hardware? My hardware is a development server, no one on it except for me - Intel dual core, 3Ghz, Ubuntu 12.04 with 16 gigs of ram.

While the loop runs my resource usage is: MySQL 27% CPU, 6M RAM; PHP 22% CPU 2M RAM.

My mysql configuration was done by the percona wizard.

Mysql says that if my CPU usage is under 70% my problem is disk bound. Granted, I have only a run of the mill WD Caviar 7200 RPM, but I should be getting more than 19 inserts a sec with it I hope!

Not too long ago I wrote about saving 30,000 nodes in a day. However, to be  clear, this node has nothing to do with any external forces.  It's purely a benchmark to learn about how to increase the speed of calls to node_save().

Realistically, I need to get 30,000 items into the database every minute using node_save.  If node save is not an option, I wonder if I can write my own drupal api function "node_batch_save()" or something that takes advantage of mysql's ability to to do bulk inserts with the INSERT query.  Thoughts on how to approach this?

You will never get 30 000 inserts a minute using node_save.
No way.

An INSERT is fast because that's all it does.
Node save does multiple inserts (main table, revision table, a table for each field), clears any entity caches, and fires hooks.
The hooks are the tricky part. If you have many contrib modules (or even one that misbehaves) that can really kill performance, especially if the author didn't account for the "I am saving a ton of nodes at once" use case.
For instance, I had to add this to my Migrate class:

  public function processImport(array $options = array()) {
    parent::processImport($options = array());
    // Do not force menu rebuilding. Otherwise pathauto will try to rebuild
    // in each node_save() invocation.
    variable_set('menu_rebuild_needed', FALSE);
  }

On the other hand, if you write a custom save function that invokes no hooks, you are in clear danger of getting inconsistent data, in a state that is unexpected by the system. I would never recommend doing that.
Fire up xhprof and see what's happening.


composer require fails because it can't delete default.services.yml Using composer with Drupal (7, 8 & 9), composer require drupal/<package-name> returns the following error.

Installation failed, reverting ./composer.json to its original content.
[RuntimeException]
Could not delete web/sites/default/default.services.yml

How can I fix this error?

Make your "local" machine work as intended, and maintain the security of your live site.
Since you want to use composer require command only on non-production environments, the following steps affect only on the machines you deliberately set up. Drupal's recommended configuration will be preserved on all other machines, including production servers.
Don't make this change to settings.php to avoid having it on PROD or propagating it silently to other developers' machines.
Steps

enable settings.local.php (here are the instructions from the docblock in settings.local.php):

 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path [... read about exceptions in file]

set file permissions to allow user and group to write to the file on your local machine:
$ chmod ug+w {name_of_docroot}/sites/default

How this approach matches up with the established community approach
By default, settings.local.php contains the following line:
$settings['skip_permissions_hardening'] = TRUE;

This line tells Drupal to avoid resetting permissions on the default folder only on your local, and allows you to work more smoothly with composer on your local without weakening permissions on any other copy of the codebase.


How to perform action after a file is deleted? Is there an API hook I could use to run some custom PHP code after a file is deleted? I need access to the name of the file which has just been deleted.

I attempted using hook_nodeapi, and testing for when the operation is delete, but it seems by this stage the file row has been removed from the database, and I'm left with just information about the node itself.

I'm using Drupal 6. (I see that Drupal 7 does have a hook: hook_file_delete)

I believe you can use FileField; this module is now part of Drupal 7 core, and provides additions to the API, such as hook_file_delete().


How to do taxonomy based css styling using template.php? I'm looking forward to implement taxonomy terms based CSS styling; especially for the body tag which I want to add the current terms.

Here is what I have so far:

function _phptemplate_variables($hook, $vars = array()) {
  global $node;

  switch ($hook) {
    case 'page':
      // die ('test');
      $vars['body_class'] = '';
      if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
        $vars['body_class'] = 'theme' . arg(2);
      }
      if (arg(0) == 'node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));

        if (is_array($node->taxonomy)) {
          foreach ($node->taxonomy as $term) {
            $vars['body_class'] .= 'theme'.$term->tid;
          }
        }
      }

      if (drupal_is_front_page()) {
        $vars['body_class'] .= ' front';
      }
      break;
  }

  return $vars;
}

I think the code is OK, but it never get called (see my 'die' function); using simple phptemplate engine and minimal Drupal 6 install.

What obviousness am I missing here?

The reason it is not called is because hook_preprocess_variables is for Drupal 5: you should use hook template_preprocess_page in Drupal 6.

So if your theme is called "mytheme", the function would be best named "mytheme_preprocess_page" in your template.php.

Also, Drupal and the Taxonomy modules already generate many body classes, so you should check out what classes already exist because it may be that you don't need to preprocess the page at all (if all you want is to add a body class depending on taxonomy).


My admin panel view fancy box not working I am new to drupal. I searched this problem in google but could not get the solution that could solve my problem. My problem is,

I used a fancybox for one of my news post page. It uses latest version of Jquery. When, I use this, my fancybox works well. But, when I come to view page, My light box does not work there. Like,

When I click on add button [Add button to add fileds or filters ], the sceen goes black and nothing happens. When I remove the fancybox, it works well. It is important for me to use fancybox. Please suggest how to solve this problem.

I also faced the same problem. This is due to jquery problem. Let me tell you that jquery contains default support to jquery. It uses older version of jquery in its core. So, if u want to use that module, then, what u can do is:

Download jquery update module and enable the moudle,
Then you open the project code, moudles folder and find the jquery update moulde, there you will find replace folder. You, will find various version of jquery there. You can include or replace the latest version of jquery.
However the drupal core works in older version, so what you can do is open the jquery_update.module file and find the line that says.

// Replace files for jQuery 1.7 and up
      if (version_compare($version, '1.7', '>=')) {
        $javascript['drupal.states']['js']['misc/states.js']['data'] = $path . '/replace/misc/1.7/states.js';
  }
Now what you need to do is. You need to check, if the user is logged in then replace the jquery with core old jquery and if user is not logged in then, use the latest your fancybox jquery.


How to show dates and times separately? I have set up events with calendaring on my site along with an agenda view. Each event has a date, possible start time, possible end time, and possible end date/time.

Therefor I have two date fields associated with this content type - field_date(value, value2) where value is the start date/time and value2 is the end date/time.

How can I show dates and times separately so that I can use CSS to make a pretty agenda view using something like the following markup?

September 21

Fall Solstice (all-day-event)

October 18

Fall Festival

10:00 am to 11:00 pm

October 21-25

Sign up for pie eating contest

9:00 am to 4:00 pm

I've looked at using the formatter module (explained here: how do I add extra classes to a date field at views?) but could not figure out how to use the formatter with two date variables for my Event content type.

Any help?

I had to do something similar recently. I created a views page and outputted the same Date field twice. I also had two different date formats set up. One showing only Month and Day, and the other format only showing time. Then I assigned the first "Date" field the date format, and the other the "time" format. Afterwards I was able to style them as I pleased.

In the field date settings, I had it to where it also showed multiple, but only first and last with a " - " seperator in order to output "September 11 - September 14" for example. The same can be done for the time formatted field.


How to link different contents together and display the linked content on the same page? I am fairly new to Drupal and would need some help.

on my site I have to show a few images (A - B - C - D ) created by a content type X.

Each of these images will link to a different content Type Y ( 1 - 2 - 3 - 4 ).

So when I click on A , the content 1 should show below it. Same for content B -2 , C -3, D-4.

I am not sure how to achieve such a result and what are the tools to use.

Thank you for your help.

Images are just media assets on a site. By which I mean you're relating something specific in X to another thing in Y -- you could just as easily relate content titles.

You likely want to either relate things together using Tagging via Taxonomies. Taxonomies can also have associated images for example. Or, you want to relate content around with relationships:

Entity Reference
Relation

Without a concrete mocked-up example with wireframes and in-depth explaination of requirements .... good luck.


How do I add a menu item to the main navigation from a custom module in Drupal 8? For my custom Drupal 8 module I want to add a link to the default main navigation menu of the site.

What parent ID do I have to give to insert my menu item into the main menu?

I currently have the following config in my_module.links.menu.yml:

entity.sss_topic.collection:
  title: 'Topic: Listing'
  route_name: entity.sss_topic.collection
  description: 'List Topic'
  parent: main

But that only adds a menu item into the "Tools" menu (the same effect as specifying no parent whatsoever).
However, parent: system.admin_structure does work correctly.

Do I have the wrong parent ID? Or maybe a bug?

You are missing the "menu_name" key as said on : https://www.drupal.org/node/2122241

this example should work :

demo.demo:
  title: Demo Link
  description: 'This is a demo link'
  parent: main
  route_name: demo.demo
  menu_name: main


How to send variable value in POST Method in Drupal How to send variable value to another page by using POST Method in Drupal?

It would just be a standard form with post as the method.

<form method="post" action="/other-page">
  <input type="text" name="yourfield" value="Value">
  <input type="submit" value="Submit">
</form>


Why is the content of the  tag no longer loading in Google Chrome? For some strange reason, the content of the <head> tag no longer loads in Google Chrome Inspector. The CSS files are still loaded.

Does anyone have a fix for this?

That is for sure not a Drupal problem. I'd check the page source to see the head contents; if they appear there, maybe there is an unclosed tag.


NoSQL vs Other SQL Drupal Setups What are the advantages of running NoSQL (ex MongoDB) over MySQL, PostGRE SQL or MSSQL in Drupal? Are the advantages gained from simply using the storage or does some Drupal configuration need to change?

MongoDB can be used to store most or all your entities into fast, document-oriented storage. This type of storage scales way better then the standard SQL based storage we have in Drupal core (which is based on a "one table per field" schema).

In the current state of Drupal 7, you would have:

The base table of the entity stored on SQL (ie. the users table, the node table, etc.)
All fields stored in SQL
The properties of the entities from their base tables duplicated in MongoDB

This allows fast querying on the entities on MongoDB, and the ability to add complex indexes that no Opensource SQL database support (including indexes across tables). At the same time, you don't lose interoperability because the base table of the entity is still stored in SQL and can thus be joined by modules that are still SQL-only (like Flag).

This type of fast querying is available thanks to the EntityFieldQuery mechanism, a way to build queries on entities, their properties and their fields in an abstract manner. The default implementation in core translate those queries to SQL, but the MongoDB module has a full-featured implementation that can satisfy those queries from MongoDB directly.

Thanks to the EntityFieldQuery backend for Views, you can easily leverage this power, by using the tools you are used to. The only downside is that relationships are not supported (but in practice you rarely need them anyway - and this can be worked-around by pushing additional data into the entity object and add exposing them as additional properties of the entity).

In a nutshell, as soon as query performance is a problem on your project, which happens as soon as you have a significant dataset (let's say starting at a few tenth of thousands of entities on a given entity type), MongoDB is a net gain for very very few drawbacks. Highly recommended.


How to create a simple list of links to Drupal panel pages? I would like to create a simple HTML menu made of links to pages A, B, C created in Drupal (but not all pages, only a subset). Unfortunately, menu's in Drupal are displayed as li lists, not just a list of urls, which adds bullets to the display.

A view displayed as unformatted list would be great, but you cannot create a view of miscellaneous page links.

I could create a mini-panel and hardcode the links, but hardcoding is always a bad idea. Ideally, there should be a way to set relative links to pages and let Drupal generate absolute links.

What would be the best way to create a simple a list of links to pages created in Drupal? A block or a mini-panels are acceptable solutions.

You could create a View of miscellaneous page links, if the list of links was actually a list of a series of nodes with a particular taxonomy term applied to them.

For example:

Create a taxonomy vocabulary called "Page Links", and create a new taxonomy term for it called "Custom Menu One". Then, tag each of the pages which you want included in your list of links, with this Custom Menu term.

Now, you can go into the Views UI, and create a block View which outputs all nodes which have the taxonomy term "Custom Menu" applied to them. You can set up the view to use fields, and output the title of each node as a link back to the original content.

You'll also be able to configure the display settings for the View so that the links are output as a List, or Table, or unformatted, etc.


Users chosen from a field in a content type see only their result I have a list of students who are users in my Drupal 8 site. I want to publish their result but I want each student to see only his/her result. I have a content type where I can get marks and an entity reference field from which I can get users. As I am the author of the node, I cannot use the content-author relationship. I have to match the user id chosen in the node to the logged in user. I am trying to use contextual filter on the entity reference field from where I get the user list, but not getting any result. Please help me with the same.

Views module doesn't control content access
Views module respects the entities permissions set elsewhere in Drupal.
There are Permissions option available in Views but that only controls that particular Views Display global visibility, it doesn't control the nodes/users visibility. You can set Views to be visible by a certain user role or some other permission, but it will only apply to that Views page/block, it will not apply to nodes that are listed in that Views results! Even if a user is restricted from viewing that Views, they will still be able to see the nodes listed in the Views if they visit the nodes through the individual nodes links.
To properly restrict access to content on your Drupal site you need to restrict it on the node level, not Views level. Once you have it sorted out on node level, Views will respect it, check access for each node and show only the result rows that the user has access to view. There is a way to turn of node access check in Views (under Advanced options) but that's not recommended and it's rarely used.
Use Content access modules, Views will respect them
In your case you want to restrict access in a very granular way, to show content to only the user that is referenced from individual content item. You can do that with the help of additional module(s), you should research Access modules on drupal.org that relate to entity references.
Some of the ones I can suggest to test:

Access by Reference
Permissions by field


how to create single flag for choosing multiple bookmarks? I want to create a flag which can be used to bookmark multiple content. In my site i am allowing user to publish their own articles. Each article has a genre type taxonomy. I want to make a flag which will be displayed below the article content page, and on clicking on the flag the user will be able to subscribe to both the article and its genre (taxonomy). I tried using flags for taxonomy but that flag does not appear on the bottom of every content page. Instead it appears on the view when we seea ll the content related to a genre. I am using drupal 7. Thanks for your help.

This is possible but you need to use the Flag API hooks and the Flag Actions module. Enable the Flag Actions module that comes with the Flag module if you haven't already. You will now have an option under the flag tab on the triggers page to fire off an action based on whenever anyone flags something with your flag.

/admin/structure/trigger/node

None of the actions available will match what you are trying to do but you can create one. In your site module (or create one), you need to just define two functions: the action definition hook, and the function that fires.

For the action definition, you're using hook_action_info() to declare a function

/**
 * Implements hook_action_info().
 */

function YOURMODULE_action_info() {
  return array(
    'MYFLAG_action' => array(
      'label' => t('Action to take after MYFLAG is flagged'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

and then you want to create the function to trigger your taxonomy flag

/**
 * Action function for report action
 *
 * @see action_example_action_info()
 */
function MYFLAG_action(&$entity, $context = array()) {

   // Use the name of the taxonomy flag here
   $MYFLAG = flag_get_flag("name of taxonomy flag");

   // add logic to find your taxonomy_id, probably from the node object available through the $entity variable

   $taxonomy_id = ( SOME OPERATION )

   //execute the flag operation
   $flag->flag('flag', $taxonomy_id);

}

Finally, flush cache and go back to your triggers page to associate the trigger of flagging a node with your new custom action.


drupal 7 display user info for current user I need to display name, role, photo of current user. I'm use views, in Advanced settings add Contextual filters select Content: Author uid and in settings of it select Provide default value ,in type selectbox choose User ID from logged in user. But in fields i haven't field 'user:name'. If i create relationship content : author , user name will be displayed, but only for users, that published node. At the end, i want see like this

Hello, SmithJN
Role: Authorised user
Photo: [photo]

When you create the view, at the very first screen, you have the option to select the entity type on which you want to create the view. (thank J.Reynolds)

Then in Fields add Field Name, Role, Image
In Fileter Criteria add filter User : current

It's all !


Get orders with free items I have a pricing rule to do some items free.
User can purchase only 3 items per month.

Question is how to programmatically get count of free items purchased by user?

I needed to do something vaguely similar the other day and the only way I could find was to go into the db tables directly to grab the data. The problem is you need to join the line item and orders tables (for the order status), which you can't do with (for example) an EntityFieldQuery.

I think you'd be looking for a query simliar to:

SELECT SUM(li.quantity)
FROM {commerce_order} o
INNER JOIN commerce_line_item li ON li.order_id = o.order_id
WHERE o.status = :status
AND li.line_item_label = :sku
AND order.uid = :uid

But it'll probably need some tweaking for your needs (to get results for orders created between certain dates for example).


Getting fields of a content type in template file - creating a slideshow I need to add a slideshow (each slide containing headline, image & html text) in my frontpage. I've decided to create a custom content type named slideshow which should have above fields.

I've figured out the necessary .tpl.php file (page--front.tpl.php) in which I'll add codes to go for the slideshow.

What I've done already

Created a custom content type named slideshow with all the appropriate fields
Added all the necessary html for the slideshow in the .tpl.php template file - with necessary javascripts already included using the .info file of my theme.

Now the problem:

I think I'll fetch data from database & populate the variables needed in .tpl.php file in: preprocess function of template.php file of the theme. How do I retrieve the fields of slideshow content type from database?

Please help!

If I understand well your question, I guess that node.tpl.php is more suitable for use templates per content types an control over individual fields:

page.tpl.php: Default theme implementation to display a single Drupal page.

node.tpl.php: Default theme implementation to display a node.

About how to name your templates according your needs, see this documentation: Drupal 7 Template Suggestions http://drupal.org/node/1089656. Regarding your case, I guess, a template for content type, the name could be node--slideshow.tpl.php. see this answer that have information related with node.tpl.php.

and about how to see your fields, the same link to the answer have one example:

I have a field called field_demotext1, then this is the way that I can use to call their respective value inside any custom html zone of a node layout:

print $content['field_demotext1']['#items'][0]['value'];

whit print_r($content); (or dsm($content); if you use Devel module) you will see fields that can be pulled. this screenshot is using dsm($content); related with the example;

Render Drupal API is an alternative to the previous way. In this way you does not need seek the file using dsm() or print_r()

print render($content['field_demotext1']);

Also, seems that field_view_field is another alternative to render Drupal fields. see this related document:

I hope information be useful.


How do I use PathMatcher::matchPath() for a wildcard path? I am trying to use PathMatcher::matchPath() to match a string of paths using a wildcard pattern.

I'd like to match any path containing /topic* so if the path matches, I'd like to add a body class for pages that have /topic, /topic/foo, /topic/bar, etc..

The code I am using is the following.

function mytheme_preprocess_html(array &$vars) {
  // Define the current path.
  $current_path = \Drupal::service('path.current')->getPath();
  // Define the pattern using a string.
  $patterns = "/topic/*";
  // If the path matches the pattern.
  if (\Drupal::service('path.matcher')->matchPath($current_path, $patterns)) {
    $vars['attributes']['class'][] = 'is-topic';
  }
}

The code doesn't work to match this pattern so no class is added when I am on any of these pages.

My Xdebug info is as follows for the page that has the path topic/review-procedures

$current_path = /node/62
$path_alias = topic/review-procedures

Note that some pages with /topic/ in the path will not be nodes however, that is why I am trying to do the path matching.

Am I correctly using PathMatcher::matchPath()?

In your sample you were comparing the internal path (/node/123) with a path alias pattern (/topic/*). This won't work. You need to do the matching with the path alias instead.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  if (\Drupal::service('path.matcher')->matchPath($current_alias, '/topic/*')) {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

You could achieve the same by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}


Can I download all data from drupal.org? Does drupal.org make any data dumps available for the content it hosts? I would love a full dump of module / theme / distribution data, etc. without having to scrape the site.

http://updates.drupal.org/release-history/project-list/all is a XML-document that lists all projects and their releases. It's a large file, but should provide all the info you need.


Check if viewing a Views page How do I check if the page I'm viewing is a Views page? I want the breadcrumbs to be hidden if the user is viewing the view page I made, which I named "Products."

I am using Drupal 7 and Views 7.x-3.0-beta3.

Following Jeremy French reply, I must say that you can do it like this :

if(function_exists('views_get_page_view') && views_get_page_view()){...YOUR CODE HERE...}

Taken from here:

  views_get_page_view() finds out what, if any, page view is currently
  in use. If it returns NULL, then the current page is not a views'
  page.


FontAwesome tags removed when switching between Source and Wysiwyg I am using http://fortawesome.github.com/Font-Awesome/ - popular iconic font

When I insert "i" tag i.e.  it is saved only in source mode enabled, but removed from html when saving in wysiwyg mode.

How to avoid removing i tag? (using Ckeditor with Drupal 7 and Wysiwyg module)

As Vic Nicethemer pointed out - the solution (for me) was to add &nbsp; within the <i> and </i> like so: <i class="icon-facebook">&nbsp;</i>.

CKEDitor removes elements that do not have any internal content...


Comments not showing up when set to open and assigned a region in manage display in drupal 7 I just set my comments for my content type to "open" and assigned the comment field to show up in the full content manage display. But it doesnt show up when viewing in my full display node. I tried changing the theme and it still doesnt show up. How can I debug something like this?

My issue was that comments was "CLOSED" for the nodes I already created as the default setting initially was set as "CLOSED". Even thought I set the comment settings to OPEN on the content type, this doesn't affect previously created work.

Solution was to bulk update all the nodes types to open comments with the following sql:

UPDATE node SET comment = 0 WHERE type LIKE "MY_NODE_TYPE_HERE";


Enable/open comments on all posts of a content type When I created a content type, I chose to keep the Comments hidden. Now I have many posts of that content-type and I want to open the comments, which I did by editing the content type, but it did not open comments of any posts of that content-type.

How do I open comments on all the posts of a content type at once?

How do I remove that little help box under comments text area?

Or directly into the database with :

UPDATE `node`
SET comment = 2
WHERE comment = 1

and

UPDATE `node_revision`
SET comment = 2
WHERE comment = 1

Where : Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write).


Update Webform and not Add if there is an existing value in one of the fields In Drupal 7, I have a field which stores Usernames of the user. If a submission is made by a user, it stores its username.

All I want is that if there's an existing submissions made by a user, and that user makes an entry in the form, the webform should update the previous entry rather than create a new one.

Any idea how it can be achieved?

Thanks.

this would be heavy on resources since it needs to search all 'submissions', searching for the user. An alternative idea:

use Rules to create a 'submission' at new user registration, setting the user as author.
use Node Limit to limit each user to one of that type
use Rules to check when trying to create a new 'submission' (url contains...) and redirect to the existing 'submission' page for that user


Changing a menu's target nodes for each page For a Drupal 7 website, I need to have 2 types of menus: 1 menu with a list of countries, each menu entry pointing to a given node. For each country page, I need to display a 'characteristics' menu, with fixed items (e.g. population, incomes), but (of course) the targeted nodes have to be changed in function of the current country. (Clicking on the 'characteristics' menu entries opens a page which is different for each country.)

Is there a module for that in Drupal 7, or a way to do that programmatically?

I found an answer to my question: the best is to use a programmatic approach by using the l() function that is available anywhere within a Drupal installation. It accepts three arguments:

$text: The text that will be visible to users for your link
$path: The URL that the link will go to when clicked.
$options: An associative array which allows to set additional parameters to further customize the link with CSS classes etc…

A good introduction is found here: http://www.pixelclever.com/how-and-why-use-l-function-create-links-drupal-programming.
This function can be used in the template files, or directly from a node body.


Migration is not able to find legacy database tables for some migrations The hosting server I am using is Pantheon.
I'm trying to migrate taxonomy over from D6 to D7 with a custom migration class.  The problem is that I'm getting different behaviors on my local repo and the one  on the server.  On the server, I get an error saying that

  Migration failed with source plugin exception: SQLSTATE[42S02]: Base
  table or view not found: 1146 Table
  'legacy_database_name.migrate_map_tdmchanneltermparent' doesn't exist, in
  /srv/bindings/3b34ee5b39e94f12ad1de632af512a5b/code/includes/database/database.inc:2171

I'm not sure why it is trying to connect to the legacy database for the map in this migration.

Here is my migration class:

class chalkTermParentMigration extends tdmTermMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->arguments = $arguments;

    $this->description = t('Chalk Term Parent Migration');

    $query = Database::getConnection('mig_dest', 'legacy')
      ->select('vocabulary', 'v');
    $or = db_or()->condition('v.vid', 10)
      ->condition('v.vid', 11, '=')
      ->condition('v.vid', 12, '=')
      ->condition('v.vid', 20, '=')
      ->condition('v.vid', 21, '=')
      ->condition('v.vid', 25, '=');
    $query->condition($or);
    $query->fields('v', array('vid', 'name'));

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationTerm('chalk');

    $this->addFieldMapping('name', 'name');
    $this->addFieldMapping('field_legacy_id', 'vid');

    $source_key = array(
      'vid' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => 'Legacy Vocab ID',
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationTerm::getKeySchema());

  }

}

Here is how I have my legacy database connection information set up:

if (!defined(PANTHEON_ENVIRONMENT)) {
  $databases['mig_dest']['default'] = array(
    'database' => 'abc',
    'username' => 'abcdev',
    'password' => 'qwe123',
    'host' => 'localhost',
    'port' => '',
    'driver' => 'mysql',
    'prefix' => '',
  );
  $databases['default'] = $databases['mig_dest'];
} else {
  $databases['mig_dest']['default'] = array(
    'database' => $_ENV['DB_NAME'],
    'username' => $_ENV['DB_USER'],
    'password' => $_ENV['DB_PASSWORD'],
    'host' => $_ENV['DB_HOST'],
    'port' => $_ENV['DB_PORT'],
    'driver' => 'mysql',
    'prefix' => '',
  );
}

$databases['legacy']['default'] = array(
  'database' => 'legacy_db_name',
  'username' => 'uname',
  'password' => 'passwd',
  'host' => 'legacy_db_host',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => '',
);

legacy_database_name.migrate_map_tdmchanneltermparent is a table typically made by the Migrate module to perform a mapping between source DB data and destination DB data. There is typically migrate_map table(s) and for instance migrate_messages table(s).

Be sure to properly Import or Rollback migrations. If you clearing the database by hand and dropping any of these tables, Migrate can get confused. Sometimes I occassionaly MySQL Truncate these tables by hand during my job workflow, but then you need to be careful and understand what migrate is doing -- how it's mapping processed data or registering migrations.

EDIT:

Then as a work around I suggest following the documentation for Map Tables heading section and explicity define the connection you want the mapping table created on. Since you have what looks like a local test migration setup and a Pantheon setup add this ... = new MigrateSQLMap( ... ); in an IF statement to point to the correct Drupal destination connection name.

  When you construct the MigrateSQLMap object, add a fourth argument to
  tell it explicitly the connection on which to create the mapping
  tables.


"Allow multiple values" vs "Allow multiple filter values to work together" In Views, when adding an Argument for a vocabulary term id, I'm presented with the following 2 options:

Allow multiple values
If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

Allow multiple filter values to work together
If selected, multiple instances of this filter can work together, as though multiple values were supplied to the same filter. This setting is not compatible with the "Reduce duplicates" setting.

The first option is perfectly clear to me. The second, however, I'm struggling with. What exactly does it do, and how does this differ from the "Allow multiple values" option?

Can the two of these options be used together? If so, what would be the expected outcome?

Thanks!

Allow multiple filter values to work together is used when you want to pass multiple arguments to and match against one field.
In other words allows for 'many to one' joins

In a sense it is similar to 1, 2, 3, however if you need to pass multiple sets like 123+345 and 889+678 there need to be 2 separate joins to the same table.

(assuming sometable has multiple results for your desired value like:

|nid|yourvalue|

|1  |123      |

|1  |345      |

|2  |678      |

|3  |222      |

|1  |789      |

|1  |823      |

|1  |845      |

|2  |678      |

|3  |222      |

|1  |889      |

select node.title from node node
join sometable sometable_1 on sometable.yourvalue in (123,345)
join sometable sometable_2 on sometable.yourvalue in (889,678)

Therefore 'Allow multiple filter values to work together' is the only way to get view to return nid 1

this is useful when you need to pass arguments that come from different sources (i.e. 1 could be taxonomy terms from 2 different vocabs).

I used this only when dealing with entityreference field that references terms from different vocabularies


weird features behavior - constantly adding and removing entries from taxonomy.inc I'm using features and I commit the features module to my repository to track changes.

Every now and then (after drush fu foobar) I see the following change to the foobar.features.taxonomy.inc file:

@@ -16,8 +16,6 @@
       'hierarchy' => '0',
       'module' => 'taxonomy',
       'weight' => '0',
-      'language' => 'und',
-      'i18n_mode' => '1',
       'metatags' => array(),
       'rdf_mapping' => array(
         'rdftype' => array(
@@ -42,8 +40,6 @@
       'hierarchy' => '0',
       'module' => 'taxonomy',
       'weight' => '0',
-      'language' => 'und',
-      'i18n_mode' => '1',
       'metatags' => array(),
       'rdf_mapping' => array(
         'rdftype' => array(
...

Note the removals in the above diff starting with -. That takes place at the same time for all of my 15 taxonomy vocabularies.

After some development and in the next drush fu foobar those exact lines are added back.

In the meantime of that cycle:

I haven't touched anything on those taxonomies
I haven't updated features (I use the latest)

Any idea why this is happening?

Edit: More info
After the offending lines are added in the foobar.features.taxonomy.inc file if I do a drush cc all then I get the following output in the console:

Reset language for all terms.

Reset language for all terms.

[...]

Reset language for all terms.

That is 15 times if I have 15 taxonomy vocabularies.

Taxonomy Edge optimizes tree functions for taxonomies. It provides a transitive closure table data model for easily managing hierarchical terms. It was created to avoid recursive functions when fetching all children, and to avoid the not-quite-so-scalable memory footprint of taxonomy_get_tree().

The provided patch contains overrides for the core module Taxonomy in regards to taxonomy_get_tree() and taxonomy_select_nodes().


How do assign a role to user after add to cart in ubercart in drupal 7? I am using ubercart for my site.. I need to assign a role to user after shopping with price base.. If user does $300 shopping then role 10%-role . if user does $400 shopping then 20%-role etc.. And remember these role next shopping.

Try to do this using Rules.

Add a new rule on event complete checkout.
Give your required conditions.
Add Assign role to user as action.

For your scenario you can do it using multiple rules.

Hope this will help you.


How can I get the uploaded file path of a contact form in drupal 8 I'm using the hook_mail_alter() to create a custom email for contact forms.
I was able to get the fields labels and values and use a twig template to send the email. Most of it is working just fine, but my problem is when I use file fields on the contact form. I want to be able to show the path of the uploaded files. When I use the default drupal email, it shows the paths at the end of the file. I want to do the same thing at my custom email. Can anyone tell me how to do this?

You can get the file entity directly from the field and check if the field is not empty before applying any methods on the file object:

/** @var \Drupal\contact\Entity\Message $contactMessage */
$contactMessage = $message['params']['contact_message'];
$file = $contactMessage->field_file->entity;
if (!empty($file)) {
  $fileInfo[] = [
    'value' => $file->getFilename(),
    'url' => $file->url(),
  ];
}


Plus or minus sign using Apache Solr When I enable Apache solr, everything works perfectly fine except for the following scenario.

When I do a keyword search using character - (minus symbol), or +, I get the error:

  The Apache Solr search engine is not available. Please contact your site administrator.

Do you know why this happens?

You need to be using Apache Solr 3.1 and have the edismax plugin enabled to allow for these boolean operator queries. You should see this in your Solr logs as 'an unknown query type' error. This should be an option in the ApacheSolr Drupal module since this patch but if not (or if you're running Apache Solr 1.4.x) you can check out this ticket on the solr forum for instructions on how to patch your solr and solrconfig.xml to allow for edismax queries.


Programatically create a menu? I can login to /admin/structure/menu and create a new menu. How can my module create a custom menu like that?

There is a function called menu_save that looks like it will help you out (I assume drupal 7)


Change taxonomy term field into text field in content-type Is there a way to transform a taxonomy term field into a simple text field? I need to keep all the terms present in the taxonomy field and have them separated by a comma.

Eventually, I simply used a PHP script I execute in mysite/devel/php to copy my taxonomy term field value to my new text field:

$nodes = node_load_multiple(array(), array('type' => 'contact'));
foreach($nodes as $node) {
  if ($node != NULL) {
    $tid = $node->field_title['und'][0]['tid'];
    $term = taxonomy_term_load($tid);
    $name = $term->name;
    $node->field_function_title['und'][0]['value'] = $name;
    $node = node_submit($node);
    node_save($node);
  }
}


Drupal 8 update via drush removes files from vendor folder I recently made a core update with drush for D8.
After the update I saw that it removed a folder from the 'vendor' folder on the server? Why did that happen?

The module has been installed via Composer because it needs dependencies to be installed: https://www.drupal.org/project/alinks

Re-installing the dependencies, works:

composer require "wamania/php-stemmer"

Is there something I did wrong? Do I need to update the core in a different way rather then using drush if you have installed modules via composer?

Removing the module via backoffice D8 and then removing folders from 'module/contrib' and 'vendor' and then re-installing the module works, but that is just not the way to do.

Thanks.

This is normal, because an update with Drush overwrites vendor and composer.json. So if you've installed a module via composer you need to reinstall it the same way (but you should be able to avoid a reinstall in the backoffice if you manage to get the code base right before running update.php or drush updatedb).

Updating core with Drush is depracetated and this function is removed from Drush 9.0. So you might consider switching core to a composer based install.

Edit to answer this comment:

  Well I'm a bit lost here on how to manage this, so more info is
  required I guess? Today I tried to install a module with composer
  (fieldblock) but could not find it? So I had to install it with drush
  ... For me it is not really clear right now what the best practice is
  and how to avoid problems in the future when having a core update ..

It's still OK to manage core and module updates with Drush as long as you use only modules which can be installed by Drush and don't mix it with Composer. However, when you start to use composer only modules you should really think about switching over to a composer based Drupal install. It's possible to start a new composer based project and keep the existing database, see this great answer from @greg_1_anderson Updating core with Composer doesn't work


Print rendered entity reference value How can I print the rendered values of an entity reference field into node.tpl.php?

I have an entity reference field called Instructors which references users.  Using Devel I can find the target_id of entity reference items, but I can't for the life of me figure out how to render these ids.

You can try something like this

// $node represents the node object
$wrapper = entity_metadata_wrapper('node', $node);
$instructors = $wrapper->field_instructor->value();

Now in instructors you will have each instructor user object and you can print what ever information you want to print from it.


Disqus Comment for one role type I have installed Disqus on localhost and want users of a particular role type only to be able to comment. Basically, there are free and premium users but I wish to allow only the premium users to be able to comment using Disqus.
The comments should be visible to every role type but the ability to comment should be given to only the premium users and the administrator.
It would be great if someone could help me out with this !

in admin/config/services/disqus set the location to block

then in admin/structure/block put the "Disqus comment" block below the "Main page content"

Now, edit the Disqus comment block, scroll all the way down, under Visibility Settings, click on roles and check mark premium and administrator.

Edit:

Unfortunately, you can't remove the comment box. Disqus used to offer a way to do it, but now they don't.

The only workaround, would be to create a block that is displayed for anonymous users and non premium authenticated users only.

Then inside that block put css to hide the comment box behind/underneath the article body.

For Example:

<style>
 #disqus_thread { z-index: 1; position: relative; top: -180px;}
 .article-body { z-index: 2; position: relative; background: white;}
</style>

Unfortunately, with this tactic you would lose the comment count and the sort option. Although, you could display the comment count using the views module.


How to wrap views-view-fields.html.twig with html container element? I have a block view with an image field.

I know how to theme this field :

views-view-fields—my-images.html.twig

How can I wrap this loop with an element like :

I’ve tried different solutions without success.

Theme the block twig template :

If I use block--views-block--slider-images.html.twig

Of course it doesn’t work because there is no possibility to theme the field inside this twig template.

I’ve tried to add my wrapper in the header and footer option in the view but even if it works, it is not perfect since I need to have a better control on the html (I’m doing a slick slider, I know there is a module but I don’t want to use it).

I’m trying to do something I can do in node :

In  node—lorem.html.twig :

{{ content.field_my_images }}

In field--field-my_images.html.twig

    {% for item in items %}

            {{ item.content }}

    {% endfor %}

I’ve also checked all the "rewrite results" options in view but didn’t manage to add a wrapper.

I prefer a solution where I can create my custom html strcucture like the above example with a loop.

EDIT

Here is the HTML structure I need :

your content

your content

your content

Option 1

You can by copying (the entire code) from core views-view.html and paste it in your theme's template folder and rename it views-view--[view-name].html.twig and then add your class to this template file.

replace {{ rows }} with

<div class="slider-article">
{{ rows }}
</div>

Option 2

Copy from core views-view-fields and paste it in your theme's template folder, rename it views-view-fields--[view-name].html.twig

Then add your div with class before {% for field in fields -%} and add close tag after {%- endfor %}

Option 3 (maybe)

You can add it via the Views UI by clicking on "None". But this will add the wrapper to the entire view, which you may not want.


javascript aggregation disables the font-your-face module and views-slideshow on the main page When I turn on the aggregate js option on my drupal commerce (kickstart 1) site, the font-your-face (dealt with by FYF module) and the slideshow on the main page stop working. The fonts seem to show up fine on the other pages.
Does anyone has any idea why it might be so?
I obtain a "syntax error" in the JS console.

It turned out the problem is with the fields slideshow module and its use of js/jquery libraries.
I've realised that JS error happens  after calling some slideshow libraries, so i googled for aggregate js / field slideshow.
As per https://drupal.org/comment/7874537#comment-7874537 , I used the 2.1.x version of the imagesloaded library and everything worked nice afterwards.


How to flag a View's item (with AJAX) when hovering or clicking it? In my previous question How to mark a Message as 'viewed' when a user sees it in a View?, I explained that I'd like to flag a Message when it's hovered or clicked in a View. @Geoff suggested to create an AJAX callback in his answer, but I've no idea how to accomplish that.

How can this be done? Is this the easiest approach?

The entire process may seem a little complicated at first, but it's easy once we break it down into smaller parts and understand how it all comes together.

Basically we have two parts which we need to address. Firstly the "backend" logic where we will be implementing hook_menu, allowing us to receive an AJAX request via a custom menu route and then flag our Message as seen. Then secondly the "frontend" logic where we'll be implementing a little bit of jQuery to trigger our AJAX calls (using the proper Drupal.behaviours way of course) :)

With this example I'm assuming you have created a Message entity and have added a boolen field to it. We'll use this to store our flag to indicate whether the Message has been "seen" or not.

Once you've done that, go ahead and create a simple custom module and implement hook_menu using the following example:

/**
* Implements hook_menu().
*/
function my_example_menu() {
  $items['my_example/message/seen/%'] = array(
  'page callback' => 'my_example_flag_message',
  'page arguments' => array(3),
  'access callback' => 'my_example_message_access',
  'access arguments' => array(3),
  'type' => MENU_CALLBACK,
  );
  return $items;
}

Now before we start writing the page callback function which will flag our message as seen, we need to make sure that we implement proper access rights. This ensures the user accessing our custom menu route actually "owns" the message, and isn't some malicious hacker trying to annoy us and mark all the messages on your system as "seen" as some kind of lame prank haha! See below:

/**
 *  Access callback to ensure user has the right to message entity
 */
function my_example_message_access($msg_id) {

  global $user;

  $access = TRUE;

  //if anonymous user then throw access denied
  if(!$user->uid) {
    return FALSE;
  }

  //load our message entity and check the uid
  $msg = entity_load('message', array($msg_id));

  if($msg[$msg_id]->uid != $user->uid) {
    return FALSE;
  }

  return $access;
}

You can test the access callback by visiting http://example.com/my_example/message/seen/[MESSAGE_ID] and trying out different message id's logged in as different users. If a message doesn't belong to you, Drupal should be giving you the old "Access Denied" message.

Now that we know our AJAX route is protected by Drupal access control, we can go ahead and write the page callback function which will flag our Message entity as "seen":

//page callback function
function my_example_flag_message($msg_id){

  $response = array('success' => FALSE);

  //first check that the message id argument is present
  if(!isset($msg_id) || $msg_id == 0){
    return drupal_json_output($response);
    drupal_exit();
  }

  //load our message entity
  $msg = entity_load('message', array($msg_id));

  //set the flag to TRUE
  $msg[$msg_id]->field_YOUR_FIELD_MACHINE_NAME[LANGUAGE_NONE][0]['value'] = 1;

  //save our message entity
  if(entity_save('message', $msg[$msg_id])){
    $response['success'] = TRUE;
  }else{
    $response['success'] = FALSE;
  }

  //return the status of our attempt at saving our entity back to the front end
  return drupal_json_output($response);
  drupal_exit();
}

Great so if you made it this far and didn't fall asleep reading that wall of text, then you should now have a working route which accepts a message id, and marks that message as "seen" (as long as it belongs to you). :)

Then our final piece of the puzzle is attaching a Drupal behaviour to each View row, enabled as to fire an AJAX call to our Drupal route and trigger our backend logic. I'm assuming you know some basic jQuery, but here's the example script you'll need to add to your page using the drupal_add_js() function or something similar. We'll call it my_example.js:

(function ($) {
  Drupal.behaviors.my_example = {
    attach: function(context, settings) {
      //you can adjust this jQuery selector to anything you like
      $('.view-row').click(function(e){
        //I'm assuming the message ID is in view row markup as a data attribe (eg: data-message-id="[MID]")
        var msgID = $(this).data('message-id');
        //trigger our jQuery AJAX call
        $.ajax({
          type: 'POST',
          url: '/my_example/message/seen/' + msgID,
          dataType: 'json',
          data: 'seen=1', //added some arb param here as an example
          beforeSend: function(){
            //if you want to do anything fancy before the AJAX call do it here
          },
          success: function(response){
            //if we successfully updated the message
            if(response.success == true){
              //do something fancy like display a message if you like
            }else{
              //if the update failed display an error message
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            //if there was some kind of javascript / jquery error you can debug it here
          }
        });
      });
    }
  }
})(jQuery);

And hey presto, we now have some jQuery attaching our Drupal behaviour to each View row which when clicked, will fire off our AJAX trigger and then get Drupal to update your message.

This design pattern opened up a whole host of other ideas (think AngularJS and other exciting geeky tech) for my use of Drupal. I hope it helps you too :)

Obviously if there's anyone else out there with a better implementation please let me know!


How can I auto-increment available options for an integer field? I have a set of available options for an integer field:

2011|2011
2012|2012
2013|2013
...etc

The thing is I want years all the way to 2050. Is there a way to set a step increment in this field? I could create the list in a text editor and paste it, but I'd love to find a more elegant solution using code or some way of incrementing the options.

I could create the list in a text editor and paste it

You can use Microsoft Excel. on A(1) put 2015 on A(2) put 2016.

Highlight both cells, click on the bottom right corner (you will get a + cursor) and drag down.


How do I insert HTML onto every page? I've got the following code in my module. I'm trying to get it to insert some HTML, ideally at the start of <body>, but it seems that my call in hook_init() isn't working - what would be the right hook to call this in? I'm hoping it will just render slidedown.tpl.php after <body>.

<?php
function slidedown_init() {
    drupal_add_js(drupal_get_path('module', 'slidedown') . '/slidedown.js');
    drupal_add_css(drupal_get_path('module', 'slidedown') . '/slidedown.css');
    slidedown_insert_html();
}

function slidedown_insert_html() {
    return theme('slidedown_template');
}

function slidedown_theme() {
    $themes = array (
        'slidedown_template' => array(
            'template' => 'slidedown', // your template file called slidedown.tpl.php
            'arguments' => array(),
        ),
    );
    return $themes;
}
?>

You probably want hook_page_build():

function slidedown_page_build (&$page) {
  $path = drupal_get_path('module', 'slidedown');

  drupal_add_js($path . '/slidedown.js');
  drupal_add_css($path . '/slidedown.css');

  $page['page_top']['slidedown_template'] = array(
    '#weight' => -1000,
    '#markup' => theme('slidedown_template'),
  );
}

I can't remember if that hook is too late to add JS and CSS.  You may need to put those in a template_preprocess_html().  That is a better choice that hook_init().


Showing "Explanation or submission guidlines" How can I get the Explanation or submission guidelines (one of the boxes when you edit/create a new content type) when the form is displayed? It obviously works fine in the default themes, but I can't figure out how/where to put the info to get those guidelines to be displayed. I'm not even sure which template it belongs in (node, page, region, etc).

The "Explanation or submission guidelines" set on the edit/create content type form is actually displayed using the "System help" Block. So you just need to add the "System help" block to a region in your custom theme and it will be displayed there as long as you are actually printing the region in your theme.

I figured this out using the Theme developer module, which really is an extremely useful module for this kind of stuff. When you enable Theme developer, it adds a checkbox labeled "Themer info" to the bottom of each page. Check that box then click on any element in the page and you'll see information about how that element was themed. For example, enable Theme developer and use one of the default themes where the "Explanation or submissions guidelines" content is displayed correctly. Check the "Themer info" box and click on the submissions guidelines text, it will popup a box with information about how the submission guidelines where themed, like the image below. This should give you all the information you need to figure out how to theme something, or at least where to start looking.

NOTE: The Theme Developer module can actually end up breaking parts of your theme when enabled. It injects lots of <span>s to do it's magic. If something looks broken in your theme, disable Theme Developer and check again. Also, don't enable Theme Developer on a live site.


CKEditor strips all inline CSS and some tokens I'm trying to add a color and font size to some text using the CKEditor. As soon as I save it these are stripped out.
I've also noticed some tokens are stripped down when certain settings are enabled.

I went to add a bit of text in a different font and color but when I saved it and viewed the text the spans were stripped of their "style" tag.
I went to config/content/formats/manage and enabled Limit allowed HTML and added span to the list like so :

<a hreflang href> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol type start> <li>
<dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src alt data-entity-type data-entity-uuid>
<u> <s> <p> <h1> <pre> <table> <caption> <tbody> <thead> <tfoot> <th> <td> <tr> <span style>

After saving this all the attributes inside of span are still stripped. I also noticed that many of the tokens I was using (such as site:url) are broken and only half of it remains.

I went back and disabled the Limit allowed HTML option and then when I saved the text the styles and token would save properly.
When viewing the text in an email, the tokens had worked just fine but the span had it's css striped.

I've tried looking for an answer but most are saying I need to enable and add the span to the limit html option but this definitely does not work for me.

There is also Correct faulty HTML enabled, would that be a problem for this?
How can I enable in line styling with the CKEditor?

See

https://drupal.stackexchange.com/a/282373/79805
https://stackoverflow.com/a/60836391/9302793
https://drupal.stackexchange.com/a/215158/79805

for some further reference :)

You could try using custom CKEditor styles. For using custom styles you'll need a custom module.

MYMODULE/

/MYMODULE.module
/MYMODULE.libraries.yml
/css/style.css

MYMODULE/MYMODULE.module:

function MYMODULE_editor_js_settings_alter(array &$settings) {

  foreach ($settings['editor']['formats'] as $name => $value) {

    // You can check for specific editors.
    // if ($settings['editor']['formats'] == 'basic_html') {
    //
    // }

    // Otherwise, add our custom styles to all editors.
    $settings['editor']['formats'][$name]['editorSettings']['stylesSet'] = [

      [
        'name' => 'Custom Color Text',
        'element' => 'p',
        'attributes' => [
          'class' => "custom-color-text"
        ]
      ],
      [
        'name' => 'Custom Color Link',
        'element' => 'a',
        'attributes' => [
          'class' => "custom-color-link"
        ]
      ],
    ];
  }
}

function MYMODULE_preprocess_node(&$variables) {

  // Attach our styles library.
  $variables['#attached']['library'][] = 'MYMODULE/styles';
}

// Nice to haves:
function MYMODULE_ckeditor_css_alter(&$css, $editor) {

  // Add our ckeditor style sheet to ckeditor.

  // This adds our theme styles to the editor field.
  $css[] = drupal_get_path('theme', 'MYTHEME') . '/css/style.css';

  // This adds our styles from the module directory.
  $css[] = drupal_get_path('module', 'MYMODULE') . '/css/style.css';
}

MYMODULE/css/style.css:

.custom-color-text {
  color: #f00;
}

.custom-color-link {
  color: #00f;
}

MYMODULE/MYMODULE.libraries.yml:

styles:
  version: 1.x
  css:
    theme:
      css/style.css: {}

These will now be available in the "style" dropdown in the CKEditor field.


Advice needed on approaching to Drupal 6 and jQuery Mobile I'm pretty new to this 'world of Drupal', and I've got this project, where I need to build a jQuery Mobile site based on an existing Drupal 6 site.

The mobile site is somewhat different in it's structure, but needs to get some data/content from the original site.

What is the best approach to his project? Should I build the mobile site based on the same Drupal-installation, as the original site? Or should I build a new site using Drupal 7 and then somehow export/distribute content from the original site?

I've read a couple of articles claiming it's quite difficult to upgrade jQuery to version 1.4.4 in Drupal 6, which is needed to run jQuery Mobile. Is that so?

My concern is, that I'm not a PHP Jedi Master (though I know some PHP), and therefore it would be great, if some could tell me, what the best approach is to this.

I found this articles yesterday: http://www.adyax.com/en/tutorials/make-mobile-version-your-drupal-site-using-jquery-mobile-and-some-magic/lets-get-started. Is this what I should be doing?

I personally don't recommend splitting the project in 2 sites but rather in 2 themes. If the project is slightly different (I assume you however use the same database) then try to customized it via theme (and theme functions).

I suggest you use the Omega/Fusion Theme which are responsive themes.
A responsive theme doesn't need a special redirection.

However if you need more customization in additional install Mobile Tools Module.

Then create a domain called m.domain.com in additional to your site domain.com and set inside the Mobile Tools Module based on a agent to switch to the theme needed.

There's indeed no need to install Drupal again.
You should ask your host to treat the m.domain.com as an alias for domain.com. That way it points to the same Drupal installation and the theme switch can take place.

If you don't have a mobile to test install Firefox addon: https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/