How to index field as single value? I use Search API, Search API Database and FacetAPIto create custom search. And there are mistakes in facets when it displays field with hyphens. For example, there is a text field "city" with value of "Rostov-na-Donu" (the name of the city in Russia). Facets show me three values: Rostov, na, Donu. But I want only one value for this field and it should be entire field content.

Please help.

The solution was to index the field as "string", not "fulltext".


Twitter like notification when new posts are made I was wondering if there was a module out there that could replicate something to what Twitter do when you have new Tweets you haven't seen in your timeline (so a notification of how many new items there are without refreshing the page).

See examples of what I mean, not the best at explaining things. preferably without using node.js as it hasn't worked for me so far!

Thanks in advance

You can use nodeJS to push live updates to your website without refreshing it, thus you also can count the new items.

There is a module that integrates with nodeJS: https://www.drupal.org/project/nodejs

You will need SSH access to make this work I think.


Create a view that displays only the fields from the most recent user node To specify, I want the view to only apply to one single node and not all other nodes and only pull fields from that one particular node that was last created. As of now the view displays all the nodes and their fields with a pager, I just want it to load content from the last node created by that user.

Can anyone suggest?

Add a contextual filter for user
Set pager to "none" and "number of items to display" to "1".
Set a sort criteria to sort by date, descending.


Secure webform inside non-secure page My Drupal 7 site uses both Webform and Secure Pages modules. I've created webform which is available as a block inserted to the bottom of another Drupal node. This node should be accessible using http protocol, but the submission of the form should be encrypted using https.

There is an option in the Secure pages (called "Secure forms") for entering form ID's, which should have https flag set to true. So I've enetered the form ID ("webform_client_form_183") here and the result is, that the module generates correct form action (). But, when I submit the form (from let's say URL http://mysite.com/thepage), the form content isn't saved to the database and URL https://mysite.com/thepage is loaded to the browser instead. The form here is filled in with the data I've entered in previous step and submitting the form from https://mysite.com/thepage does finally the right thing and data are stored in the database.

What I should do to correctly submit (using https) the form from page located at http://... URL?

You shouldn't really try. If form is served via HTTP, attacker already stolen your user's data using MiM attack to inject his own JS code into your site, so sending it via HTTPS is pointless at this moment.

If you need reliable security, always serve form using encryption. If you don't, don't waste resources on unneeded SSL processing.

See Transport Layer Protection Cheat Sheet for more details, as Clive suggested.


Print node URL in a custom block template I have a custom block that loads multiple nodes from the database and passes it to the twig template.
Inside the template I loop the list printing some node details, but I need to create a link on the node title, possibly its clean (alias) URL. The problem is that with node.url I get a security error:

  Twig_Sandbox_SecurityError: "Calling "url" method on a "Drupal\node\Entity\Node" object is not allowed

I tried with {{ link(item.label, item.url.value) }} but I get the same error.

What is the correct way to create a link in twig using the node URL?

Ok, it seems I have solved the problem using twig/drupal path() function, building the linked title in this way:

{{ item.label }}

where "item" is the node object inside the list loop.


Uploading youtube videos to the site I would like to be able to upload youtube videos to the new site I am currently building. I would like to have a page which will list ALL the youtube videos uploaded, and then on the homepage, I would like to have a single video selected from the list of already uploaded youtube videos (changeable).

I would like it to be as simple as possible. I was thinking of a YouTube Field module. Is this simple enough?

I was thinking of possibly using Views to list all the Youtube Videos... but how would I embed the one on the homepage?

Any feedback and advice would be appreciated.

I am not sure what you are trying to do, but I recently tried a module that allows you to upload your videos via your website to Youtube. Check it out:

http://drupal.org/project/video_upload

On the other hand, if you simply want to integrate existing Youtube videos to your website (as fields), simply use the Media modules:

First of all, you need Embedded Media Field module:
http://drupal.org/project/emfield

Then install Media: Youtube to integrate your videos:
_http://drupal.org/project/media_youtube

You can list, sort, filter all your nodes (that contain your video field) very easily with views.

I hope this help, feel free to ask some more details.


Drupal sitemap still contains urls of deleted pages I've deleted some products from my commerce kickstart database by means of standard Drupal commerce kickstart tools. But it looks like something gone wrong. Because some deleted pages urls still remain in sitemap,so Google webmaster tools tell me about 404 pages.
   I've rebuilt sitemap n+1 times but urls of deleted pages still here, in sitemap file. Checking manually commerce_product table,for example,I found  that there are some tails(that should be deleted) remain in it.

What tables should I check up to find tails have to be deleted manually?What tables does the sitemap module use to build sitemap file?

if you are using the XMLSitemap module, uninstall it and run cron to delete its tables from the database, then reinstall it, it will generate the right urls


How to update header text in hook_views_pre_render I have a view with a header of type "Global: Unfiltered text" that contains the string "Number of drivers: ".

In hook_views_pre_render I count the total number of drivers in each row, and now I want to append this number to the string in my view header.

I did a print_r on the $view object in hook_views_pre_render and found 59 instances of that string.

If it was only a few I would just try replacing each one until it had the desired result - but 59?!?! Too much recursion...

So how do I find which value to update in order to update the text in my view header?

Well the important thing is to narrow down the particular view display you want to affect. Then you can look at the header text later. I have the following similiar code ... you should be able to use views_pre_render fine, I don't use that here:

function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'migration_audits') {
    $drupal_nids = array();
    if (count($view->result)) {
      foreach ($view->result as $i => $node) {
        $drupal_nids []= $node->nid;
      }
    }
   $sql = " ... ";
   $result = db_query($sql, array(':drupal_nids' => $drupal_nids));
    $output = '';
    foreach ($result as $course) {
      #dpm($course);
      $title = html_entity_decode($course->course_title, ENT_COMPAT, 'UTF-8');
      $instructors = html_entity_decode($course->instructor, ENT_COMPAT, 'UTF-8');
      $output .= "
$course->quarter $course->year - $title Instructors:&nbsp;$instructors
";
    }

    $my_values = "
$output
";
    $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values;
    $view->display['page']->handler->handlers['header']['area_1']->options['empty'] = 0;
  }
}

You can also do like $view->display[$view->current_display] usually as a safe none hard coded approach. Note that the global header regions are given names such as area_1, area_2 etc as a convention by Views. I also tell Views the area is now not empty.


Vertical Tabs in Front End (Drupal 7) I am trying to use Vertical Tabs on the front end of my site.

Normally, I would just add a jQuery plug-in to my theme. However, vertical tabs are built into Drupal 7, so it seems silly to use a plugin, when the functionality already exists.

I'm just not sure how to call the built-in vertical tabs.

Dan Silver's blog has an excellent tutorial on how to call the built-in tabs. However, his tutorial is for horizontal tabs. I am not sure how to convert them to vertical ones.

I would appreciate if anyone could give me some hints.

(P.S. I am aware that modules exist to do this. However, for my purposes it seems overkill to use a module when I can achieve it with a few simple lines of theming).

The examples module will provide you some custom code to implement this, have a look at the API documentation which add a vertical tab to the node form.

The only restriction I can think of is that this code is for forms so if you want to theme a node output you should use jQUery UI tabs. The tutorial you linked seems fine, but you'll need to change a little its CSS classes in order to output vertical tabs, compare its code tho this demo.


Where to modify feed status to change number of created and updated nodes i want to change the message after a feed is completed that shows the number updated and created.  What file in the feeds module is the one that outputs this message? using Feeds 7.x-2.0-alpha9

the progress is in  feeds.pages.inc
but I still cannot find where  the number created and updated is

in feeds.pages.inc, function feeds_source_status() the status information is shown for the importer, including the number of imported items. The number of items is calculated in FeedsProcessor::itemCount() in plugins/FeedsProcessor.inc.

The message of how many entities were created and updated happens in FeedsProcessor::process(). FeedsSource::$state keeps track of these numbers. The case where these numbers might not be accurate is if the same entity is updated multiple times in a single import. Usually, this is caused by a configuration error: the target that is configured as unique appearantly isn't unique in the source.


Database corruption after trying to reinstall Rules Module I was getting a database error when trying to op the Rules UI so I tried to reinstall the module. I uninstalled the Rules Modules and Rules UI module then tried to install the Rules module and now every page of the sites gives this error:

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;sgda_arcade.rules_config&#039; doesn&#039;t exist: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] =&gt; reaction rule [:db_condition_placeholder_1] =&gt; 1 ) in EntityAPIController->query() (line 152 of /srv/arcade/sites/all/modules/custom/entity/includes/entity.controller.inc).

Additional

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;sgda_arcade.rules_config&#039; doesn&#039;t exist: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] =&gt; reaction rule [:db_condition_placeholder_1] =&gt; 1 ) in EntityAPIController->query() (line 152 of /srv/arcade/sites/all/modules/custom/entity/includes/entity.controller.inc).

Is there anything I can do to fix this?

As it turns out the drive on which my database was installed had run out of disk space, so as JimaJamma suggested, the table could not be created by the rules module.


Multi step user registration form drupal 6 How to do Multi step user registration form in drupal 6 ?

I am having an idea of doing multistep process using custom form.

But i am bit confusing while doing the same case with "user registration".

For example :

Let us consider i am having 10 fields and separating it with three forms like 4+4+2.

Now when i complete the first form and click next button where should i need to save the values of current form. I used $form['storage']. But it didn't helps.

Could anyone please clear me this or provide me an easy tutorial for "multistep user regsistration".

Any help will be thankful and grateful..

Thanks in advance..

This blog post may help you: Multistep registration form in Drupal 6


How do I create a link to a node to put in new entity? So what I'm trying to do seems pretty simple.  And I've found lots of posts similar to it but none have really helped me.

I have a an application content type, when somebody submits it, I'd like to use the rules module to create a post in the forums that has either
a.) a link to the application
b.) the data from the application in the body of the forum post.

I've figured out how to create a forum post each time the application is saved.  Seems to be working ok.  I've also figured out how to set the body to be either a static message, or the contents of ONE of the fields from the application.

What I cant figure out is how to either combine fields from the application to set the forum body to (which i'm guessing is a more complex thing), or to simply have a link to the application be what is put in the body of the forum message, which seems like it should be simple.  I've looked at the rules faq at https://groups.drupal.org/node/15542 but it seems to think that i should have a NID option in the selector which i do not. (yes its set to trigger after save)

My data selector for setting the body field of the forum entity only includes site, node, and entity.  And the Node options are only the individual fields of the application.  It doesnt include any NID or options to link the the node itself.  I choose other options like convert data type i can find UID and URL options, but then I don't know how to use the variable in the set data action.

I'm guessing that it has to do with the type of the body field and its only showing me things of the same type and i have to convert the UID/URL or something, but apparently I'm slow, anyone want to point me in the right direction?

My current rule (in export format):

{ "rules_test_application" : {
"LABEL" : "test application",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--guild_application" : { "bundle" : "guild_application" } },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "guild_application" : "guild_application" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "forum",
        "param_title" : "New App: [node:title]",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : { "data" : [ "entity-created:language" ], "value" : "en" } },
  { "data_set" : { "data" : [ "entity-created:taxonomy-forums" ], "value" : "9" } },
  { "data_set" : {
      "data" : [ "entity-created:body" ],
      "value" : { "value" : {
          "value" : "link to application that generated this post",
          "format" : "Plain_text"
        }
      }
    }
  }
]
}
}

Entity-created:body was a formatted text type.  Because of that the rules selector was only showing values from the Node that were also Formatted text.

Once I changed the data value i was modifying to entity-created:body:value, the text part of the formatted text, it allowed me to select more things in the selector including the node:url.


How to avoid Drush command not found after switching to aegir or other user? I installed Drush like this:

It works fine when I am centos user, when I switch user to aegir it doesn't work.

When I do which drush I get:

How can allow user aegir to use Drush?

Try to create a symlink to let all user access drush.

sudo ln -s /usr/local/bin/drush /usr/bin/

if not worked try

sudo ln -s /usr/local/bin/drush /usr/share/bin/


How to use dependency injection for Plugins/Blocks [\Drupal::formbuilder() and \Drupal::config()]? I cannot get my head around this dependency injection theory. How are we supposed to get the below methods aligned with dependency injection?

\Drupal::routeMatch()->getParameter('node');
\Drupal::request();
\Drupal::formBuilder()->getForm('Drupal\enquirycart\Form\EnquiryForm');
\Drupal::config()

Here is a class that I need to fix this warning message when viewed in
https://pareview.sh/

  "\Drupal calls should be avoided in classes, use | | dependency
  injection instead"

    class EnquirycartBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_config = \Drupal::config('enquirycart.settings');

    return [
      'label_display' => FALSE,
      'enquiry_email' => $default_config->get('enquirycart.email'),
    ];

  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $builtForm = \Drupal::formBuilder()->getForm('Drupal\enquirycart\Form\EnquirycartButtonForm');
    $renderArray['form'] = $builtForm;

    return $renderArray;

  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form_new = parent::blockForm($form, $form_state);

    return $form_new;

  }

For future reference, from the link by @Kevin:

  The key to making plugins use dependency injection is to implement the
  ContainerFactoryPluginInterface. When plugins are created, the code
  first checks if the plugin implements this interface. If it does, it
  uses the create() and __construct() pattern, if not, it uses just the
  __construct() pattern. - From Acquia's Lesson 11.4 - Dependency injection and plugins

The example code below is written by Mart Matsoo from Chromatic. Please check the full article here: https://chromatichq.com/blog/dependency-injection-drupal-8-plugins. As @Kevin already mentioned in the comments it is a great article about Depencency Injection in Plugins.

Dependency Injection example in a block

Note the injection of the 'current_user' service via $container->get('current_user') in the create() method. You can pass extra services there.

<?php

namespace Drupal\heytaco\Plugin\Block;

use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Hey Taco Results Block
 *
 * @Block(
 *   id = "heytaco_block",
 *   admin_label = @Translation("HeyTaco! Leaderboard"),
 * )
 */
class HeyTacoBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var $account \Drupal\Core\Session\AccountProxyInterface
   */
  protected $account;

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   *
   * @return static
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param \Drupal\Core\Session\AccountProxyInterface $account
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }

Dependency Injection example in a controller

The same concept applies here, pass extra services via $container->get() in the create() method.

<?php

namespace Drupal\heytaco\Controller;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for HeyTaco! block.
 */
class HeyTacoController extends ControllerBase {

  protected $account;

  public function __construct(AccountInterface $account) {
    $this->account = $account;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }


Export node report base on Word and Excel template I want to export node content to Word or Excel.
Are there any module to do this?

You can use the Views Data Export to export in many popular table formats.  XLS, CSV, DOC, TXT and XML.

Some other modules worth mentioning here:

Views Datasource

Service Views

It should go without saying that the modules above will require Views be installed and enabled.


Redirect after login to specific page We have a link on our site which will redirect users to the edit profile page when they are logged in.

We have same link for the anonymous users which will redirect the user to login page when it clicked.

We would like to redirect users to the edit profile page after login but if users use normal login link, after login, they are redirected to the homepage.

I would like to know how we can redirect users to edit profile page after login only if they clicked on the edit profile link.

In Edit Profile link append destination parameter like:

if(user_is_anonymous()){
  $editlink = l(t('Edit Profile'), 'user/login', array('query' => array('destination' => 'user/UID/edit')));
}

Then after login, it will redirect to profile edit page.


Display user field into html.tpl.php In my user-profile.tpl.php file In print fields like this :

<?php

    global $user;
    $user_id = arg(1);

    $user_item = user_load_by_name($user->name);

    if($user->uid == $user_id) {
        echo 'I'm connected';
        print render ($user_profile['field_mon_statut']);
    }

 ?>

I wrote this exact same code in html.tpl.php but it does not appear..

Thanks for your help !

U are setting $user variable inside if condition, while in if u have condition that $user->uid, so it will compute as false, and it will not go inside if condition.

You will have to write:

global $user;
if($user->uid) {
// Your code

// Edited

global $user;
$user_id = arg(1);

// $user_item = user_load($user->uid);

if($user->uid == $user_id) {
    echo 'I m connected';
    print render ($user_profile['field_mon_statut']);
}


Handling mobile images in responsive theme Sorry for the open-handed nature of the question, but I don't know where else to get an answer to this. I'm deciding whether or not go full-force into a responsive Drupal 7 theme, probably the Omega framework.

One issue that keeps nagging at me is that the mobile devices have to download all the large images (not to mention everything else...).

Is there an easy way to serve up smaller images for mobile devices?

There are many modules to handle responsive images, including;

Responsive Images
Client-side adaptive image
Adaptive Image Styles (ais)
Adaptive Image
Borealis


Does Drupal override php setting by it self by .htaccess? When I migrate or restore a Drupal 6 site Always php version I have set in the account page of the shared hosting service has been automatically changed.

For example, though I have set php 5.3 for example.com when I restore the site using exactly the same domain, files, db and the host after the restoration php version is set to php 5.1

Also after the restoration php.ini file gets set back to OFF though it was set to "On" before the restration.

I contacted the shared hosting company but they say I should check the .htaccess file that overrides the php setting.

Does Drupal do this?

Does Drupal override php setting by it self by .htaccess?

No.  Nor does it do it by any other method.

As pointed out in the comment by kiamlaluno,  Drupal comes with its own .htaccess file. You'll find it as one the files in your Drupal root.  You can read through it yourself and see that it does not change the setting of PHP version that you set in the account page of your shared hosting service.

The .htaccess overrides some settings that may be set different in php.ini, as shown in the directives below (copied from the default .htaccess file), but not anything else.  As you can see, it has IfModule directives that makes the overrides contigent on the versions of PHP and Apache you use, rather than overriding the version.

# PHP 4, Apache 1.
<IfModule mod_php4.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 4, Apache 2.
<IfModule sapi_apache2.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

The changes you ask about cannot be explained by the Drupal .htaccess-file or anything else done by Drupal. Nor do I know about any backup/restore program or migration program for Drupal that does such things as those you describe.


How to store a nodes Fivestar average rating inside another field with computed fields In order use rating to sort on inside search api, i'm trying to store the fivestar decimal value inside another field that can be indexed. This is because Fivestar doesn't play nice with search_api, so this will be a workaround.

I have a computed field that performs different tasks on the node such as copying the field_review_votes_average to field_index_review_score. I'm using this code to do so.

$entity->field_index_review_score[LANGUAGE_NONE][0]['value'] = $entity->field_review_votes_average[LANGUAGE_NONE][0]['average'];

But I keep getting Notice: Undefined index: und, what code can I use to to retrieve the average score?

Eventualy I used a different methode to get the average value. Here's how

 //Get average rating and place in index review score
    $average_field = field_view_field('node', $entity, 'field_review_votes_average');
    $rating = $average_field['#items'][0]['average'];
$entity->field_index_review_score['und'][0]['value'] = $rating;


Drupal template files are not recognized sites/all/modules/dc_wiwo
function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'template' => 'wiwo',
    ),
  );
}

function dc_wiwo_page() {
  return theme('dc_wiwo_page', array('tweets' => array()));
}

If I put a template file in sites/all/modules/dc_wiwo/wiwo.tpl.php it works, but if I put a file in sites/all/themes/media/wiwo.tpl.php it doesn't work. I thought you could override templates in the theme. Is there a setting I have to change to allow this?

By default, the template file is expected to be in the same directory containing the module or the theme which defines the theme function. To use a different path, in the hook_theme() implementation you need to use the path property, which is defined as:

  path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

So, in your case the code should be similar to the following one, since you are using a theme.

function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('theme', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}

For a module, the code would not be much different.

function dc_wiwo_theme($existing, $type, $theme, $path) {
  return array(
    'dc_wiwo_page' => array(
      'variables' => array('tweets' => array()),
      'path' => drupal_get_path('module', 'dc_wiwo') . '/media';
      'template' => 'wiwo',
    ),
  );
}


Setting View Filter Operator to "Greater Than Or Equal To"? I have a view for which I've set different exposed filters and users can search for objects of different criteria. However, I want some fields to be searched by "Less than/Greater than or equal to" what the user types. I don't have those options in the operator field. Some people seem to have them however.

The operators you get in a Views exposed form depends on the type of data that is stored. If you store a text string you can't use GT or LT, instead you can use starts with or ends with.

Most likely your problem is that you are storing numbers as text in the database instead of storing them as numbers.


What's the best way to allow a user to save variables/options I have a user who wanted to save some configuration options for his site. I had initially created a content type of Options, then created a node for that user so they could edit it, and didn't allow them to delete or create any other nodes of this content type. But it feels like this isn't what content creation was created for!
Am I missing a trick in allowing users to save options, or should I just create a custom form and save it to db?

Yes, instead of content entities you can use config entities. But for only a few configuration options this is too much effort. In this case you can use the Simple Configuration API, either by creating your own form
https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms
or by adding form values to existing admin forms in a form alter hook.
See for example how the core dblog module adds an option to /admin/config/development/logging when it is enabled:
/**
 * Implements hook_form_FORM_ID_alter() for system_logging_settings().
 */
function dblog_form_system_logging_settings_alter(&$form, FormStateInterface $form_state) {
  $row_limits = [100, 1000, 10000, 100000, 1000000];
  $form['dblog_row_limit'] = [
    '#type' => 'select',
    '#title' => t('Database log messages to keep'),
    '#default_value' => \Drupal::configFactory()->getEditable('dblog.settings')->get('row_limit'),
    '#options' => [0 => t('All')] + array_combine($row_limits, $row_limits),
    '#description' => t('The maximum number of messages to keep in the database log. Requires a cron maintenance task.', [':cron' => Url::fromRoute('system.status')->toString()]),
  ];

  $form['#submit'][] = 'dblog_logging_settings_submit';
}

/**
 * Form submission handler for system_logging_settings().
 *
 * @see dblog_form_system_logging_settings_alter()
 */
function dblog_logging_settings_submit($form, FormStateInterface $form_state) {
  \Drupal::configFactory()->getEditable('dblog.settings')->set('row_limit', $form_state->getValue('dblog_row_limit'))->save();
}


Hybridauth facebook and google login not works in live server I am using the HybridAuth Social Login for social media login for my website. The login works in my local server but the user profile picture is not fetched.

But in live server nothing works, it just returns some message like so:

  Closing..

I also changed my website url in Facebook and Google URL field for live server, but still it's not working.

Does anybody know what I missing here?

Please try out the below possibilities.

If you have any Redirect rule enabled, please disable it. OR
Set Redirect after login path in HybridAuth configuration. OR
May be javascript error was stopping the process. You should also uncheck "Aggregate Javascript files" under Performance to actually see what's going on more precisely.

I Hope it will solve your problem.


How would one upload a list of users via a .csv file and have them blocked by default? The user import modules exists for Drupal 7, but how would one import a list of user from a csv file into Drupal 8? And once they are imported, have them blocked by default.

Now when the users come to the site to register, they can only register with one of those imported accounts on the csv. So that means you cannot create a new account, but only unblock an existing account in the system. How would one accomplish this setup?

I suggest setting up a Migration using Migrate CSV. When Feeds is ready, it should be possible, but it looks incomplete at the time of posting.

Using the migrate code that you implement, set the accounts as blocked by calling $user->block() per User import.

Block any anonymous user registrations, this will make new user additions possible only by admins.

In place of the user reg form, create a new custom form using Webform module or core Contact module. You can replicate the fields from the reg form of use to you there. On form submission, using a custom module including a hook_form_FORM_ID_alter, do a check on the submitted form for email address and verify if it matches, then call $user->activate() to unblock the user account.

Or if Rules module provides you the necessary settings through the UI, you could try the email address check using that, but this module maybe incomplete for this type of check at present.


How to sub_process a non-associative array in migration.yml I know I can use sub_process to iterate over an associative array like

field_categories:
  plugin: sub_process
  source: remote_categories
  process:
    target_id:
      plugin: migration_lookup
      migration: my_existing_taxonomy_migration
      source: name_of_key

But I don't know how to iterate over a numeric / non-associative array. Assume the JSON data structure

{
  remote_categories: [ 'alpha', 'beta', 'gamma' ]
}

how can I pass the values as keys to migration_lookup? I.e. what would be name_of_key in the example above?

I've written a process plugin that transforms a sequential list into an array of associative sub-arrays, so sub_process and migration_lookup can use them.

namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Transforms an array of values into an array of associative arrays.
 *
 * The inner array will be filled with one key. E.g. ['alpha', 'beta'] becomes
 * [[value => 'alpha'], [value => 'beta']]
 *
 * Use this plugin to preprocess a numeric/non-associative array for other
 * plugins that requires an associative array as input, such as the sub_process
 * plugin.
 *
 * Available configuration keys:
 * - source: Source property.
 * - keyname: name of the key to be used for the associative sub-arrays,
 *   defaults to 'value'.
 *
 * Example:
 *
 * @code
 * source:
 *   my_flat_array:
 *     - category1
 *     - category2
 * process:
 *   my_associative_array:
 *     plugin: deepen
 *     source: my_flat_array
 *   field_taxonomy_term:
 *     plugin: sub_process
 *     source: '@my_associative_array'
 *     process:
 *       target_id:
 *         plugin: migration_lookup
 *         migration: my_taxonomy_migration
 *         source: value
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "deepen",
 *   handle_multiples = TRUE
 * )
 */
class Deepen extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $keyname = (is_string($this->configuration['keyname']) && $this->configuration['keyname'] != '') ? $this->configuration['keyname'] : 'value';

    if (is_array($value) || $value instanceof \Traversable) {
      $result = [];
      foreach ($value as $sub_value) {
        $result[] = [$keyname => $sub_value];
      }
      return $result;
    }
    else {
      throw new MigrateException(sprintf('%s is not traversable', var_export($value, TRUE)));
    }
  }

}


Block is not showing up in a custom taxonomy page template I am using Drupal 7
I have a content type courses. I have a page folder in template folder, with courses.tpl.php file. When i go to courses page it is showing contents from courses.tpl.php. Issues is that courses.tpl.php is not rendering blocks.

I checked region in info file. I cleared cache etc, but block is not rendering.
I am not sure, if this page is a taxonomy page. 'footer_testimonials' is the block i am trying to render in this page, but it is not showing up.

'footer_testimonials' is showing up in page.tpl.php but not in courses.tpl.php

    <?php print drupal_render(drupal_get_form('course_searchbox'));?>

<?php print $page['page']['course_page_top_ad']['block_1']['#markup'];?>

Popular Courses: Certificate IV in Bookkeeping, Diploma of Accounting, Diploma of Business, Advanced Diploma of Accounting

Courses

    Central College Distance Education offers a range of Government and Industry Accredited courses ready to help launch your career.  Remember, Central College has been launching careers for over 30 years.  You may also be interested in our specialty Central College Certificates that will help you better manage your existing business and do it in your own time at your own pace, right in the comfort of your home.

<?php
//$taxoTerm = course::get_taxonomy_term(1);
$categories = course::getAllCategories();

foreach($categories as $category):?>

<?php echo $category->name;?> Courses

            <?php //get courses by taxonomy
                $courses_term = course::courses_by_term($category->tid);
                $i = 0;
                foreach($courses_term as $course):
                $courseObj = course::getCourseByNid($course->nid);
                    $i++;
                ?>

<a href="<?php echo course::courseUrl_alias($course->nid);;?>"><?php echo $courseObj->title;?>

                <?php endforeach;?>

<?php
if($i%2==0):
    echo '

';
endif;

endforeach;
?>

Testimonials

<?php print render($page['footer_testimonials']);?>

A page.tpl.php template file doesn't get blocks to render; it gets the theme regions to render, which by default are the following ones:

$page['help']: Dynamic help text, mostly for admin pages
$page['highlighted']: Items for the highlighted content region
$page['content']: The main content of the current page
$page['sidebar_first']: Items for the first sidebar
$page['sidebar_second']: Items for the second sidebar
$page['header']: Items for the header region
$page['footer']: Items for the footer region

Themes can define other regions as well.

When you want to show a blocks that has been associated to the "highlighted" region, the page template file needs to contain the following code (or similar).

<?php if ($page['highlighted']): ?>
<?php print render($page['highlighted']); ?>
<?php endif; ?>

Without that code, a block that should visible in the "highlighted" region would not be visible.

In a taxonomy term template file, you need to get the block content using code similar to the following one.

  global $theme_key;

  $query = db_select('block', 'b');
  $block = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->condition('b.delta', $delta)
    ->condition('b.module', $module)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute()
    ->fetchObject();

  if ($block) {
    $array = module_invoke($block->module, 'block_view', $block->delta);
    drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);

    if (isset($array) && is_array($array)) {
      foreach ($array as $k => $v) {
        $block->$k = $v;
      }
    }

    if (isset($block->content) && $block->content) {
      // Normalize to the drupal_render() structure.
      if (is_string($block->content)) {
        $block->content = array('#markup' => $block->content);
      }

      print render($block->content);
    }
  }

You need to know the module implementing the block, and the delta used for that block. It is better to put the code in the preprocess function to set a variable that is then rendered in the template file. As usual, the logic code should be in the template.php file of the theme, or in the module file, and the rendering code in the template file. (Don't confuse the template.php file with the template file.)

Instead of executing that code, it is easier to assign the block you want to show in the taxonomy term page to taxonomy term pages. In the settings page for the block (admin/structure/block/manage/<block id>/form/configure) select Only the listed pages, and in the textarea enter:

  taxonomy/term
  taxonomy/term/*


How can I set a custom CKEditor on only one field? I'm using Drupal 8.

I have a field that can only allow for specific styles, so I created a custom CKEditor and set the field to use it.

Now when I go to the field on the content edit form, I see the custom editor as the default, as well as a select menu to specify which editor I want to use to enter content.

When editing this field, I do not want to show any other editor options and I only want the editor to be used for this field.

What is the best way to implement this functionality?

I believe the module you want to add is Better Formats. This will let you specify format options for a field, if you only want to show one (even if the role has access to multiple).

Edit, because it is not clear from the project page:

composer require drupal/better_formats:1.x-dev


Is there a limit of tags to associate with content? I am currently wondering if this is the way to do it and would therefore like some input.

The idea is that I want to show content to specific users. However this can not be done by creating a view with categories because it may not be all in a group that I want to show the content to.

That is why I am thinking of extracting a list of users (where companies have filtered by their request) and implementing them as tags on the content. I will therefore have total control over who's going to see the content.

Does anyone know of any limitations that might hinder this setup? I do not want the tags to show on the content and to be automatic generated from the list. Is this possible?

It's a simple you must follow this 2 Steps :

First Step :

Create a views that will list your users that you want to reference
Add a Reference display to your view make your filters then Save

Second Step :

Download entity reference module
Add new entity reference field  "Users that will access this content"
Chose the target type : User
Choose the mode "Views: Filter by an entity reference view"
Select the views that you've build on the first Step (the display type must be Reference and not page or block)

Now you will be able to select the users like a tags on content type but without any access permission

To restrict the Permission to the referenced user :
download the user reference access module

Then configure it under the user entity reference field settings of your content type


"Signature" user field not appearing in list of user fields I have the Drupal core Signature field that appears on the user edit page; it doesn't seem to show up as a field on the Manage Display tab when I go to re-order and group the fields on the edit page.

Does anyone know how I can get this field to appear in the field list with the rest of the fields so I can group and reorder it?

While it doesn't appear that you can put it in the field list directly and drag and drop it around as the user module only exposes the account and timezone in its hook_fields_extra_fields(), you certainly can move it around "manually" in a hook_form_alter() in a custom module, eg something along these lines:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_profile_form':

      drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>'); // to see what you have to work with

      $form['signature_settings']['#weight']='8';
      $form['field_my_second_custom_field']['#weight']='9';

      break;

    // other forms go here

  }

}

...which, if you had the following in your user:

...would create this in the edit form:

...eg, we moved the #weight around, which is what the drag and drop anchors do in the UI.

In this example, user.module initially creates the signature settings with a weight of 1, and then the custom fields with 7 and above, so, by changing the weight to 8 for the signature settings and the next field to 9, it puts it between those two fields.  Check out the Drupal Form API and #weight for more information on what this is all about.

If you click show row weights at admin/config/people/accounts/fields you can see this more directly:

ADDITION:  Using Field Groups

If you had it set up like this:

...and wanted to put the signature settings inside the "My Group" field group, you could do something like this:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      $form['#fieldgroups']['group_my_group']->children[]='signature_settings';
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

...which would produce this:

YET MORE ADDITIONS:  Tab Groups

If you want to put it in a tab group, eg:

...this will do it:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      // $form['#fieldgroups']['group_my_group']->children[]='signature_settings'; // apparently this isn't needed afterall
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

...which produces this:


Drupal_get_title() but for another field by name? If I use drupal_get_title() I can print the title of the page to the page body. Custom content types that I'm using have many fields like subtitle, url redirects, etc. How would I go about printing those to the page body just like drupal_get_title() allows me to do for the page title?

I've reviewed the forum for other solutions. field_get_items() and $content['field_name'] aren't working for me. I think what I want to do is simple but most of the examples pertain to database manipulation.

Maybe print $content['field_MACHINE_NAME']['und'][0][taxonomy_term]->name;? That should print the field without the HTML

If you want the HTML, trying using print render($content['field_review_nationality'][0]);

Source


Multiple pagination of arbitrary array of objects I have an array with this structure:

$things = array('term1' => array(Object, Object, ... Object),
                'term2' => array(Object, Object, ... Object),
                'term3' => array(Object, Object, ... Object),
                 .... etc...

I want to be able to generate output like:

Term1

* Object 1
* Object 2
* ... etc ...

 < 1, 2, 3 > (<-- that's pagination :D)

Term2

* Object 1
* Object 2
* ... etc ...

 < 1, 2, 3 >

Which each list of things paginated (assuming there are more than x of them).

Is there a way I can achieve this?

A template function I can pass each of the individual arrays of Objects into to get pagination?

If it matters, this is all taking place inside a block, in D7.

See Drupal Pagination with a Custom Query for full code example


Entity API and Contrib Modules When using the Entity API, is it fairly simple to interact with Taxonomy, Path/Pathauto, XML Sitemap, and Views? If so, what parts of the API should I be looking at?

In response to the original question and to electblake's answer, I would second the fact that the Entity API contributed module is separate and distinct from the core entity system. It is meant to augment the core system by providing a more robust entity controller (the piece of code used to create, load, save, and delete entities), provide some automatic token generation, and allow modules to define metadata for their entities' properties.

electblake mentioned that the core entity system includes a class for querying entities in the database based on their property and field data called EntityFieldQuery. This is in fact the recommended way for making entity queries. The Entity API isn't actually meant to be a querying tool. However, it provides in my opinion the other missing piece for building robust contributed modules using entities and fields - the entity metadata wrapper.

As I mentioned, the Entity API module provides a hook that lets you define metadata for your entity's properties (i.e. $node->uid, $node->created). It combines this information with what it knows about field definitions and instances. It then lets you "wrap" an entity to make it easier to access and manipulate field data and (what I'll call) referenced entity data through the wrapper object. One of the main things this has made easier for me is not having to worry about the language of entities when I'm trying to access their field data. Without the wrapper, you need to know the schema array of the data you're trying to access or manipulate. Using it, you can simply access field data like any other property.

Additionally, it makes it easy to access the data of referenced entities. In Drupal Commerce, I make extensive use of this functionality since a couple of our entities serve primarily as containers of references to other entities. An example approaching the usefulness you mention in your original post would be to have quick access to all the taxonomy terms referenced by a node. A simple way to do this with the wrapper would be to wrap the node and then loop over your taxonomy reference field's data to access the fully loaded term data. It's hard to demonstrate this without including extensive code snippets, but you can easily see how I put this to work by grepping the Drupal Commerce source for entity_metadata_wrapper.

The jury's still out on how useful or widespread the Entity API will be, but as it's a dependency of Rules 2, I doubt it's going anywhere soon. This may be a little too much information based on your response to electblake, but my hunch is the information should be useful for additional people who find this question when searching for more information on the Entity API. : )


How to prevent result from being displayed when user selects search/apply I created a "view" on my site with 3 exposed filters (One for "name", the other for "occupation" and the last for "location") to allow users search/filter for other users on my site.

On page load, no results are displayed. However, if I simply select search/apply (without inputting any search string), it displays results.

Please, how can i resolve this?

Thanks.

If you go to advanced settings of the view, you can set the exposed form settings to input required.

Another option if you are making use of the Better Exposed Filters, there's a patch for it which adds 'input required' option/functionality,


What would cause this error when upgrading Panels module? $ drush up panels
Code updates will be made to the following projects: Panels [panels-7.x-3.4]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project panels was updated successfully. Installed version is now 7.x-3.4.
Backups were saved into the directory /home/bzisad0/drush-backups/newco/20140724235906/modules/panels.       [ok]
WD php: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't [error]
exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of
/var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;newco.cache_panels&#039; doesn&#039;t exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of /var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
Drush command terminated abnormally due to an unrecoverable error.                                           [error]
Backups were restored successfully.                                                                          [ok]

The only clue I have is that the company I'm doing work for underwent a merger, and we had to set up the new web site before the name of the new company was public, so everything went by "newco".  I could not find anywhere that this is configured in Drupal, but I see that showing up in the error message "Base table or view not found: 'newco.cache_panels' doesn't exist".

I'm not sure if that's relevant or not, but I'm mentioning it just in case, and hoping it's not a red herring.

For some reason, the "cache_panels" table of panel used for cache is missing.

It's reported as an issue for this module.

To solve this error, first, I strongly recommend to do a backup of the database before make any change (even before do a drush updb or update a specific module as you are trying in this case).

You cloud try one of the following solutions:

Using drush, follow this proposed solution.
Using a SQL query, follow this other solution.

I recommend you to use the first alternative as I see that you use drush.


How to exclude a custom 404 error page (not found) from a Popular Content block? Is there a way to stop a custom 404 page from being added to the Popular Content block?

I set up a node for the custom 404 page. But every time a missing page gets redirected there, it increases the number of page hits of that node (of course). Which increases its ranking in Popular Content blocks also.

Is there some configuration setting to exclude it from Popular Content blocks, or place it in a different category?

Option 1: Use the CustomError module

The CustomError module allows a site administrator to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them. Some more details about its features (from its project page):

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

What you should be most interested in, is this part from that project page:

  Since the error pages are not real nodes, they do not have a specific content type, and will not show up in node listings, or in a Popular Content block.

Option 2: Tune the View that creates the block

Edit the View that actually creates the Popular Content Block like so:

Use the "Add" link to add an extra condition within "Filter Criteria".
The extra condition could be either of these:

"Content: nid", using "Is not equal to" as operator, and with "value" the node id for your 404 page.
"Content type" is different from "Content type ABC", whereras you first created such Content type ABC to create pages such as the custom 404 page (which automatically also covers other similar pages you want to always be excluded also).

Bonus: Also for 403 variations

Either option above can be used in case of a similar question related to 403 errors (Forbidden, or "Access Denied").


Links in sidebar to link to search results I have a view in sidebar showing a taxonomy Category. There is a view on /search-page that displays search using Search API view and exposed filters. I want the sidebar Categories to link to the search page with filtered category (/search-page?filter_category[]=13)

What would be a proper way of doing this?

I tried to do rewrite on the Name field in sidebar view.

"Rewrite the output of this field"
rewrite Text to [name]
checked the "Output this field as a link"
set Link Path to search-page?field_[machine_name]%5B%5D=[tid]
the links in sidebar get double escaped (it's a bug https://www.drupal.org/node/1342124)

In addition to the bug, I don't particularly like this way, because the path is hardcoded.

Is there a way to kind of link to the search view with some params instead so that Drupal handles the URL internally?

Actually it seems like the double escaping did work OK after all. A rewrote the URL to search-page?field_[machine_name][]=[tid] and it worked :)


Drupal Services node filtering Is there a way to filter the nodes that come from a SERVICES node Endpoint, by a field or status?

http://test/api/node?parameters[nid]=1&parameters[status]=1&fields=status,bid,title

As always you can look at the tests.

Below you can see whats possible.


Best way to create mobile menu? I have a template that I am trying to convert into a custom theme and it contains a mobile menu that is a duplicate of the main menu.

What is the best way to tackle this with the least amount of duplication?

I tried to create a menu--main.html.twig file and repeated 2 menus in one file.  It looked liked it worked at first until my menu contains submenus and then some weird behavior where it nested both menus into the below menu.  I would like to avoid creating a separate mobile menu in the admin dashboard and manually adding new links if created, but if that is the best way then I can handle it.  Just looking for other opinions.

Thanks

Are you familiar with Boostrap or Zurb Foundation framework? I suggest you research either of these 2 frameworks and you will find that you can accomplish your goal using either one.

Here is a little background. Basically they are just a javascript file and css file. The javascript file has code for a ton of common/widely used features and built to be mobile responsive.
All you have to do is assign your divs a specific class name and they will get a certain functionality. You can find the class names that you need to use on their documentation page.

In Drupal, you can use the Boostrap theme or Zurb Foundation theme to build on top off. These themes have done some of the work for you. Ex: assign all the buttons the proper button classes using a preprocess function.

Here are specific tutorials regarding your question:

Bootstrap 3 Tutorials - #2 - Responsive Collapsing Navbar

Zurb Foundation | Top-Bar Tutorial


What is the parent name for the admin menu? what is the parent name for the admin menu ?  if I put system.admin_structure in the mymodule.links.menu.yml file as below, it places the new menu item under the structure tab on the menu.  How do I get it on the first level of the menu.?
mymodule.demo:

title: Demo Link
  description: 'This is a demo link'
  parent: system.admin_structure
  url: 'internal:/taxonomy/term/3'
  //route_name: entity.taxonomy_vocabulary.overview_form
  menu_name: admin
  weight: -79

parent:system.admin is the answer , obvious wasn't it.


Proper directory layout for tests I'm coming across what seems to be contradictory information, and I'm hoping someone here can clarify.  The basic question is "what is the correct folder structure for PSR-4 style auto-discovery of classes in Drupal 8, particularly test classes, and how much flexibility is there in that structure?"  (I apologize in advance about this, but I'm going to have to partially break up my question into comments, since I don't have enough reputation yet to post all the necessary links.)

I have run across the following conventions I'm about to list in subsequent comments.  I'm hoping someone can clarify what the proper layout is.  Or will all work?  I could spin up a D8 instance and test this, but I'm afraid such a cursory examination would conceal pitfalls of one approach versus the other, in terms of community support.

There are three different testing frameworks in Drupal 8.

1. Simpletest: Functional, Upgrade and Unit Tests

These should be located underneath src\Tests per the documentation linked in the Question comments. This corresponds to the namespace Drupal\my_module\Tests.

This is documented best at https://www.drupal.org/node/2166895.

2. PHPUnit: Unit Tests

Theoretically these could be anywhere with a phpunit.xml.dist file, but if you need to support running through Drupal's test runner (run-tests.sh) or drupal.org infrastructure then these must be placed in tests\src\Unit and the namespace corresponds to Drupal\Tests\my_module\Unit

3. Behat: Behavioral Tests

I think there is a movement to store behavioral tests in a directory parallel to tests\src\unit, but no official convention as Drupal core does not utilize Behat yet.


math operators for text fields in views filters I have a field of type text that contains a number like 10. I want to create a search form with views exposed filters. Since the field is a text, I can't use greater than and less than operators on the field. Is there any way to have such operators for a text field?

You'll want to create a different field of type "number" for that.

You might be able to do something like creating using Computed Field to create a new field that takes the value of your original field and changes it to an integer with  $num = (int)$str;


Limit the comments view to node author Is it possible to add a visibility restriction to article comments? (For instance, only the poster can view comments.)

A way by which you can elegantly do this from a custom module would be:

/**
 * Implements hook_node_view_alter().
 */
 function my_mod_node_view_alter(&$build) {
   $node = $build['#node'];
   if (isset($build['comments'])) {
     // It is good practice to allow the administrator to see comments of all nodes.
     $build['comments']['#access'] =
       user_access('administer comments') || ($node->uid == $GLOBALS['user']->uid);
   }
 }


Trigger Drupal Rule Based on Taxonomy Term I have a rule built that sends an email to users of a specific role, when new, published content is created. What I want to do is be able to send this email only when the content matches a specific taxonomy term. Unfortunately, I'm struggling with this -- any help would be much appreciated!

When you say the content "matches" the term, do you mean the content has a field to select that term, and you want the email to send when the content has been tagged with that term?

If thats the case...

Create a new condition "Entity Has Field"
Choose the taxonomy field.
Create a new condition "if taxonomy field == taxonomy name"
Create action to send mail to user of a role.


How to deny certain terms from being allowed in autocomplete field? I'm looking for a way to restrict my users from creating certain terms that do not belong in that particular field.
I want them to be able to add terms on the fly, but I also want to deny certain terms from being used.

Some examples of this could be swear words, or more specifically in my case abbreviated words.
(MN, WI, MI - I want to force them to use - Minnesota, Wisconsin, Michigan)

You should be able to create a custom module that uses taxonomy_autocomplete_validate to validate the input on node_presave and/or node_save. You would just need to define a list of banned terms, either directly in the module, or from an included file that could be more easily maintained.

You could always go one step further and build an administrative interface within the module, but that's probably veering too far away from your question.


Node title get deleted when saving a translation of the node Not sure if this is issue of the Title module which I have enabled, or just a bad configuration.

To reproduce:

1- Create a content type: My content and checked Enabled, with translation

2- Create a english node with title: My english node title. Save

3- Create a translation for that node to french with title:  My french node title. Save

4- Now(after I saved the french node) if I go to edit the english node the title field is empty

It happens in the other way too. If I edit and save the english node and then I go to edit the french node the title field is empty

How can I trace this? It seems a bug to me, but not sure.

Do you want to manage your content type translation at node level or field level ? You can have a mix of both on the same site if needed, for different content types, but don't mix up within a content type.

If you choose "basic" node translation for content type A, you won't need the Title module, so if it's enabled/in use for content type B, just don't "replace" (admin/structure/types/manage/content_type_A/fields/replace/title) the built in node title of A by a field.

Then when you translate a node from node/xxx/translate then node/add/content_type_A?translation=xxx&target=lang , everything should be ok.

Read also Gábor Hojtsy explanations which are still valuable about translation settings, or Randy Fay Field translation: First steps


IMCE module: list only image files I have a Drupal 7 with the IMCE module installed.
It works good but it shows me every files in my media directory.
I need to limit the listing to only image files, for example to only jpg, png and svg file.

Anybody know a way to do it?
Thanks a lot.

You can restrict by placing file extensions which you want to display in the permitted file extensions field. It will appear in the configuration of IMCE profiles. See below image for your reference.


Cron has been running for more than an hour and is most likely stuck I am using poorman Cron Run and it is giving error like this: "Cron has been running for more than an hour and is most likely stuck." plz help if any solution for it??

It seems that cron is locked, hence the semaphore variable needs to be deleted before running cron again. In your includes/common.inc file, on line 2755 you need to delete the variable from drupal_cron_run(). You can use the following code:

function drupal_cron_run() {
  //The following line will delete the semaphore variable.
  variable_del('cron_semaphore');
  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
}

Then visit http://yoursite/cron.php and check the logs for errors.
Note: You should comment out the line variable_del('cron_semaphore');, after cron runs successfully.
I know it is not recommended to hack the core, but this was the only solution I found useful. If there is any work-around to this solution, please let me know.


How to add css to a form according to the user's role? I know how to add css to individual form types using:

function theme_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'formtype_form':
      global $theme;
      $form['#attached']['css'] = array(
        drupal_get_path('theme', 'projectname') . '/css/new.css',
      );
    break;
 }
}

but how can I restrict this attached css to users with a single role?

You need to call $user object and compare user role with current logged in user.

function theme_form_alter(&$form, &$form_state, $form_id) {
  global $user, $theme;

  switch ($form_id) {
    case 'formtype_form':
      // change user_role to whatever role you want to restrict this css
      if (in_array('user_role', array_values($user->roles))) {
        $form['#attached']['css'] = array(
          drupal_get_path('theme', 'projectname') . '/css/new.css',
        );
      }
      break;
  }
}


I18n translation of site_name not working I have installed i18n, changed settings.php according to this guide, set language detection to url and cleared cache.

Then on site config page, I set the url prefix to English and all UI changed to English. Then I updated the Site Name to something English.

Then I repeated the above steps for a local language.

But it looks like changing the url path prefix each time gives me identical results regarding Site Name, i.e. the Site Name is changing each time I update it, no matter which language path is chosen.

What am I doing wrong?

P.S. In table "variable" the site_name is just one. I never used i18n before, no idea how it should look here.

To translate a Drupal 7 Site name you have to activate Variable translation module (which is in the same package as i18n) and the required ones (like Variable store).

After you install these modules, go to Configuration -> Multilingual settings -> Variables tab and choose Site name (?q=admin/config/regional/i18n/variable),Then go to Configuration -> System -> Site information (q=admin/config/system/site-information) and select the language you want. Change the Site name field and save.

You'll find the translated site name in variable_store table.


Taxonomy inline with several category types? Is it possible for D7 to display several taxonomy fields inline with some separator between them? I want to have a node with 2 category types, say, a song with a Year and a Singer. Now the taxonomy displays in a column:

Year: 1999
Singer: Britney Spears

And I want it to appear inline with some separator:

Year: 1999 |separator| Singer: Britney Spears

I've found a similar question but it deals with displaying one multivalued taxonomy field. That's not quite what I want. So where should I look and what I should override to display several types of taxonomy fields inline?

Update: after spending 2 days on that I've done it using node.tpl.php and field.tpl.php. It's always better to print your separators outright. Relying on CSS is good but not when there are guys using IE6 out there (I've seen one as late as 2011). Not that I did the best solution ever here (I'm lousy with the code) but still it works and at least does what I want it to do. I did the following:

1) copied node.tpl.php from modules\node to sites\all\themes\mytheme.
2) used $content variable to find all taxonomy fields:

$taxonomy_field_names = array();
$all_field_names = array_keys($content);
foreach($all_field_names as $i => $value)
{
    $field_name = $all_field_names[$i];
    $field_type_name = '#field_type';

    //if content contains an array with $field_name and it is an array itself
    //and has an item #field_type of taxonomy_term_reference
    //it is a taxonomy field
    if(is_array($content[$field_name]) &&
        array_key_exists($field_type_name, $content[$field_name]) &&
        $content[$field_name][$field_type_name] == 'taxonomy_term_reference')
    {
        $taxonomy_field_names[] = $all_field_names[$i];
    }
} unset($i);

3) hid them to prevent rendering:

//hiding taxonomy fields
$count_taxonomy_fields = count($taxonomy_field_names);
for($i = 0; $i < $count_taxonomy_fields; $i++)
{
    hide($content[$taxonomy_field_names[$i]]);
}

4) after rendering $content I rendered taxonomy fields:

//rendering taxonomy fields
for($i = 0; $i < $count_taxonomy_fields; $i++)
{
    //printing a separator after each of the fields except the very last
    if($i < $count_taxonomy_fields - 1)
    {
        $content[$taxonomy_field_names[$i]]['#separator'] = '&bull;';
    }
    print render($content[$taxonomy_field_names[$i]]);
}

5) copied field.tpl.php from modules\field to sites\all\themes\mytheme and renamed it field--taxonomy-term-reference.tpl.php (affects all ). After setting $content[$taxonomy_field_names[$i]]['#separator'] at the previous step one can use it as $element['#separator'] in field--taxonomy-term-reference.tpl.php:

<?php if (isset($element['#separator'])): ?>
<?php print $element['#separator']?>
<?php endif; ?>

6) added the following lines to sites\all\themes\mytheme\css\fields.css:

.field-type-taxonomy-term-reference .field-item {
   float:left;
}

To people who answered my question I offer my sincere thanks.

Option 1: Pure CSS. Assuming that you have your Content type's display options are set so that all the taxonomy reference fields are next to each other, you would simply display each of the divs that wrap each taxonomy field as an inline element, then use the + selector and :before pseudo-element to add your separator between each field.

These two special selectors are supported in most web browsers, but you might want to check whether they can be used in older browsers your site may need to support.

For example, if each taxonomy field is wrapped with a div having the class "field-type-taxonomy-reference" and your nodes have a div with the class "node-type" wrapping them, your CSS would look something like this:

//make the taxonomy fields and their contents display as inline elements
.node-type .field-taxonomy-reference,
.node-type .field-taxonomy-reference * {
  display: inline;
}

//add a pipe separator between two taxonomy fields
.node-type .field-taxonomy-reference + .field-taxonomy-reference:before {
  display: inline;
  content: " | ";
}

Option 2: edit the HTML with a custom field template. Copy the field.tpl.php file from Drupal core into your theme and rename it field--taxonomy-reference.tpl.php. This would affect all taxonomy reference fields across your entire site, which may not be desirable. You can also implement  template_preprocess_field() in your theme's template.php to add a new template suggestion for only the nodes (and fields) that you want to have affected by this template.  For example:

function YOURTHEME_preprocess_field(&$vars) {
  $variables['theme_hook_suggestions'] = array('field__' . $element['#field_type'] . '__' . $element['#bundle']);
}

This would allow you to use a field template named field--taxonomy-reference--news-article.tpl.php to affect all taxonomy reference fields on a node type named "new article". One the documentation page for template_preprocess_field() you can see a few other variables that are available for you to check (such as field name). You could make multiple fields with different names (and types) across multple node types use the same field template like this:

function YOURTHEME_preprocess_field(&$vars) {
  $field_names = array('field_name_a', 'field_name_b', 'field_name_c');

  if(in_array($element['#field_name'], $field_names) {
    $variables['theme_hook_suggestions'] = array('field__inline-style');
  }
}

This would allow you to use one template named "field--inline-style.tpl.php" for the fields named "field_name_a", "field_name_b", etc.


Page where I can see my user's managed files Is there a page in Drupal that lists all of the files in file_managed that the logged in user owns?

I do not think there is a pre-made page for this, but you can make one using Views.  Create a new view of type Files.  Under the Advanced section, add a Relationship for the user who uploaded the file.  Then add a filter "User: current" using this relationship.


Repository-based site deployment -- what to do about sites/default/files? I'm trying to get more rigorous about my process for deploying Drupal sites across development and production servers.  In particular, I'm experimenting with pulling the site from my SVN repository into a directory on the server and flipping a symlink to point the server to the updated site.  This makes sense to me, but I'm not sure how to handle the sites/default/files folder -- it's not in the repository created by the development process since those files are produced by the production users, and the directories inside this folder have different permissions than the default 0755 that I'm getting from doing the export.

So, what to do here?  My current guess is that sites/default/files should be physically moved out of the site directory and then symlinked back in, but wanted to check with others with more experience in this.  A related question is whether there are other files or directories in a Drupal installation that would need to have their permissions updated after an svn-based installation like this.  sites/default/settings.php comes to mind, for instance.  Anyway, is there any advice out there?  Thanks!

Ahh the age old question of how to properly deploy Drupal from dev->test->live. If you search around you will find many opinions and answers. There is no one answer and no singular method. The symlink solution is good one and is safe and simple. Another solution would be to use SVN to sync directly back to the same site/directory(s). You could mark certain files so that they are not pushed. If a mistake is made, you just revert. One other file I can think of that you may not want to overwrite is .htaccess. Other than that, settings.php and your files directory are about all that would need to be excluded.


Using Services, request new password Tell me, how do I enter, via the module Services has, if I have "pass_reset_token" and then change the user password? How to password recovery. Tell me please! I'm desperate =(

Services user update function internally calls Drupal's user_account_form function (via user_profile_form).  In user_account_form, it's specifically looking for pass-reset-token as a $_GET parameter, so to update password via Service, unfortunately you have to pass it as a GET parameter on a PUT call.

Example:

PUT https://drupal/:api-endpoint:/user/:uid:?pass-reset-token=:pass_reset_token:
and the body is {"pass":":new-password"}.

If you wanted to be able to pass "pass_reset_token" as a parameter in the body, you could override _user_resource_update so that it checks if the pass_reset_token parameter is present and puts it into $_GET['pass-reset-token'] prior to calling user_profile_form.


In search result page, pagination is not showing up I have migrated a site from Drupal 6 to Drupal 7. Search form I have rendered in page.tpl.php like this

<?php
     $block = module_invoke('search','block_view','form');
     print render($block['content']);
?>

I am able to search, but pagination is missing in the search result page.

In the theme folder I have search-results.tpl.php and search-results.tpl.php.

In the search-results.tpl.php <?php print $pager; ?>  is available.

If I change theme to default theme or core theme pagination is working fine.

What is the issue over here which is causing not showing pagination links?

i don't think that this will help you but do it like this:

// template.php
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

page.tpl.php:

<?php print $search_box; ?>

according to this discussion. You should not put your logic into tpl.


Add a term under a vocabulary when a content of particulr type is added I have a vocab like 'category'. I want to add terms under this dynamically i.e when a content of type 'category_list' is added a term with this content title should be added under the 'category' vocab. Can this be done?

In short, "yes".

Using hook_node_insert() where you can assign a category term value programmatically. Note that this is an over-ride (hook) of the node creation process. Basically do a Googe search for Drupal 7 node creation programmatically", example: Guide to programmatic node creation in Drupal 7. Look for the details on "Term reference (taxonomy) field".

Note that this an advanced Drupal task that involves creating a custom module that's specific to your site. If you're not already familiar with this process of applying hook functions to alter default Drupal functionality then I suggest you do some research on basic Drupal requirements for custom module creation first.

Good luck and keep asking questions, you'll figure it out and might become a Drupal rock star in the process!


How to bulk delete empty taxonomy terms? The website has thousands of unused (empty) taxonomy terms and I want to bulk delete them.

With views all empty terms can be listed but it's not possible to delete them via Views (VBO etc).

I saw that taxonomy terms should be cleaned with taxonomy_term_delete() in this question: How to delete true orphaned taxonomy terms. But I don't know where to use it? Should I create a block and put the code inside it or a custom module or anything else?

(I also tried the Delete Orphaned Terms module but couldn't be sure if it's working properly. I tried it on a dev. site but couldn't check the results.)

A quick solution:

Go to your folder theme and edit the node.tpl.php and put this code at the top of the file:

<?php

$query = "
SELECT taxonomy_term_data.tid AS tid
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
GROUP BY tid
HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'
";

$tids = db_query($query)->fetchCol();

foreach ($tids as $tid) {
  taxonomy_term_delete($tid);
}
dpm($tids);
?>

Then go to visit one of your nodes and the code will be triggered.

Take into account that if you don't eliminate the code from the node.tlp.php then every time that you access a node the code will be triggered.

EDIT: I (quickly) created a little module for you. Is not the best solution but I tested it and it works.

file: delete_unused_taxonomy_terms.info

name = Delete Unused Taxonomy Terms
description = Delete all unused taxonomy terms
core = 7.x
package = Administration

configure = admin/structure/delete_unused_taxonomy_terms

files[] = delete_unused_taxonomy_terms.module
files[] = delete_unused_taxonomy_terms.admin.inc

file: delete_unused_taxonomy_terms.module

<?php

/**
 * @file delete_unused_taxonomy_terms.module
 */

/**
* Implements hook_menu().
*/
function delete_unused_taxonomy_terms_menu() {
  $items['admin/structure/delete_unused_taxonomy_terms'] = array(
  'title' => 'Delete Unused Taxonomy Terms',
  'description' => 'Delete Unused Taxonomy Terms',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('delete_unused_taxonomy_terms_admin_settings'),
  'access callback' => 'user_access',
  'access arguments' => array('administer taxonomy'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'delete_unused_taxonomy_terms.admin.inc',
  );
  return $items;
}

File: delete_unused_taxonomy_terms.admin.inc

<?php
/**
* @file
* Calls results to administration's pages.
*/

/**
* Form constructor for module configuration.
*
*/
function delete_unused_taxonomy_terms_admin_settings($form_state) {
  $form['#submit'][] = 'custom_form_submit';
  return system_settings_form($form);
}

/**
 * Submit handler
 */
function custom_form_submit($form, &$form_state) {
  $query = "
  SELECT taxonomy_term_data.tid AS tid
  FROM
  {taxonomy_term_data} taxonomy_term_data
  LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
  LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
  LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
  GROUP BY tid
  HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'";

  $tids = db_query($query)->fetchCol();

  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }
}

In your module folder make a folder named delete_unused_taxonomy_terms put the 3 files inside and install the module.

Then go to admin/structure/delete_unused_taxonomy_terms and click the button.

Reference:

How to delete true orphaned taxonomy terms
Create a Views that displays all unused taxonomy terms


How can I remove the header n the node/add/[content_type] pages I have a content type 'Numbers' and on the node/add/numbers page there is a header that says 'Create Numbers.'

I would like to remove this header from the page. I've searched in node.tpl.php with no success. I'm thinking that this is a job for a HOOK_form_alter() but I'm not sure what needs to be altered in the form.

This may not be a good solution but it works. Put the below code in template.php preprocess_page in your admin theme.

if(arg(0) == 'admin' && arg(1) == 'numbers') {
      $vars['title'] = "";
}

Where number is the node type.


How to add a reference to a view block in a field? I am using Drupal 8. I created a block (hotel) with the Views module, and I would like to add a reference to the block in content type's field, but only custom blocks can be added. The hotel block cannot be added to a new field because it was created with the Views module.

How can I add a reference to a views block to a field? Alternatively, how can I convert a views block in a custom block?

Both Views and Entity Reference are now part of the Drupal 8 core.

Go to
1) structure >views and create a view of type page or block. In another   display select entity reference as display.
2) In format settings select the search fields for this view and select the fields you wish your view should display. Now save the view.
3) Go to structure > content types> Content type to which you want to add the reference field. Create and new field of type content, set the label you wish to and save and continue.
4) In type of item to reference select, "view". Save field settings.
5) In field settings, under reference type, select "Views: filter by an entity reference view". Under "View used to select the entities ", select your entity reference view and save.
6) In manage display of content type for this reference field you can select Link to entity or rendered entity. I had selected rendered entity and save the manage display settings.
7) Now create a content of your content type and in the entity reference field give the name of entity to which you want to refer to.


Can I avoid creating a new revision of every attached field upon entity save? I have created a custom entity with several properties and several attached fields.

When I load a instance of my custom entity, update a property of the entity (e.g UID) and save it a new revision of the entity is created, but also a new revision of every attached field is created.

To avoid saving lots of redundant data I only really want to create a new revision of an attached field if the data in that field has changed.

I've noticed that this same behavior is exhibited by core node objects, but is still not really desirable.

My function which currently saves my entity looks like this:

/**
* Saves a emtr safe check to the database.
*
* @param $emtr_safe_check
*   The emtr_safe_check object.
*/
function emtr_safe_check_save(EMTRSafeCheck $emtr_safe_check) {

    $is_new = isset($emtr_safe_check->is_new) ? $emtr_safe_check->is_new : false;

    // always make a new revision
    $emtr_safe_check->is_new_revision = TRUE;
    $emtr_safe_check->save();

    if($is_new) {
        // now we have the new emtr safe check id lets save the attached fields
        field_attach_insert('emtr_safe_check', $emtr_safe_check);
    } else {
        // This is where my attached fields are saved
        // Can I do something clever here to avoid creating redundant revisions?
        field_attach_update('emtr_safe_check', $emtr_safe_check);
    }

    return $emtr_safe_check;
}

I have looked around and found one HACKY solution. I think it probably has some serious side effects that you may be able to handle with custom code and db queries. This is definitely not a generic solution.
I did my test on the node entity and every thing worked fine in my 5 min test case. Here is what I did:

function playground_node_presave($node){
  dpm($node);
  // do a query here and check if the value is in the field_revision_table is
  // equal to the value on the node/entity object.
  unset($node->field_cookies);
  dpm($node);
  // The node will be saved without changing the value of the field and without creating
  // creating a new entry in the field_revision_table.
}


Is this a reasonable use of hook_user_presave? The documentation for hook_user_presave says that

  This hook is primarily intended for modules that want to store properties in the serialized {users}.data column [...]

Instead, I'm using it to check that a change of email address does not clash with any email address in a database separate from the database for my drupal site. If it does, I do

$edit['mail'] = $account->mail;

so that the update to mail does not go through, but the rest of the edit is unaffected. (I also put up a warning message, under the assumption that the only time the email changes is when someone changes it manually.)

With anything web-related being outside my usual field, I'm not sure if using this method in a different way than intended is too clumsy or unsafe. Is it ok to use this method in this way?

If you look at the documentation page for Drupal 8, you will notice that sentence is not used anymore.

  Act on a user account being inserted or updated.

  This hook is invoked before the user account is saved to the database.

  Modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, may add their properties to $account->data in order to have their data serialized on save.

The fact the hook has different parameters in Drupal 8 doesn't change its purpose. In fact, with Drupal 8 you could use the following code.

$account->mail = $account->original->mail;

$account->original contains the value returned from entity_load_unchanged().

Although on Drupal hook_user_presave() is normally used for the purpose you noticed, you could use it for the purpose you described.

The alternative would be to add a form submission handler to the user edit form which is executed before the default form submission handler. The pro of using hook_user_presave() is that it works also when a module programmatically save a user object using user_save().


Limit address field postcode and city I need to limit the commerce_customer_address field to 10 cities. You should be able to choose a city from a select list and this should then set the correct postcode. It also needs to be ajaxified so that the postcode updates dynamically. Possible? How?

The commerce_customer_address is an Address field. You can add your behavior by implementing a custom format plugin, like the one in the addressfield_example submodule.


How to facilitate meetings / events with participant registration, agenda and documents? How to manage meetings in Drupal? I would like to do the following:

Participants can register for an event or be added by the admin.
The meeting has an agenda, consisting of a number of agenda points.
Documents can be attached to the various agenda points.
Participant details, the agenda and documents are shown.
Record that the meeting is one in a series of meetings of the same group.

An example of what is needed is here, but the site is Joomla and it seems to be a custom module.

There are many options in Drupal allowing you to add registrations to content. So if you add a content type of 'meeting', you can add file fields, dates and an agenda text field. Add a taxonomy field for grouping by type.

Then with any of the registration modules you can register users.

Entity Registration
Node registration
RNG (Drupal 8)

Basically it is not one module, but a combination of fields and modules to get the desired functionality.


Unable to upload file from $_FILES array in drupal7 I am trying to upload file from $_FILES array. but getting following error in drupal7.

The specified file temporary://fileOYnPHK could not be copied, because the destination directory is not properly configured.
This may be caused by a problem with file or directory permissions. More information is available in the system log.

The sites/default/files has permissions 777

Here is my code

if($_FILES['files']['name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']){
    $file_path = file_save_data(file_get_contents($_FILES['files']['tmp_name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']),
    'public://sites/default/files/'.$_FILES['files']['name']['field_tenant_review_ref_und_form_field_tenancy_document_und_0']);
   }
   //$tenant_review->field_tenancy_document->file->set($file_path);

Is there any mistake in code? Please suggest.

The problem is not with your Public file system path but with your Temporary directory; normally it is /tmp if you're in a Mac or Linux server.

You can check that the Temporary Directory is well configured, maybe it is pointing to a non-existing path.

To check the configuration in Drupal 7 you must go to Configuration > Media > File system.


How do I make a page-specific .tpl? I have a global module that has several .tpl files.

I would like to alter these files, but only have the alterations appear on one particular page (or Node Template).

I know I can duplicate the existing .tpl files and place them in my theme directory to overwrite the global .tpl files, but how would I go about creating .tpl files that only get picked up when a particular page is viewed?

Eg, something like:

/sites/mysite.com/themes/custom/mytheme/templates/gallery.tpl

and then, for the 'About us' page:

/sites/mysite.com/themes/custom/mytheme/templates/about-us-page-gallery.tpl

With theme hook suggestions:

function MYMODULE_preprocess_page(&$vars) {
  if (some_contextual_condition()) {
    $vars['theme_hook_suggestions'][] = 'page__about_us_gallery';
  }
}

The above will correspond to a template file in your theme named page--about-us-gallery.tpl.php


How do I build a relation of users having a specific role, automatically? I have installed the Relation module. I need that users with the "test" role are related with all users having the "student" role, automatically.

How can I build this relation?

With the Rules module, you could take action on a "user created with role student" event.


How to filter on taxonomy term in a view? I've got a view where I would like to filter content based on a taxonomy term. I've created the taxonomy, added some terms, created a field reference on the specific content type I'd like to show, then added some terms to content.

The issue I have is this: In the view, under add new filter, the taxonomy I created doesn't show up as an option to filter by. There's a bunch of "indexed node: xxx" available, but none of them refers to the taxonomy I created. I suppose there is an option somewhere to have the taxonomy terms indexed? How do I do this?

This might seem like a very straightforward question, but for some reason on this particular website, I can't find the culprit.

You need to create a relationship to your taxonomy vocabulary. Think of this like adding a join to a mySQL query.

For more info, take a look at Views relationship using taxonomy


How can we manually enter a payment using their credit card information for a customer in Commerce? We have customers that are not web savvy and would like us to enter their order for them on the website.
Currently, the admin masquerades as the user, creates the order as them, checks out as them, and then enters their credit card info. Then un-masquerades.
Is there an easier way to do this? We've tried Creating an Order in the backend but the Payments tab says the following for all Credit Card payment methods.
"There are no reusable payment methods available for the selected gateway."

We were hoping it would be as easy as manually creating the order and then enter the payment for Commerce does not seem to allow enter CC info on the backend.
We're using Authorize.net

Create the order in the admin UI and add the user as the first step of creating the order.
Save the order.
Go to People and then edit the user you just created.  Add payment info.
Then add shipping info in the orders > shipments tab (if you have a shippable product).
Then go to Orders > Payments and you should be able to add the payment that you just added and make the charge (if cc).
Then edit the order and place the order.

Maybe there is an easier way to do this but so far these are the bizarre steps I am going through.


Should we use drupal_exit() after drupal_goto()? I think, drupal_goto() breaks the execution so next lines of code won't execute after drupal_goto(), Am I right? Somebody recommended me to use drupal_exit() on the next line of the drupal_goto().

Is it necessary? Will the code after drupal_goto() execute ?

Please guide me.

Will the code after drupal_goto() execute ?

No - the last line of drupal_goto() is:

drupal_exit($url);

So the script will already have terminated without returning, and no subsequent code will execute.

You can safely ignore that recommendation.


A responsive thumbnail grid in Drupal 7 node How to create a responsive thumbnail grid in Drupal node? I need simple thumbnail grid with description under the pictures, without expanding image. Something like this example. All thumbnail containers should have the same size, say 210px x 210px, but size of images can be diffferent. I installed a lot of modules, include Views, Chaos tool suite, Picture, Brilliant Gallery, but it mostly suitable for image galleries, not for simple thumbnail grid.

Is there method to create responsive picture grid without editing templates or altering core? (i.e. adding code directly in the body of 'Article' or 'Basic page' content, while text format is full HTML) I have read Views and Views Fluid Grid modules manual, but got no idea how to use them for this task, not even sure whether this will be suitable for this purpose.

When you get to this level of customization you need to start considering creating your own page/node templates.

If I was doing this,  my pages for this content would get their own content type,  then I would create a corresponding page template.

These links may be helpful:
https://www.drupal.org/node/982122
https://api.drupal.org/api/drupal/modules!system!page.tpl.php/7

Inside that page template, I would then load the raw data for the node, using node_load  and then access the fields directly and put them inside the appropriate markup.