Installing Drupal on an all-Nginx server - OOB or should you customize / replace any file? When one downloads Drupal, she gets several .htaccess files with it. These files contain Apache directives written in the Apache variant of the Perl Compatible Regular Expressions (PCRE) language holding server, as well security related configuration directives.

My question can actually be comprised of the following 2 questions, and I ask these as one who plans to move working with a VPS and got many recommendations instilling Nginx on it (if I'll use it, I would want it to be the sole server, and not just a reverse proxy as it seems to me the best way to develop familiarity with it, in the long run):

Should or can Drupal 8 work out-of-box with Nginx?
Where are the Nginx parallel to .htaccess (and to any other Apache conf file, if there is one) in the Drupal instillation and if there aren't any, how can one know how to construct them? I ask as I try to understand if one must be a PCRE genius for constructing these in case they don't come with Drupal.

Nginx doesn't support .htaccess files without an extension. You could install that extension, but most don't.

Drupal doesn't include sample rewrite config for Nginx, so there are a few extra steps when setting up the vhost, but nothing major. You'll also need to make sure FPM is set up and configured correctly, but that goes without saying when using PHP with nginx.

There's a pretty sensible looking sample config on the Nginx site itself:

server {
    server_name example.com;
    root /var/www/drupal8; ## <-- Your only path reference.

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        # Security note: If you're running a version of PHP older than the
        # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
        # See http://serverfault.com/q/627903/94922 for details.
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_intercept_errors on;
        # PHP 5 socket location.
        #fastcgi_pass unix:/var/run/php5-fpm.sock;
        # PHP 7 socket location.
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal.
    location ~ ^/system/files/ { # For Drupal >= 7
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}


user warning messages keep popping up even after uninstall I have recently disables, uninstalled and removed a few modules from my drupal 7 site but this error keeps popping up no matter what I do, I have researched how to remove them but to my dismay nothing, please help.

User warning: The following module is missing from the file system: admin. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /opt/lampp/htdocs/drupal/includes/bootstrap.inc).

Most probably the disabling and uninstalling process of the modules didn't went smoothly. According to this help page on Drupal.org:

  Restore the module and actually disable and uninstall it (recommended if possible): First, restore the module to its original location in the file system. Then either go to the Modules page and disable/uninstall it from there, or use Drush (drush dis module_name && drush pm-uninstall module_name, where module_name should be replaced with the name of the module).

Don't forget to also clear the caches, that "magic" feature also resolves a lot of problems ;)

You could also disable the specific message by using the Disable Messages module. However, I would recommend to try cleaning up your Drupal configuration that are causing the messages.


How to add a column to DB with weight by using hook_update_N? I want to add a column to a database by using hook_update_N(), but it should be 3rd column instead of last column. How I can achieve that please help in this regard. I tried to add weight but not working. below is my code which is creating a column at the last in the existed table.

function test_update_7001() {
  $column3 = array(
    'type' => 'varchar',
    'length' => 256,
    'not null' => FALSE,
    'weight' => 3,
  );
  db_add_field('test_table', 'column3', $column3);
}

db_add_field doesn't support AFTER, which you would need to create your desired query.

You'll need to build an appropriate SQL string and run it through db_query() instead.


What was the motivation for developing the plugin API? I am trying to wrap around my head as to what was the need for the Plugin API when the module system extends the Drupal core.

It is not modules vs. plugins. Plugins are competing against hooks, which they will eventually replace entirely, together with event subscribers and services. By the way, all are implemented by modules because you are not allowed to insert them in core directly.


How to use/show different path alias of same URL according to user roles? Hi I have set URL alias of for node add from path like below :

  node/add/my_content_type =  addlink
  node/add/my_content_type  = suggestion

When user is logged-in we make access of node add form via this URL:

  www.example.com/addlink

Now for not logged-in user we want users to use node add from via below URL:

  www.example.com/suggestion

I am trying with rules on event "Initialize drupal" then checking path and roles and trying to redirect but not able to achieve that.

Please suggest is that possible to make it happen in some way!

Thanks!

The ensure the right path is used when displaying links, you need to implement hook_url_outbound_alter() in a custom module.

/**
 * Implement hook_url_outbound_alter().
 */
function MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if ($path == 'node/add/my_content_type') {
    $path = user_is_logged_in() ? 'addlink' : 'suggestion';
  }
}

Ensuring the right path is always used can be achieved with a hook_menu_alter(). There, you can alter the page callback for node/add/my_content_type. And in your callback, check whether the user is accessing the page using the expected path.

/**
 * Implements hook_menu_alter().
 */
function MODULE_hook_menu_alter(&$items) {
   $type_url_str = str_replace('_', '-', 'my_content_type');
   $items[['node/add/' . $type_url_str]['page callback'] = 'MODULE_my_content_type_add';
}

/**
 * Page callback for the add new My Content node page.
 *
 * @see MODULE_hook_menu_alter
 */
function MODULE_my_content_type_add($type) {
  $expected_path = user_is_logged_in() ? 'addlink' : 'suggestion';
  if (current_path() != $expected_path) {
    drupal_goto($expected_path);
  }
  else {
    return node_add($type);
  }
}

If you site use multiple language with prefix language selector, then current_path() will also contains the language prefix whch need to be accounted for in your code.


Error while set a paragraph field to NULL during cron run I am using Drupal 8 and I have implemented a hook_cron to set a node field to NULL. Here is my code:

if ($lesson->field_lesson_ended_at->value < $current_time && $session_id && count($paragraphs) > 0) {
  $pids = [];
  foreach ($paragraphs as $paragraph) {
    $pids[] = $paragraph['target_id'];
  }
  $storage_handler = \Drupal::entityTypeManager()->getStorage('paragraph');
  $entities = $storage_handler->loadByProperties(['id' => $pids]);

  foreach ($entities as $entity) {
    try {
      $apiObj->forceDisconnect($session_id, $entity->get('field_session_connection_id')->value);
    } catch (Exception $e) {

    }
  }
  $storage_handler->delete($entities);
  $lesson->set("field_session_id", NULL);
  $lesson->save();
}

When cron task reaches these lines:

$lesson->set("field_session_id", NULL);
$lesson->save();

Throws the following error (capture from cron logs):

Error: Call to a member function getTranslation() on null in Drupal\Core\Entity\ContentEntityBase->hasTranslationChanges() (line 1430 of core\lib\DRupal\Core\Entity\ContentEntityBase.php)

Any ideas on how to solve this issue?

Even if the cron job is working now after you changed the order, you might get the same error later when using the saved parent entity.

Don't delete referenced paragraph entities programmatically (now the last command after you've changed the order). The Entity Reference Revisions module is handling this automatically after all revisions referencing the paragraph are removed.


I want to allow users to click "share this" on a page with an image, and then email that image as an attachment I have a site that shows floor plans for houses. I want to allow users to share a floor plan via an email form where they can enter their email address and their friend's email address who they want to share with. Then when they enter their message and submit, the image of the floor plan will be attached to the outbound email from the server.

If you are willing to write your own module, check out the mimemail module. Sending the mail is as easy as this:

mimemail($sender, $recipient, $subject, $body, $plaintext = NULL, $headers = array(), $text = NULL, $attachments = array(), $mailkey = '')

If you store the picture in a imagefield or filefield inside a node, you can put that field into the attachments array and send it.


How to set a conditional webform to copy the value of a field to another? I'm trying to design a webform in Drupal 7. We have a separate entries for a "student postal address" and "guardian postal address". A request appeared to have a "use same address" check box.

Is there a way to attempt this without custom coding? Optimaly, I'd love to select the value of another field using the Webform Conditional UI shown below.

webform sameas

  this module makes a "Same As" component available for use on your
  webforms. This component allows you to add a "Same as" checkbox to a
  form allowing you to indicates that one set of fields should have the
  same value as another set of fields. For example, if you had fields
  for both a Billing and Shipping address on your webform, you could add
  the Same As component to allow users to only fill out their billing
  address if their shipping address is the same.


How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/* I have been searching for the answers to this question with no luck at all.
From what I observe in the database structure, the location to the modules are specified in the 'system' table.
The only solution I have is to write an SQL query to update the 'filename' column.

Is there a better/cleaner solution in solving this, for eg., a contrib module?

You only need to move your modules to the your new location and rebuild the regisry. When the registry rebuilds the path to the modules will be updated. Check registry_rebuild().

  Rescans all code in modules or includes directories, storing the location of each interface or class in the database.

Although, I would recommend you to backup you database before testing this.

If you are using drush you could also rebuild the registry using the following command:

drush cc registry

You can also install the registry_rebuild command for drush:

// install registry_rebuild
drush dl registry_rebuild
// rebuild the registry
drush rr


Time limit items in your cart Product in your cart active only 20 minutes, then is removed

how to do?

I think Commerce Cart Expiration (https://www.drupal.org/project/commerce_cart_expiration) will do what you want. But I've only used to expire carts that are older...48 hours, for example. That works fine with cron, but for shorter periods, you'll need something else.

From the readme:

The module also provides a block which displays the time remaining. Its content gets refreshed by javascript just like a countdown. To show up the block, add the 'Cart expiration' block to your preferred region under admin/structure/block.
You can configure this blocks content on the block configuration page. Use the token [commerce-order:expiration-formatted] to get a format that can be manipulated by javascript.


Custom display suite field In a custom module I have defined a display suite field like so:

namespace Drupal\custom_dsfields\Plugin\DsField;
use Drupal\ds\Plugin\DsField\DsFieldBase;
//Views
/**
 * Plugin that renders the field.
 *
 * @DsField(
 *   id = "total_hours",
 *   title = @Translation("Total hours"),
 *   entity_type = "node",
 *   provider = "custom_dsfields",
 *
 * )
 */
class MyField extends DsFieldBase
{
    /**
    * {@inheritdoc}
    */
    public function build(){

        $node = \Drupal::routeMatch()->getParameter('node');
        $entities = [];
        $hours = [];
        foreach ($node->field_hours as $key => $value) {
            array_push($entities, $value->target_id);
        }
        $entities = entity_load_multiple('user_entities', $entities, $reset = FALSE);
        foreach ($entities as $key => $value) {
            array_push($hours, $value->field_hours->value);
        }
        $hours_sum = array_sum($hours);

        return array(
            '#markup' => 'Total hours for this day ' . $hours_sum . ''
            // '#theme' => 'item_list',
            // '#items' => $hours_sum
            );
        }
    }

In the default display this works perfect. (open to improvements
But when I use a view, and display the teaser display with this field in it then the field is not working. Why is this?

Some things I am questioning...

Am I loading the node in the correct way as I am not entirely sure what routeMatch() is doing.
Should I be doing this in a view template (hope not)

Thanks DSE!

I found a better way to access the node so this will work anywhere.

$this->entity();

Inside the current class it will load the entity, in this case, the node.

Happy drupaling!


Linking taxonomy terms that appear in content Is there a way to find and link to taxonomy terms that appear within content?

You mean automatically? You probably want something like the glossary module

  The glossary module scans posts for glossary terms (including
  synonyms). The glossary indicator is inserted after every found term,
  or the term itself is turned into an indicator depending on the site
  settings. ... The glossary uses Drupal's built in taxonomy feature, so
  you can organize your terms in a Drupal vocabulary.


Node gallery: display image count in a template file I use the Node Gallery API  module (part of the node_gallery project) to create galleries of nodes. Now I need to theme node--gallery.tpl.php to display the count of images in a gallery.

I tried to use the Node Gallery API function called node_gallery_api_get_item_count, but it doesn't work. So I tried to look at the database and indeed the node_gallery_galleries table contains zero values on the item_count and pub_item_count columns (even if I call the function with reset=TRUE).

So how to calculate the value directly from the database?

One answer:

<?php
  $results = db_select('field_data_node_gallery_ref_1')
  ->fields(NULL, array('entity_id'))
  ->condition('node_gallery_ref_1_target_id', $node->nid)
  ->execute()->fetchAll();

  $pcount = count($results);
?>

Explanation:

The field_data_node_gallery_ref_1 table contains one row for each picture in the gallery. I filter it by the nid of the gallery (node_gallery_ref_1_target_id) in order to get only pictures in that gallery, then count how many pictures exist on the gallery by counting the results of the query array.


How do I declare a Telephone field in a content entity? I want to create a custom content entity with a telephone field. I'm baffled on how to do it; I can't figure out what should go into setDisplayOptions() to have it show up as a telephone field on the form. Does anyone know where I could find an example of this?

Okay, the following configuration seemed to work:

$fields['display_number'] = BaseFieldDefinition::create('telephone')
      ->setLabel(t('Display Number'))
      ->setDescription((t('The phone number to display')))
      ->setDefaultValue('')
      ->setDisplayOptions('form', array(
        'type' => 'telephone_default',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);


Reusable images question I want to have reusable images in my new Drupal 8 blog.

I followed this guide that uses the Media Entity and Media Entity Image   modules, but I have a problem every time I want to use an existing image. I get the following error.

  The referenced entity (media: 206) does not exist.

So far, I used the default field_image field in the articles, but now I want to use the new field_reusable_image that uses existing images.

Will the already uploaded images in field_image be available to be added in field_reusable_image?

The problem was that I created a field in media bundles that didn't match with the one in the content type.
The guide that I followed was not so clear so in the media bundle I created a field_image and I was trying to reference it with content.field_reusable_image in content type, which apparently didn't work.


Find out who updated Drupal modules Someone updated modules in my Drupal install 5 days ago, and I would like to find out who.

I looked in Reports > Recent log messages, but this is filled up with so many php warnings that it only goes back 1 day.

I also tried searching for "update" in the watchdog table, but couldn't find any entries for the date I was interested in.

I think you'll find details in the Watchdog if the updates were performed using the UI.

If the modules were updated using a different method, e.g. Drush or manually, then you'll need to turn to your server logs, assuming that you keep logs for such actions. Drupal won't hold any data about those actions, as it wouldn't even necessarily know they had occurred.

Just to clear things up, the "Recent log messages" report gets its data from the watchdog table, so you're looking in the same place for both.


How to create a drop down field to categorize content when creating new pages? I want to have a drop down field available so that when a content author (user) creates a new page, they can select which section of the website this new content should get placed.

For example, my top navigation may be About Us > Services > Products. A user creates a new page that should go on in the Products section. When they go to add the new page, there should be a drop down field that shows About Us, Services, Products. The user would select Products and when they save the page, that page will automatically get placed in the Products section of the website.

Can anyone tell me how to achieve this?

The drop-down can be created as a Taxonomy.

The section pages can all be one View with a Contextual Filter for each taxonomy term.


Drupal 7: hook_menu not working correctly I've created a custom module (called page_arg) simply for the purpose of registering a path and having it use a certain template file. I had this working with Drupal 6, but can't get it to work in Drupal 7. Basically, if I leave the page_arg_callback() function in the module, I get a 500 Server Error on every page in the site. If I remove it, I'm able to visit the path I'm trying to register, but it isn't using the template file I want it to use.

function page_arg_menu() {
  $items = array();

  $items['flashcards'] = array(
    'title' => 'Flashcards',
    'page callback' => 'page_arg_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function page_arg_preprocess_page(&$vars) {
    $url = urlSplit(); //custom function. trust me, this isn't the problem :)
    if($url[0] == 'flashcards'){
        $vars['template_files'][] = 'flashcards';
    }
}

function page_arg_callback($arg){
  return 'howdy';
}

As a secondary question, is this the best way to go about simply registering a path and pointing it to a template file? Seems a bit elaborate. Could I implement hook_menu() in my theme instead?

Try this:

function page_arg_menu() {
  $items = array();

  $items['flashcards'] = array(
    'title' => 'Flashcards',
    'page callback' => 'page_arg_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function page_arg_callback() {
  // Do stuff
  return theme('page_arg');
}

function page_arg_theme($existing, $type, $theme, $path) {
  return array(
    'page_arg' => array(
      'template' => 'page-arg',
      'path' => drupal_get_path('module', 'page_arg') . '/theme/templates',
    ),
  );
}

Create a file page-arg.tpl.php and put it in /theme/templates in your module (page_arg) directory.


how to render a field "view mode" inside a field collection item template file? to render a field "view mode" (or "format") inside a node.tpl.php i use, for example:

<?php
     print render(field_view_field('node', $node, 'field_myfieldname', array(
        'label'=>'hidden',
        'type' => 'text_summary_or_trimmed',
        'settings'=>array('trim_length' => 30),
    )));
?>

now i'd like to do quite the same thing, but inside a field-collection-item.tpl.php (for a field that is part of a field collection).

in my field-collection-item.tpl.php, i can render each field just like in a node;tpl.php:

<?php print render($content['field_myfieldname']); ?>

but if i try the first code above inside field-collection-item.tpl.php (to trim a field-collection field), it just doesn't work...

thanks you for helping !

I haven't tested this but I suspect your issue arises from the fact that the $node object is not available to that template file. You have a couple of options; write your own theme function, load the node object some other way (this might still not work though because of the way field collection works) or just trim the rendered value.

Something like this should work for you if you are just looking to trim the result to 30 characters:

<?php print trim(substr(render($content['field_myfieldname']), 0, 30)); ?>


Taxonomy menu with a large list of terms I want to display a list of terms and child terms using Taxonomy menu,my list is very large ( more than 2000 terms), and Im getting this error:

Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = &#039;theme&#039; OR (type = &#039;module&#039; AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of C:\wamp\www\Books\includes\module.inc).
Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] =&gt; theme_registry:runtime:adaptivetheme_admin:cache ) in lock_may_be_available() (line 167 of C:\wamp\www\Books\includes\lock.inc).
Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 206 of C:\wamp\www\Books\includes\session.inc).
Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] =&gt; 14337154844f4e188d884c54.86419408 ) in lock_release_all() (line 269 of C:\wamp\www\Books\includes\lock.inc).

Is this because Taxonomy menu can not handle a large amount of terms?

Yes, this error usually is related to a large size of data, so database can't handle such sizes due the given limits and it fails, because the server timed out and closed the connection.

To fix it, you need to increase value of max_allowed_packet in your my.cnf (e.g. ~/.my.cnf) under [mysqld] section, e.g.

[mysqld]
max_allowed_packet=256M

See: B.5.2.9 MySQL server has gone away for more detailed information.

Another thing is that in this particular case it happens in shutdown function (which is after Drupal finished the processing of the site), therefore it could be related to some cron or debugging tasks.


Where are profile2 fields shown? I have installed the profile2 module and added some fields, but I can't find where are they shown. How do I display fields' values for a user?

I also can't change fields' values after creating a user.Fields are shown only in user registration page.

Assuming you're using the default admin theme you should see a tab on each user edit page for each profile type in the top right hand corner, e.g.

You should also see a tab on the user page itself for each profile type, the fields are displayed in there.


How to set a default theme programmatically I am trying to build an install profile and I want to have my custom theme enabled and set by default after the installation.

Adding in MYPROFILE.info.yml...

theme:
  - my_theme

...is not enough. This only installs it, but it is not set as the default theme.

I guess I have to do something else in the MYPROFILE.install file in

function MYPROFILE_install() {
  // how to set as default my custom theme
}

Thank you

Looking at ThemeController::setDefaultTheme (the request handler for the /admin/appearance/default route), this should do the trick:

\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', 'machine_name')
  ->save();


User information based on external database In one of the community portal based on Drupal,

Now, there is a rich user information which is also used by external applications. This information can be LDAP, MySQL or any other different database per say. (the choice here is still open).

Now, we are also considering using Profile2 for rich user information, for authentication as well as and also for various social features.

So essentially, there are two different Applications (Drupal and External) that need to access the same data and both might need to read/modify the information. (we can be safe here in terms of simultaneous access because traffic will be very minimal.)

So what should be the right approach ? Should Drupal look up to the external database or should the external application directly modify Drupal's own database? Or should there be some sort of DB to DB sync?

Is any of the approach possible and if so, how can this be achieved?

Please note: this approach requirement is only for User specific information not any general purpose other content in Drupal.

Personally, I would fetch and update the fields on Drupal when the user logins, and update the remote database when the user in Drupal is updated. If you user Profile2 you might have to use other hooks.

An other option may be running a script outside Drupal to synchronize the two databases.


Why drush "assume yes" -y option do not work for some commands Drush has global option -y (or --yes) which allow you not to type y on every promt during given command execution. (There is also -n or --no option to which following applies as well.)

This works perfectly when you run something like:

drush en i18n -y

The propblem arises, for example, when you trying to run rsync in that manner:

drush rsync @staging:sites/all/themes @production:sites/all/themes -y

Drush just don't get the -y option, and prompts you for a confirmation.

What is this and how to make use of -y option?

The solution is to pass all global options like -y or -n before drush command:

drush -y rsync @staging:sites/all/themes @production:sites/all/themes

This allows you to pass options to a shell command run with drush without getting in conflict with drush options:

drush [global options] command [command options]

This will pass [global options] to drush, and [command options] to a shell command.

Take a habit of passing -y and other global options right after you type drush.

Run drush topic docs-strict-options to get a help on that case.


Show certain content to roles based on taxonomy terms I am trying to personalize the viewing experience for users on a site.  I'm trying to figure out how to create a view that will show content tagged with taxonomy term 'a_term' to users with the role 'a_role'.  I want to tag all of my content with these different tags so that users with 'b_role' will see content tagged with 'b_term', 'c_role' -> 'c_term', etc...

Note: these are example names for roles/terms - there will be no naming convention like this.

Have you taken a look at Taxonomy Access? It allows you to set access control for roles based on taxonomy terms.

EDIT: Ignore the above dumb reply and feel free to downvote.

I think you could do this by creating a custom contextual filter in Views. Your contextual filter would look at the current user and decide which taxonomy terms ids to return.

If you are using Drupal 7 you could tag the users themselves with the same terms as a way to store which terms are associated with which users. Otherwise you might need to create a separate table to store the user to taxonomy association.


How do I troubleshoot specific Products missing from Commerce Search? Using Commerce Kickstart 2

Having a situation where certain Products simply do not appear in the Search results. Is there a way to troubleshoot specifically -why- certain products (or other content) are not appearing in the search index?

I looked through the search_api_db_product_display table and sure enough, the missing node is -not- there.

So: Is there a log or table which displays each node and index term and/or -why- a particular node was included/excluded?

Just to be clear: If I enter the URL for the Product directly, it displays fine.

ALSO: I can search from admin/commerce/products and the Product shows up as well as from admin/content.

Perhaps related: There seems to be a known issue where adding new products does not automatically update the index. But I have cleared the index and rebuilt several times and it makes no difference.

Not sure if this is proper 'etiquette' but here is the solution for -this- problem:

My Product Display has an Entity field which displays a list of 'related products' -- a common enough situation in a Shopping Cart system. The related products are a View which displays products linked to the parent product NID.

Like most sites, I imagine, the Index excludes unpublished products.

Apparently if any one of the Related Products is unPublished, this affects the Commerce and/or SOLR Search index for the -Parent- product. IOW: if any child product is unPublished the index skips the -parent- product as being 'unpublished'.

Not sure which module is at the root of this... or who to notify... but if the Commerce Guys monitor, this is a real 'gotcha'. I've run into this many times in Drupal where SQL Queries are not 'isolated' from one another... ie. a child view will affect a parent query.


A module for generating PDFs I have tried PDF using mPDF and Printer-friendly pages (Drupal 7.x). They both need own styling of an output. I have got a CSS that formats my pages for printing. I would like to generate PDFs by just "printing" to them. I do not want to maintain separate styles.

Is there a module that generate a PDF file with an output that would be sent to a printer?

Try Printer, email and PDF versions module.

  This module allows you to generate the following printer-friendly
  versions of any node:

  Printer-friendly version (webpage format) (at
  www.example.com/print/nid)

  PDF version (at www.example.com/printpdf/nid)

  Send by email (at www.example.com/printmail/nid)

  where nid is the node id of content to render.


drupal facebook autopost working but post are not visible to public I am using Facebook Autopost module and rules module to automatically post content to my facebook page when a new content in created. The post are appearing in my facebook page but they are not visible to public. What am I doing wrong.

You need to take your app out of development mode and make it live to the public. All of your previous posts will then appear to their appropriate audiences (and so will future posts).

You can do this by going to https://developers.facebook.com, going to your app's dashboard, then to App Review. At the top there is a Yes/No field for "Make app public?" Set it to yes.


How to add a background image wallpaper to a drupal site from within the drupal admin? How can I add a background image wallpaper to a drupal site from within the drupal admin i.e. not editing themes or PHP?

I'm not adverse to PHP or themes but adding a background image wallpaper is a generic non-theme specific feature so should require editing a specific theme.

This has to be one of the simplest/fundamental/popular things one wants to do with their site. It ought to be obvious in Drupal -and- possible within the Drupal admin, not via editing themes / PHP code.

Is there a way to do it?

I found some promising modules (actively depveloped for Drupal 7) but am a little unsure how to use them:

http://drupal.org/project/bg_image (Instructions say: "provide a css selector and color and repeat attributes in the 'Default CSS Settings' section." - but how do I know what CSS selector to use? Yes I know CSS but in the context of Drupal, is there more than one I need to consider and why? Perhaps an example would help here)
http://drupal.org/project/dynamic_background (This has more advanced settings for specific entities in drupal: User, Blog, Panels, Node, Views (beta), Context) - OK fine. BUT WHICH one do I use to simply put up a background image for the pages of my Drupal site?!

For simple Drupal themes we use Artisteer. You can change most properties of a theme with just a mouse click. Please note that the tool is not free (and I'm just a happy user).


How to compare two fields for filter criteria in view I want to compare this field value with another field value

How can I do that?

Thank you very much!

With latest views in 7 you have under global filters, "field comparison" filter that you can select any 2 fields which you added into fields of that view (they can be hidden fields) and that is it. Image below shows how this looks:


My first custom module I found some code on the Drupal forum that solves a problem I have. Several users report the code works for them so I suppose I did not exactly get how to create a custom module. I followed the following steps:

Create a folder called i18nblocktran in sites/all/module and added two files:

i18nblocktran.info

; $Id$

name = Wysiwyg taxonomy translation
description = Displays the wysiwyg editor in the taxonomy term translation interface
package = Nathan
core = 7.x
files[] = i18nblocktran.module

and i18nblocktran.module

<?php
function i18nblocktran_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'i18n_string_translate_page_form'){
    foreach($form['strings'] as $name => $field){
      if(preg_match('/blocks:block:[0-9]+:body/i',$name)){
        // Change textarea to text_format
        $form['strings'][$name]['#type'] = 'text_format';
        $form['strings'][$name]['#description'] = '<br/>';
      }
    }
    $form['#submit'] = array_merge(array('i18nblocktran_string_translate_page_form_submit'), $form['#submit']);
  }
}

function i18nblocktran_string_translate_page_form_submit($form, &$form_state) {
  // Remove wysiwyg format because i18n cant handle it
  foreach($form_state['values']['strings'] AS $name => $field) {
    if(preg_match('/blocks:block:[0-9]+:body/i',$name)){
      unset($form_state['values']['strings'][$name]['format']);
    }
  }
}
?>

Then I activated the module in the admin but nothing happened. What did I miss ?

Change line 4 in your .module file

foreach($form['strings'] as $name => $field){

with this

foreach($form['strings']['all'] as $name => $field){

It should do the job


Remove Filter When Exposed Filter is Selected Currently, I'm working on an events view in Drupal 8 which needs to only show events that are on or after the current date (now() filter). This view also has an exposed date range filter that allows user's to select a start date and end date. The start date can be from before the current date.

The problem is that the now() filter isn't letting user's see anything before the current date. How can I remove the now() filter when a user enters a start date so they see the list of all the events in the date range they've selected?

You can do this by combining two "Authored on" Filters, one regular and the other one Exposed with the OR Operator working between them/groups of Filters.

Add the regular "Authored on" Filter Is less than or equal to now.

Add another "Authored on" Filter and Expose it with your preferred settings, how you want your visitors to use it, don't enter a default value.

Then under Add dropdown choose And/Or Rearrange, Create a new filter group. move the Exposed "Authored on" to it, and choose the OR between the groups, while keeping AND within groups.

Recreate any Filters you might need in the second group.

That's it!

Be very careful of your entire Filters configuration. If you have Exposed filters in the first group too, they will not be able to be applied at the same time (because OR), which may be confusing to users...


How to Query MySQL Database Module Could you help help me correct the follow piece of code

I am getting the following error.

"The website encountered an unexpected error. Please try again later."

public function __construct(Connection $connection) {
    $this->connection = Database::getConnection();
  }
public function hello($state = '0') {
    $sqlQuery = $connection->select('pop11', 'C2011')
    ->fields('C2011', array('male', 'female'))
    ->condition('C2011.sCode', '10', '=');
    $data = $sqlQuery->execute();
    if ($data) {
        $results = $data->fetchAll(\PDO::FETCH_OBJ);
        foreach ($results as $row) {
        echo "Field a: {$row->male}, field b: {$row->female}";
        }
    }else{
        return array('#title' => 'Error', '#markup' => 'Could not Find. What you are Looking for.',);
    }

}

$connection doesn't exist in the context of hello(). You need to use $this->connection if you're wanting to use the Connection that's built in your object.


how to implement facet search api on content types feilds? Is it necessary to build taxonomy for each field of content type to show it in search option in sidebar in facet search api ?

Just follow the steps here and you will be done. https://beautiful7mind.wordpress.com/2013/03/10/step-by-step-how-to-implement-facet-search-on-data-in-drupal-7/


Why are two database tables (node and node_field_data) used for node data? I would like to understand the database architecture of Drupal 8. I noticed that Drupal 8 has two separate tables (node and node_field_data) which include almost the same columns. Can anyone give some clarification on this?

To add additional information to @jaypan's answer following are my observations

node_field_data contains 6 fields

nid     int(10) unsigned
vid     int(10) unsigned
type    varchar(32) The ID of the target entity.
status  tinyint(4)
title   varchar(255)
uid     int(10) unsigned    The ID of the target entity.
revision_translation_affected   tinyint(4)NULL

the nid is primary key in this table and referred by node and other fields as target id.
The type attribute tells what kind of content it is referring to, like posts, article or custom. In case of custom, it will store the name of the content type.


How to use autocomplete text field in fieldset? I want to use a textbox with autocomplete features. I have gone through the drupal form API and found the solution at here.

It's working fine if I am using this directoly in the form fields. But it's not working if I am using this any Field collections item in profile2 fields.

I am using profile2 fields with fieldscollection and following is my code.

/*profile_2_type is id for profile 2 module and it's not working for me*/
$form['profile_2_type']['field_test_auto_cmplete']['#autocomplete_path'] = 'user/autocomplete';

/*Here is the code which is working for me for node fields */
$form['title']['#autocomplete_path'] = 'user/autocomplete';

finally got the solution
here is updated code

$form['profile_2_type']['field_test_auto_cmplete']['und'][0]['value']['#autocomplete_path'] = 'user/autocomplete';

and "user/autocomplete" only works for admin users


Shared Drupal 7 core and shared contrib libraries & modules I have a server and I run around 20 Drupal 7 websites. As I start to get more clients It's becoming increasingly more time consuming doing Drupal core and modules updates.

Is there any way to have a shared Drupal 7 core, libraries and modules (just the main ones that I use as standard like views, context, backup, libraries etc) so I can updated those once and it updates for ALL of my websites. Any site specific modules I would still like to keep seperate.

I'm running a linux server with WHM and cpanel for each account if that helps at all. I also have shell access to my sevrer.

note: that each website is running as a different account on the server so each is an individual vhost.

Any advice on how to manage this would be greatly appreciated

You can symlink the same core into several drupal installs. This works cross vhost.
You can also run several sites on the same Drupal Core in a multi-site fashion. This however requires you to keep a single vhost, so you need to restructure the server config for this.

Note that I recommend against clustering to many sites. If you break a single core, you break all of them. So you would do well to run, say 5, sites per core. Obviously the number should be adjusted depending on how much resources they require and how many sites you run in total.


Tree like structure in views I have a content type in which I have following fields

Title, year, and report type. I create a block using BEF for exposed report type. which is working fine

Now I want to show results as

- 2014
    --Title1
    -- Title2
+ 2013
     --Title 2013
     --- Title 2013 1

and so on

When i click on + icon result will expand.

Can we do this using views or I have to right custom code for this?

Maybe you should look at the Views tree module, to see how well it would fit your needs. Here is a quote about the module (from its project page):

... provides a tree-based style plugin for Views.
It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.


Is there a module for repeated content? I recently faced a need of reusing some content, creating content templates (not in the usual meaning of the word).

I have content that is created periodically, a product for instance, which differs from another by one or two fields, all of the rest stays the same, so I thought of reusing content.
Have you ever seen a module that would accomplish that?

If you are talking about the actual content then check out the replicate and the replicate ui modules. They allow you to duplicate any entity. Much more powerful than the node clone module which only supports nodes.

If you are talking about cloning the content type or product type then look at the bundle copy module.


How to translate countries in multilingual site? I have used country_get_list() function to render all pre-installed countries in my select list.

When my site is in English, it is showing all country names in English, which is fine. But for French site, I want all country names should get translated in french.

For example: in English a country name is India but in the French site, it should display like Inde.

Is this possible to achieve?

Make sure you have the translated country strings in your database, ready to be used.
country_get_list() calls _country_get_predefined_list(), and inside this function country names are passed through t(). So, if you have country strings translated in your database, translation should work.


Entity reference field on select show some data about entity consider i have a customer content type with fields (name, phone, address) and i have a feed back content type with an entity referenced field to customer.

When  the user select the customer i want to show the phone and address somewhere near the field.

Is there a module for this? Or how do i do this?

There is an option to use views for populating the dropdown in the entity reference fields. Since you are building the options using views, you can pretty much customize it as you want.

Check out this video http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7 for more details.

----------------THIS PART ADD BY QUESTIONER-----------------

Thanks to Gokul N K.

This tutorial made what i want in the view mode. What to do in the edit mode?

Create a custom module
Hook form_alter
Add a HTML div just below the autocomplete field
Inject some JavaScript and bind the auctomcompleteSelect trigger on your specified field.
In the bind function add an ajax callback to acquire your desired information and display it inside the div.


How to set the link in a view slideshow? Currently,  I'm creating a xyz resort website. In my home page, I implemented a slideshow by using views. I want the slideshow to be clickable: When I click on to the resort image in slideshow it should go the respective resort description page.

Can anyone guide me on how to set the link in the view slideshow?

You just need to make a little change in the slideshow view: Just link the image field to the content and save. Go to Configure Field > Link Image to > Select Content.


How to resize an uploaded image based on the longest side? I can't seem to figure out how get ImageCache to resize an image based on the longest side.

Desired behaviour:

upload image 800x532 --> resize image to 400x266 (landscape)
upload image 532x800 --> resize image to 266x400 (portrait)

Is this possible with ImageCache? If not, how can I achieve this? Aspect ratio must be preserved.

To follow up on this question; ImageCache Actions now offers a feature called Aspect Switcher which allows for different image styles based on the original images aspect ratio, if it's portrait or landscape.


Scald get usage for an atom In Drupal 7 with the Scald, is it possible to get the usage for a given atom, for example the nodes which are referencing it?

There is a module for that https://www.drupal.org/sandbox/pascalt/2128697. It also has Views integration.


Migrate failure: on clause is ambiguous I'm working with the migrate module for the first time and I've worked with the db_select api a little bit, but I'm running into an error.

I'm trying to convert some old labels into a drupal taxonomy. When I browse to the /admin/content/migrate page, it does my query correctly and shows the right number of rows that should be migrated. However, when I actually try to run the import, I get this error:

  Migration failed with source plugin exception: SQLSTATE[23000]:
  Integrity constraint violation: 1052 Column 'labelId' in on clause is
  ambiguous

Here is the code I have in my LabelMigration class:

$this->map = new MigrateSQLMap($this->machineName,

    array(
        'labelId' => array('type' => 'int', 'not null' => TRUE)
    ),
    MigrateDestinationTerm::getKeySchema()
);
$query = db_select('migrate_account_label', 'l')
         ->fields('l', array('labelId', 'label'))
;

$query->leftJoin('migrate_asset_labels_membership', 'lm', 'l.labelId = lm.labelId');
$query->leftJoin('migrate_asset', 'a', 'lm.assetId = a.assetId');
$query->addExpression('count(*)', 'num');
$query->condition('a.type', 'B');
$query->groupBy('l.labelId');
$query->groupBy('l.label');

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

// Set up our destination - terms in the vocabulary
$this->destination = new MigrateDestinationTerm('article_labels');

$this->addFieldMapping('name', 'label');
$this->addFieldMapping('description')
    ->defaultValue('');

If I remove the leftJoin() calls then obviously the error about the on statement goes away, but I don't understand how labelId is ambiguous because I'm always referencing it with a table alias.

Any ideas where this error is coming from? Is it coming from the MigrateSQLMap at the top? If so, how can I reference that labelId with an alias to make it non-ambiguous? I tried making it l.labelId, but that didn't work.

Figured it out!

When defining the field in the MigrateSQLMap I can set a table alias for the field:

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'labelId' => array(
            'type' => 'int',
            'not null' => TRUE,
            'alias' => 'l', // it's the letter small case "L", not the digit 1
        )
    ),
    MigrateDestinationTerm::getKeySchema()
);

The 'alias' => 'l' makes the labelId become l.labelId in the queries.


How do I download a sandbox project? I want to develop the recommendation platform for job orders. In drupal there is the Prediction IO module but it is a sandbox project. How can I download it?

As reported in Installing sandbox projects, sandbox projects don't have download links, since versions are not enabled for them. You need to use git to download the code.

Assuming you mean the PredictionIO module, that doesn't still have code, at the moment; it is reported in its Version control tab.

  No code is available for PredictionIO. File an issue or contact a maintainer if you have questions.

If there were code, you could download it with the following command.

git clone --branch master http://git.drupal.org/sandbox/mrded/2116851.git predictionio

In the predictionio directory, you would find the module code.

Update

On June 17, 2015, the maintainer answered to Code? saying:

  Hi guys,

  We actually stopped developing of this module.
  If you're interested, I can publish your codebase as full project and give you a maintainer permissions to fully control the module.

If nobody is going to offer to be maintainer of that sandbox project, the project will not have any code.


How do I hide nodes that shouldn't be directly accessed from users and search engines? I've found that there are times I have a node that simply contains content that will be displayed somewhere else, but shouldn't be viewed directly. That is, no one should ever go to node/1234, but the content in node 1234 should be displayed somewhere else. For example, I create an about page with tabbed content using views. So there are "About Me", "About Us" and "About Them" pages. All of these are displayed in a single page with tabs using Views. So I don't want people to get directly to the "About Us" node because then they wouldn't see the tabs for the other pages. At the same time, I don't want Google giving people a direct link to this node, I want to limit access so users can only get to it through the View (i.e., the tab).

So I need to restrict access to the node, remove it from the Drupal search results, and make sure Google doesn't pick up on it. Any suggestions?

The Rabbit Hole module provides this feature.

  Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


page tpl pattern for a page with contextual parameter I create a views with contextual filter and it's path is prodcuts/%, I know I can create a tpl for views but I need some more, I want to create a page tpl for this,( I want do another thing in that page  ),
what is pattern file name for this page?

I write down my answer because maybe this help another guys in future,I found out that there is not related to url parameters,and it work according to current path, then accroding the tpl file name pattern accroding to the pattern ( page--path.tpl.php) the answer is
page--products.tpl.php and work for any address  according this pattern products/% .


Separate all my content I have one page structure. This is my menu:

news 1

news 2

news 3

about 1

about 2

about 3

about 4

about 5

And this is content structure:

When I click a menu item goes to content in same page, but my site is slow. I think if I separate all tpl.php files maybe I'll improve my site performance. But I don't know how can I do it.

For example, click news-1 item go to news-1.tpl.php file.

Separating your tpl.php files in that manner won't improve your site's performance in the way that you hope, unless your current base node.tpl.php file is doing something really weird right now.

Loading more tpl.php files in a single page generally makes things slower not faster, as more hooks are invoked for preprocessing, etc...

Chances are, that if you have a 1-pager the tpl.php file being processed is not slowing your site down. It will be something in the database layer or excessing php processing, or incorrect caching setup.

If you still really want to do it, try Nikhil M's link to get the template naming suggestions.


The best way to synchronize old host and new host when migrating a Drupal site? I'm planing to migrate my live site from the current shared host to another shared host. I'm thinking to use Backup and Migrate module or importing/exporting mysql by phpmyadmin.

However I'm concerning about the new users who register on my site and their content profile node. Because on both old and new host users will be registered for some while (maybe 2 weeks?). And in this period there probably will be duplicated User ID and Node ID with different data on both hosts.

Is there any way to prevent this or synchronize both old and new site for some time?
Or is it safe to import eventually the data of discrepancy from the old one to the new one just changing uid and nid after name server propagation is completed?

I think you're on the right track. It is nearly impossible to implement a migration project and not plan for incremental updates. The migrate module supports that with its "update" function (as shown in the screen shot).

That said, there shouldn't be a problem of duplicate UIDs after the initial migration of data, unless you are letting people create accounts on both the legacy system and the new instance.


Which core module provides the default send email action for use in rules? There is a core module (might be related to core actions) that allows your to send an email via VBO. What is the name or where is that function located in core?

For e.g. When I am modifying the system mail settings, what "module" in core provides this functionality? (See screenshot)

There is no "module", at least not one that can be turned on and off like other modules. Emails are normally handled by drupal_mail() and a bunch of other functions found in the system.mail.inc file under /modules/system and mail.inc found in /includes .  These work together to create the framework, using templates that you can set up in order for other modules (like VBO) to actually send emails.

drupal_mail():

  Sending an e-mail works with defining an e-mail template (subject,
  text and possibly e-mail headers) and the replacement values to use in
  the appropriate places in the template. Processed e-mail templates are
  requested from hook_mail() from the module sending the e-mail. Any
  module can modify the composed e-mail message array using
  hook_mail_alter(). Finally drupal_mail_system()->mail() sends the
  e-mail, which can be reused if the exact same composed e-mail is to be
  sent to multiple recipients.


Content profile bug - cannot edit user profile page If the administrator user creates a profile node for a user, then that user cannot edit his own profile. How can I solve this problem? I have looked on the Content Profile module's issues, and found similar problems but no solutions for that.

In my case, that user created his profile node by himself, but I changed his username through phpmyadmin; now, his profile node results created by the admin user, not himself.

Problem solved! that profile node had php input format and that user whom i edited profile hadn't access for php input format filter.

The Content Profile module associates a node with a user.  If the administrative user adds a profile node, then it is authored by the administrator.  Therefore, the user that the profile node was created for will not have access to edit the node since they are not the author.  As an administrator, make sure to change the "Authored by" field to be the user whose profile the node belongs to, then the user will have the ability to edit it.


Problem creating path alias in code I am creating a node and a path alias roughly as follows:

<?php
$node = (object) array( 'type' => 'article');
node_object_prepare($node);
$node_wrapper = entity_metadata_wrapper('node', $node);
// ... some more fields get set here...
$node_wrapper->title->set( 'Foo' );
$node_wrapper->save();

// Set the path
$path = array(
  'source' => "node/$node->nid",
  'alias' => "foo/bar",
);
path_save($path);

The node is created OK, and the path seems to be created OK, too. I can type foo/bar in as the path and I see the new blank page. However when I edit that page, the Path Alias is blank?!

I have pathauto installed - could this be something to do with it? Nb. when I edit the page the "Generate path automatically" pathauto checkbox is not checked (which is what I'd expect).

Inspecting the differences in the node table, I noticed that the node created by my code had an empty language field. Updating this to "und" fixed the node alias.

This makes sense, because path_save() defaults to LANGUAGE_NONE (i.e. "und").

I had assumed that node_prepare would do likewise, but it does not.

So the solution is to set $node->language = LANGUAGE_NONE; at the point of creation.

Also, this is an easier way to create the alias...

$node->path = array('alias' => $path, 'pathauto' => FALSE);


How do I merge changes from a development copy of the site to the live site without losing new content? What is the best procedure for merging work done on a development copy of a site to the live production copy? Often times there has been a lot of new content added to the site since development started on the newest features. And most additions to a site will involve database changes. So copying any new files is easy, but what about the database? How do you merge your changes with the existing production database without losing new content that was added since the last time you updated the production site? Are there any modules that help with this?

For content types, views, and structure changes on the dev site look at using Features to export the database to code.

For content migration there are many options, but not a single solid solution. One example is the Deployment suite.


field widget is not saving selected value to database I am creating a widget under taxonomy_term_reference field and trying to use the same autocomplete used by taxonomy module, autocomplete is working fine but data is not getting saved.

    /**
     * Implements hook_field_widget_info().
     */
    function test_field_widget_info() {
      return array(
        'test_widget' => array(
          'label' => t('test Engine'),
          'field types' => array('taxonomy_term_reference'),
          'settings' => array(
            'size' => 60,
            'autocomplete_path' => 'taxonomy/autocomplete',
          ),
          'behaviors' => array(
            'multiple values' => FIELD_BEHAVIOR_CUSTOM,
          ),
        ),
      );
    }

    /**
     * Implements hook_field_widget_form().
     */
    function test_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      if ($instance['widget']['type'] == 'test_widget') {
        $form_field = array();
        $tags = array();
        foreach ($items as $item) {
          $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
        }
        $form_field['autocomplete'] = array(
          '#type' => 'textfield',
          '#title' => 'Tags',
          '#default_value' => taxonomy_implode_tags($tags),
          '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'], // Trying to use the same autocomplete path from taxonomy module.
          '#size' => $instance['widget']['settings']['size'],
          '#maxlength' => 1024,
          '#element_validate' => array('test_validate'),
          '#attributes' => array(
            'class' => array($element['#field_name']),
          ),
        );

        $form_field['search'] = array(
          '#type' => 'button',
          '#value' => t('Search Tags'),
          '#ajax' => array(
            'callback' => '_test_callback',
          ),
          '#attributes' => array(
            'reference_class' => $element['#field_name'],
          ),
          '#name' => $element['#field_name'],
        );
        $element += $form_field;
        return array('tid' => $element);
      }
    }
function test_validate($element, &$form_state, $form) {
  $value = array();
  if ($tags = $element['#value']) {
    // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);

    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }
  }
  $typed_terms = drupal_explode_tags($tags);
  foreach ($typed_terms as $typed_term) {
    // See if the term exists in the chosen vocabulary and return the tid;
    // otherwise, create a new 'autocreate' term for insert/update.
    if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
      $term = array_pop($possibilities);
    }
    else {
      $vocabulary = reset($vocabularies);
      $term = array(
        'tid' => 'autocreate',
        'vid' => $vocabulary->vid,
        'name' => $typed_term,
        'vocabulary_machine_name' => $vocabulary->machine_name,
      );
    }
    $value[] = (array)$term;
  }
  form_set_value($element, $value, $form_state);
}

Try adding the following line below form_set_value().

$element['#value'] = 'new_value';

P.S. Borrowed from Alter taxonomy autocomplete value


Is it possible to add unlimited values as a group of fields? Imagine I have a content type that asks you to list your friends.  The 2 fields are:

| first name |

| last name  |

Is there a way a user could add unlimited friends for both fields (i.e. first and last name) as a set?  Right now Drupal is not smart enough and only let's me add unlimited first names or unlimited last names.  In other words, they are not paired together.

If any of you have used Sharepoint, then you will know what I mean.  In Sharepoint you can easily hit the "add another" link and it would create a new set of first name and last name fields that stick together as a group.  You do not want to separate the first and last name fields.

For your use case, there is the Field Collection module. The description given in its project page is the following.

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

The latest stable release for Drupal 7 is 7.x-1.2, released on December 26, 2020; it's not covered by the security advisory policy. The development snapshot for that release has been last updated on March 26, 2021.
For Drupal 8, the project maintainers suggest using a different module.

Use Paragraphs and Entity Reference Revisions instead of field collection for Drupal 8 projects.

Since one of those modules doesn't have a release for Drupal 7, that suggestion isn't for users who are running Drupal 7 sites.


Send email to all users with specific role (updated privacy policy) We want to send an email to all users of a given role, to let them know about an updated privacy policy.

The filter by role allows to send different versions of the email to different roles.. not sure this is needed, but it will be useful to know.

Since this is a legal notice, it does not make sense to provide an unsubscribe link.

The email should be a somewhat decent looking HTML.
Perhaps we want to add some user-specific tokens, e.t. to link to the user profile.

So there needs to be some kind of authoring UI, e.g. by creating a node or something.

What I looked at so far

I installed mass_contact, but it seemed to add unnecessary complication with its categories.

In some other questions, people suggest to use rules. But in my understanding those are mostly meant for repeated email-sending, not for a one-off. Also I don't really know where I would find the authoring UI.

Simplenews might be another option. In my understanding, this is designed for consent-based newsletters.

Perhaps all these solutions can be used for the purpose I intend, but perhaps there is something more specialized for this specific task?

Mass contact is probably the way to go for you, if it has to be a solution integrated into the site. Categories are really easy to configure.

Automated and integrated solutions are always recommended over hacks, but if you're really doing this only once, the fastest way would be to export email addresses and use an email campaigning service or design and send manually in batches (sending bulk emails are limited per hour for spam reasons) from your site email address but that is difficult to test.

Setting up the HTML styling for your email is what you'll spend most of your time (through Mime mail module). If you plan on testing it on various email clients that is. Many services (Gmail for example) strip styling from emails, so you have to be careful what you style and how. Usually you use a tool that takes your email CSS and applies it all inline, because that is the most reliable way most of the styles will "survive" various email client filtering.

Simplenews is a very comprehensive solution, much much more to configure and understand there than Mass contact.

I can't see configuring Rules to be triggered would be easier than using Mass contact.

In the future you may consider using a module like Legal.


Give Role Permission to 1 Admin Configuration area? Is there a simple way to give access to 1 panel of options within Administration Configuration? I made a custom module with settings under /admin/config/mymodule and it shows up as a block with links in the admin config area.

But I cant see how to easily say Role X can access that -- without giving global access admin configuration in Permissions, which lets them see everything there :(.

My example hook_menu is:

function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );
  // Need at least one child item before your section will appear.
  $items['admin/config/eap-predeparture/list'] = array(
    'title' => 'Student Predeparture List',
    'description' => 'Upload, Revise or Rebuild the student perm list to administer access to the predeparture survey.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('predeparture_csv_admin_form'),
    'access arguments' => array('administer site configuration'),
    'weight' => 10,
  );
  $items['admin/config/eap-predeparture/incomplete'] = array(
    'title' => 'Not Yet Completed Orientation Report',
    'description' => 'These students have not completed the Predeparture survey based on those in the CSV file.',
    'page callback' => 'predeparture_incomplete_listing',
    'access arguments' => array('administer site configuration'),
    'weight' => 20,
  );
  return $items;
}

you can write your own "access callback" function returning TRUE just if the current user have the role you choose. Something like this:

function predeparture_menu() {
  $items = array();
  $items['admin/config/eap-predeparture'] = array(
    'title' => 'Manage Site',
    'description' => 'upload the valid predeparture csv file from this page.',
    'position' => 'left',
    'weight' => -100,
    'page callback' => 'system_admin_menu_block_page',
    'access callback' => 'my_access_callback',
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );

function my_access_callback() {
  global $user;
  return in_array('the role', $user->roles);
}


Do I need all drupal core history in my own repository I decided to update core via git, mostly by following the approach explained here.

I did this (in my local repo, dev branch):

git remote add core git://drupalcode.org/project/drupal.git
git fetch core
git merge 7.21
(resolved few conflicts)
git commit --amend
drush updatedb

I did this for the sake of making it easy to update core in the future, as proposed:

git fetch core
git merge [new commit hash]

Am I adding too much to my project by fetching all core history, or is this needed? I am interested only in updating core in my existing project.
If so, can I get rid of the core history?
Can I in next core update fetch only by tag?

Drupal.org suggests a similar approach.  But, I'm not sure I understand the need to keep core's history under your own repo either. Or any code you yourself didn't create or amend.

Why not just have your repo at /sites/?  And have your ignore file leave out anything you haven't touched, including unmodified modules from drupal.org (and all the stuff in /sites/default/files/). Then you're workflow could be to use drush to update core, modules and themes and use git for all your own code.  Use drush rsync for files when working between local, dev, stage and production.

Side note: I'm glad to see this question here because this is something I've been wondering myself and though I don't use the approach I've just suggested, I'm thinking about it.


media module - simple picture upload Currently if using media module and users can upload pictures, they are presented with modal window where they can select a file for upload. On the same page there is a dropdown for selecting folder (taxonomy) and on second page there are fields for adding alt aln title text. Which is quite complicated for uploading one picture.
Question:Is there any way of simplifying the process? Setting default upload directory for users and not to be asked to fill alt title fields?
Thank you.

You'll find the settings to skip field settings under

  admin/config/media/file-settings


Classify content in Views based on distinct values Is there any elegant way to classify content in view, so that content with same value of some field gets the same value from some predefined list?

For example: I have nodes with entity reference field and would like to get different colors (from pre-defined palette) for different entities referenced through this field.

I know, that this might be solved by using Views PHP field, but this seems to be quite "hacky" to me. Also, classification lists can't be defined in user-friendly way.

Also, it's possible to add another field to referenced entity, which allows us to use this value for classification through views relationship. But this seems to overkill - and even then I would need to use something like Computed field to get randomly generated colors, which are compatible with each other (or use computed field in combination with list field - but that seems to be completely insane).

Do you know about any better solution?

I haven't done this myself, but off the top of my head...

On the node type, I would add a CCK Colour Field to allow the person adding the node to determine a colour for that node. (Then in the content type setting, manage display and hide the colour field).

Then in views, you can add the colour field, and exclude from display.

Then in the same view, add the node reference field you wish to change the colour for (for example node title colour or background colour). (Make sure the colour field is first in the list of view fields)

Then in the view admin, click on advanced, and click "Theme Information". Find the field you wish to override (something like views-view-field--title.tpl.php).

Then copy the field.tpl.php file from the theme folder in the views module folder, and place it in your themes template folder, renaming the file views-view-field--title.tpl.php

You can then place your own php in that template file, around the default $output variable, something like...

$color = $row->{$field->color_field};

<div style="color:<?php print $color ?>;">
<?php print $output ?>
</div>

I think that's what you mean? Please let me know if I have misread the question.


Multisite Cache Clear I have a site with multisite settings

There is one main site, where all the news are created and those are gotten by the other sites via a direct db_query via a taxonomy tid. This is the part that I managed to work after all.

Now the problem.
When I create or update a news node on the main site, the others have to be somehow notified of this. But I don't know how I can clear the cache of a different site

Is there some module which can do this?
If not, do I have to delete from cache tables directly on hook_node_update(), hook_node_delete(), hook_node_insert() ?
If yes, which table(s) does drupal store the cached rendered output (or doesn't she?)?
…
I cannot use drush

One thing might help you(not sure)is that you can write your function in hook_cron and run that cron in background. So let's say your cron run after every 5 min, which means your page is refreshed and cache will get clear on every cron hit.


How can I implement a flag module with caches but won't affect cache the flagging nodes? According to a post here, I have installed flag module to implement product comparison. However I found that the CPU usage is very high 80-90%, then I tried to install boost and Views content cache to improve the performance. The result is good, CPU usage drop to around 10%, but when I flag(add) or unflag(remove) the node from the views, it not work.

Views Content Cache has a patch for flags support, although I don't know how well it will work with Boost.

Try using the Views Flag Refresh module, it's supposed to tell the view when to refresh, don't know if it will play nice with the other modules though.


Filtering Views to make several users see the node I have a content type which contains files. I have a node with that content type which i want several, but not all people to be able to see it from a Drupal View. I know the list of the people i want to see the files, and am willing to input the names of users into any type of field of that node.

How do i filter a View to only show that node to that certain people listed in that field of users?

For context, the nodes contain some private documentation or architect design files, that not everyone should see, but also should be seen by several people, not only administrator and owner of the node.

It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.

use the Views module to create the list – actually a list of users (rather than nodes/content).
use relationships settings to add in the interests, and finally
add a contextual filter on "user: uid" with a default value fetched from the currently logged-in user.


Is there a Drupal module to add a Creative Commons license to entities? I am looking for a module (beyond the Media Gallery module) that allows content creators to licence the content they create by means of the Drupal WCMS under one of the Creative Commons licenses. Is there a module for this?

Yes, in addition the the Creative Commons licensing support that is integrated in the Media Gallery module, there exists a module for that does exactly that: the Creative Commons licenses module. From the project page:

  The Creative Commons module allows users to select and assign a Creative Commons license to a node and any attached content, or to the entire site. It also provides integration between CC and Drupal technology.

It was originally written for D6 and is still under development for D7 (up to alpha2 at the time of writing), but the core functionality is in place.

Somebody may ask:

  "Why would you need a module for that? Why can't you just add an Entity Reference field to link to whatever license the user chooses? What tasks should this module accomplish that a simple dropdown (or dropdown with link) cannot?"

The answer is that there is a lot more to Creative Commons licensing than just linking content to the CC license.

I think that reading the road map for the D7 port will shed some light on what is desirable, and why you need a module to accomplish it. To summarize: When licensing content under Creative Commons it is highly desireable that RDFa and ccREL metadata is properly presented, and you need more than a link for that. A CC search option should also be is available.

Looking at the issue queue for the Creative Commons module, it looks like development may have stalled when it comes to porting the more advanced features of the D6 version to D7, but I think it still is worth checking out.

There is also an experimental module named Attributions. It is not only for Creative Commons. It lets module and themes authors who use third party materials (e.g. fonts, photos and icons) that requires attribution register an attribution string in the project's .info-file. All the registered attribution strings from various projects can then be shown together on an attribution page or block.  Disclosure: I am one of the co-maintaners of Attributions.


hook_views_pre_render and hook_node_view In my custom module I'm creating a logic with two fields.

The first field is an image and the second is date field.
When I choose past date from the date field, the image field should be hidden. If the date value is present or made in future, the image will be visible.

It's working great on hook_node_view, but I can't figure out how to do this on views.

Here's my code:

<?php
function custom_alter_node_view($node, $view_mode, $langcode) {
 if ($node->type == 'hot_offers') {
    $c = strtotime($node->field_hot_offers_new_date['und'][0]['value']);
    $current_time = date("m/d/Y H:i:s");
    $d = strtotime($current_time);
    if ($c < $d) {
    $node->content['field_hot_offers_new_image']['#access'] = FALSE;
    }
  }
}

I know there's a hook_views_pre_render, but how do I create the same logic, so the image will be visible only if the date field value will be present or in future?

I've solved the puzzle and I'm sharing the solution.

function custom_alter_views_pre_render(&$view) {
    if ($view->name == 'hot_offers') {
        //dpm($view);
foreach ($view->result as $key=>$value) {
    $c = @$value->field_field_hot_offers_new_date[0]['raw']['value'];
    $d = date("Y-m-d"); //2014-06-26
    if ($c < $d) {
    $value->field_field_hot_offers_new_image[0]['rendered']['#access'] = FALSE;
    }
  }
 }
}

The tricky part was to set the $d same format as the new_date field, otherwise the if statement logic will not work.


Trying to update taxonomy menu item with hook_taxonomy_menu_update I'm having issues getting this to function to work, if I understand correctly this hook fires after saving or creating a taxonomy term.

I am also unable to use dpm($item) as nothing is rendered

function form_alter_taxonomy_menu_update(&$item) {
    $item['options']['attributes']['class'] = 'myClass';
    return $item;
}

Can anyone spot what I have done wrong

If you're just adding a class, I wouldn't rely on a hook from the taxonomy menu contributed module at all. Do it at the theme level like this.


do the sum of two commerce_price field with programming api I want to do the sum of two commerce_price fields and set the result in another one.

i've tried to just add the related ['amount'] values and set the result into another price field but it looses the components (VAT, taxes...).

Is there a commerce api call to do that ?
Such as :

add_price($price1,$price2)

returning the full added price with all it's component ?

Thx

There is no basic price addition function, though we have API enhancements on the roadmap for Commerce 2.x. I'd take a look at what commerce_order_calculate_total() is doing to figure the order total price field; you have to sum the amounts, like you've already discovered, and you then use commerce_price_components_combine() to merge the two price fields' components arrays together. Hope that helps!


PHP require_once() warning with hook_menu I'm writing a small module for learning purpose, where I try to create a module settings form using hook_menu() and form_api.
Everything look good in my code but I still getting this error message :

  Warning:
  require_once(/var/www/html/drupal/modules/system/demo_usernames_form.inc):
  failed to open stream: No such file or directory in
  menu_execute_active_handler() (line 515 of
  /var/www/html/drupal/includes/menu.inc). Warning:
  require_once(/var/www/html/drupal/modules/system/demo_usernames_form.inc):
  failed to open stream: No such file or directory in
  menu_execute_active_handler() (line 515 of
  /var/www/html/drupal/includes/menu.inc).

function demo_menu(){
    $items[]=array();
    $items['admin/config/people/usernames']=array(
        'title'=>'bad usernames list',
        'description'=>t('configure not allowed usernames'),
        'page_callback'=>'drupal_get_form',
        'page arguments'=>array('demo_usernames_form'),
        'access arguments'=>array('administer site configuration'),
        'file'=>'demo_usernames_form.inc',
        );
    return $items;

function demo_usernames_form($form,&$form_state){
    $form['bad_usernames']=array(
        '#type'=>'textfield',
        '#title'=>'Bad usernames',
        '#default_value'=>variable_get('bad_usernames'),
        '#description'=>t('Enter a list of "bad usernames" separated by commas.  If a user tries to enter one of these usernames either on account creation or when editing their account, the form will display an error message.'),
        );
    return(system_settings_form($form));

}

If you look a bit closer at the path in the error message:

  /var/www/html/drupal/modules/system/demo_usernames_form.inc

You'll notice it's trying to find your include file in the system module.

It's happening because the user module's implementation of hook_menu() has this in it:

$items ['admin/config/people'] = array(
  'title' => 'People',
  'description' => 'Configure user accounts.',
  'position' => 'left',
  'weight' => -20,
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

Notice the file path at the bottom, explicitly setting the path Drupal should look for the included file in.

Since properties are inherited from parent paths, and the path of your item sits nicely under that one, you get an implicit file path that you weren't expecting. The result: your module path is no longer consulted when the system tries to find the include file.

To fix, just add the correct file path to your hook_menu() code:

$items['admin/config/people/usernames']=array(
  'title'=>'bad usernames list',
  'description'=>t('configure not allowed usernames'),
  'page_callback'=>'drupal_get_form',
  'page arguments'=>array('demo_usernames_form'),
  'access arguments'=>array('administer site configuration'),
  'file'=>'demo_usernames_form.inc',
  'file path' => drupal_get_path('module', 'demo'),
);

And flush them caches.


Show a Custom Block on Homepage in Drupal 6 I am trying to show a simple block on my home page in Drupal 6.

The Drupal has simple HTML Text.

My question is that how can I show it in my code in let's say Page.TPL.PHP

I searched Internet and tried this:-

 if (drupal_is_front_page()) {

      // $block = block_load('block',314);
      // $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
      // print $output;

      $block = module_invoke('user', 'block', 'view', '314');
      print $block['content'];

The block num is 314 but other than that I am not sure that what user, block or view means in the function. I want to show it on the home page, hence I put it in a condition.

Do I have to leave it disabled or should I enable it in some region so that it can be shown on the Home Page?

Thanksa lot.

If you have a suitable region to display the block, why not set it to display in that region and in the Block Visibility settings configuration under Show block on specific pages select Only the listed pages. Then in the text area type <front> to display it only on the front page.


Contextually filtering a view using values from a completely separate table? I have a table "user_connections"

id | uid1 | uid2
1  | 1    | 2
2  | 3    | 1
etc

So, if the current user has uid = 1, then according to my table, he is "connected" to use 2 and 3. So I just want to be able to do something like:

select uid1 from user_connections where uid2 = :currentUserUid

Then pass these uids as a parameter to the view. So that it is ultimately used as a "where in" condition.

Any ideas how to do this? Or what is the best way?

Make sure you check mark allow multiple values on your contextual filter's "More" settings.

Use hook_views_pre_view to pass your uid's to the arguments (contextual filter).
/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $uids = [2, 19]; // hard coded example, you would query db here.
    if (is_array($uids)) {
      $uids = implode('+', $uids);
    }
    $args[0] = $uids;
  }

}

You will also need to disable the view's caching or add a cache tag if you created one for your other table query.


Use orConditionGroup with query (non entity) I've used orConditionGroups with queries before. Specifically with entity queries. But now I have a custom sql table I created separate from drupal but still on the same database I have access to. I want to update a row if any of the fields are different but I'm having generating the or statement. Here was my attempt.

$connection = \Drupal::database();
$orConditionGroup = $connection->orConditionGroup()->condition('address', $fulladdress, '!=')->condition('full_name', $fullname, '!=')->condition('telephone', $workphone, '!=');
  $connection->update($table)->fields(['full_name' => $fullname, 'address' => $fulladdress, 'telephone' => $workphone, 'email' => $email])->condition('id', $id)->condition($orConditionGroup);

But I get the error

  undefined method
  Drupal\Core\Database\Driver\mysql\Connection::condition()

Which makes sense since the connection class isn't a query object on its own, but not sure how else to tackle this. How would I create an orConditionGroup for just a plain direct sql query that isn't a drupal entity or anything like that?

I was able to get it to work by added the select method to the connection object like so:

$orConditionGroup = $connection->select($table)
                    ->orConditionGroup()
                    ->condition('address', $fulladdress, '!=')
                    ->condition('full_name', $fullname, '!=')
                    ->condition('telephone', $workphone, '!=');


How to ensure emails are sent only once to users in a Views Block Operations (VBO) list? I created a view which is a list of comments made by users to a particular node.

I then created a rule which triggers upon event "when a new comment is saved" The action is to load the view i created, loop through the list and then send an email to all the users who have previously posted comments.

My challenge is that it sends emails to the users based on the number of times they appear in the list. So for example a user who has made 3 comments to the node will get three (3) emails each time a new comment is saved.

I have tried using the Distinct query. It did not work.
I also installed the Views distinct module and selected the filter option. This filtered the list to one value each, but mails were still sent multiple times to people who had commented more than once.

Please is there a way to ensure emails are sent only once irrespective of times user has commented to the node/appears on the list?

You can adapt my answer with a "trick filed" on your content type in this (last) answer. Update "trick field" when your mail is sent the first time.
Why is my rule that reacts on event "After updating an existing user account" firing twice?
Then hide "trick field" modifying your "form-id" and field name with this solution (2nd answer) Is there a way to prevent a user from seeing a field on their user profile page?


Inline style fetched from database I'm editing an existing Drupal 7 site, with coloured menu buttons, and each part of the site has the corresponding colours in it's titles and links.
For example: the menu item "about us" is coloured orange, and each subpage of "about us" uses orange for it's titles and links.

The problem is: these are all inline styles, fetched from the database table "field_data_field_colour" and printed by a template.
I can change the hex-colour values directly in the database, but I've looked everywhere and can't find where to change/set those colours without messing with the database.

The pattern field_data_field_ refers to Field storage. This data is attached to an entity of some kind, most likely a Node. You can learn more about content management on drupal.org, Nodes, content types and fields.

You should edit the node that you want to modify (admin/content or click Edit on a node if the tab hasn't been styled out of existence), and find the field that someone added there. Then you can change the value. You can check what fields are used in which entity types by going to /admin/reports/fields. Each field usage has a link to its respective Field Management page where you can learn more about how that particular field is configured.

Modifying field_data_field_ directly in the database is incorrect because data retrieval happens in field_revision_field_ tables.


CSV import ends up in unresolvable state I'm having a problem with Feeds and Commerce Feeds in D7.

I am using Feeds and Commerce Feeds to import products into my Drupal Commerce store.

The CSV import was failing with a 403 error. Once this happened the import button was greyed out with text showing "importing 21% complete". Initially I cleared the message by running a delete and then reuploading. Now the delete tab has the same problem! It says "deleting 51% complete"

I have added a support request for this on drupal.org; but I think that the question may be better suited here as a "how-to" type answer would seem more appropriate.

Any ideas on how I can sort this out?

I solved the problem by cloning my import.

When I selected the cloned import it wasn't hampered by the progress information and greyed out import button. I could just upload my csv via the new import.


Rewrite the html tags for frontpage I am using views for front page. I was able to customize some things.

But I have some

 in the body of an article and for the frontpage I want to change that automatically into

. Is that possible with views and if yes, how?

If you are having issue with the content that is being printed on the front page.
Then you can create a page--front.tpl.php and print the variable according to the requiremt.

If $title gives you the <h1> and <h2> tags, then you can strip_tags($title, 'tags that need to be maintained e.g. <a>') to remove the tags.

If you have issues with views field label, you can use 'Rewrite the output of this field' and 'Strip HTML tags' to change the output mentioned in the image below:-

Hope it will help!


Feeds creates duplicate content each time cron runs I have created a custom feed importer but each time it runs it creates the same content again. How can I make it only create the content once?

In order to update existing nodes, Feeds needs a unique ID to match the source item with the target node. Otherwise, Feeds cannot know which node to update, so it just creates a new one.

When configuring the mapping for your feed importer, choose a unique field in the source, map it to the 'GUID' target and check the 'unique target' checkbox.


multiple submit button I have two submit buttons in two field .
My problem is that if I press ENTER from the field 2 of textfield , Submit 1  gets triggered instead of trigger submit 2.
but submit handler works perfectly for both submit button when it is clicked.

This is native browser functionality, you are going to need to use JavaScript to circumvent and add your own behavior


Vote Up/Down Widget only visible to admins I have installed the Up/Down Vote module under Drupal 6.x and it is working fine when I use it under my admin login.  However other logged-in users do not see the widget.

Below are screens of the installed modules and all of the config I can access.

What do I do to enable for other users?

Set the permission for authorized users to be able to vote.

There will be a checkbox you need to tick.

Visit /admin/user/permissions and look for permissions relating to this module.

See this page for more help.


Display a text field on a node/add form I want to display a text field on a content type which is simply a paragraph of text (non-editable). Is it possible to add such a field.

The context: I have a node/add form available to anonymous users so that they can create a content type of 'contact form'.

I am using conditional fields to display certain fields based on the choices made in creating the contact form.

I would like to be able to add a 'message' that displays if they select a certain field.

For example: if the problem selected from a  select box is 'forgotten password' then the paragraph message would appear directing the user to the retrieve password page via a link.

I think you can use Static Field module to add your text as a separate field. In this case it can be shown/hidden by conditional fields


User roles and permission for 1 can publish and 1 can't I have 2 user roles which I created

1] Article Creator  -> Can Create/Update/Delete
2] Article Publisher -> Can Create/Update/Delete/Publish

Article Creator can create content, but can't publish. While Article publisher can do that.

Can we manage it without any module or any custom coding?

Can manage from default Drupal Admin?

You are looking for Workflows and Content moderation. Those are features available out-of-box in Drupal 8 (stable form 8.4)


How to integrate Field collection module in Views? I have created fields and grouped together with Field collection module. I have attached the group field (containing 4 fields), to user account settings in :  admin/config/people/accounts/fields.

Now I am trying to display the content of this field-collection into a view, however I can not do it!

Views 7.x-3.0-beta3 do not allow me to specify the current user and to get in a table the  field-collection contents. How can I get this contents into a view-kind table?

UPDATE:
I have seen that Field collection module has a patch for Views module here: Add Views Relationship to Field Collection - patch attached which is already included in Field collection 7.x-1.x-dev. This allows me to have access at field in collection form Views, however is not allowing me to set a custom filter for the entity of which I associate the field collection. I my case is the user ID.

How can I have access to that form views ?

What kind of view are you creating?

Since the collection is being used in the user entity you should create a user view. This will allow you to set the user id filter you want to set.

Once you create that user view you will need to add the field_collection relationship to display those appropriate field.

This is assuming you are using the latest field_collection - dev version.
Hope this helps.


Multiple users on one profile? Does anyone have any solutions for multiple users using one profile? Looking for something like profile2 but with the option open for more than one person to use a single profile. Say for instance a company name or organization.

Using Views sounds like a way to go. You could have separate employee and company profiles (where employee profile references company), and then add a view to each company profile listing all its employees.