# Question
Title: How do I assign variables from BlockBase object?
I want to create a Block-Module for drupal 8 (beta 12). To display the Content I want to use a twig-template (mytest-block.html.twig).

But the Twig-Template needs some Data to Display, So I need a Method to assign Some Variables from MytestBlock.php to the Template.

I know how to assign Variables from mytest.module, but I have no idea how to assign Variables from the Block-Plugin MytestBlock.php.

Or is it possible to access the instance of MytestBlock.php and therefore call a method which would return the variables as an array?

My MWE-Module consists of following files:

```
mytest/
├── mytest.info.yml
├── mytest.module
├── src
│   └── Plugin
│       └── Block
│           └── MytestBlock.php
└── templates
    └── mytest-block.html.twig

```

File Content mytest.info.yml:

```
name: mytest
description: A Testmodule
core: 8.x
package: Custom
version: 0.1
dependencies:
    - block
type: module

```

File Content mytest.module:

```
<?php

function mytest_theme() {
    return array('mytest_block' =>
        array('variables' => array('test' => 'hello')));
}

function template_preprocess_mytest_block(&$variables) {
    $variables["test2"] = "hello2";

    //a call to get_variables() would also be an option, e.g.:
    //$variables = array_merge($variables, $A_INSTANCE->get_variables());
}

```

File Content mytest-block.html.twig:

```
Template
{{ test }}
{{ test2 }}
{{ test3 }}
{{ test4 }}

```

File Content MytestBlock.php:

```
<?php

namespace Drupal\mytest\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Provides a Test-Block
 *
 * @Block(
 *   id = "MytestBlock",
 *   admin_label = @Translation("My Testblock"),
 * )
 */
class MytestBlock extends BlockBasMytestBlock.phpe implements BlockPluginInterface {
  public function build() {
    return array(
        '#theme' => 'mytest_block',
        /*here I want to assign some variables: e.g.:
         * test3 = hello3 */
    );
  }

  public function get_variables() {
    retrun array("test4" => "hello4");
  }
}

```

In this example, only test and test2 are assigned, but I want, that test3 and test4 are assigned too.

# Answer
> 1 votes
Via try and error, I found out, that declaring the variables-array in the function mytest\_theme() makes it possible, to set the variable in the MytestBlock-Class:

Changes in mytest.module:

```
function mytest_theme() {
    return array('mytest_block' =>
        array('variables' => array('test' => 'hello', 'test3' => null)));
}

```

Changes in MytestBlock.php:

```
class MytestBlock extends BlockBase implements BlockPluginInterface {
  public function build() {
    return array(
        '#theme' => 'mytest_block',
        '#test3' => 'hello3',
    );
  }
}

```

But I still have no idea how to access the Block-Plugin Instance in mytest.module.

---
Tags: theming, 8, blocks
---


title: GET request of more than one resource

text:
# Question
Title: GET request of more than one resource
I'm working with services 7.x-3.12, I need to create a web service in order to get a kind of "associative request" between : books(table stored in db) and categories(another table) those two tables are linked by entity\_id

I can GET books (retreive, index) same for categories, but how to get Book A -\> categorie A ? or the book list of category A

How can I make it work (the get service)? P.S. book is a content type (node), categories are taxonomy(taxonomy\_term)

# Answer
The short answer is, you can't. I have an issue posted to hopefully make this, and other filters, a reality soon.

In the mean time, you can however create a custom service resource that uses *POST*, and from there build a custom callback function to return your desired results.

Alternatively, you can use the Views JSON module (a sub module of Views datasource) or Services Views to easily create a View (with contextual filters, normal filters, sorts, etc) that returns **JSON** data to you via *GET*.
> 1 votes

---
Tags: services
---


# Question
Title: Views of Node Revision with Revision Update Date Expose filter
I have a Views of Node Revision with **Revision Update Date** Exposed.

Exposed form rendered as "textfield" widget by default, I want to have Date popup calendar instead.

# Answer
1. Download and Enable the module 'better\_exposed\_filters'
2. Refresh view, then change Exposed form style to use Better Exposed Filters (under advanced).
3. Under BEF settings, use 'jQuery UI Datepicker' widget.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How can I automatically visually number each webform component? e.g. 1) ... 2) ... 3)
I am building a webform and would like to number each question (webform component). What is the automated way to do this (rather than number the component label text)?

Webform 3 (but may move to Webform 4 later).

I've searched a bit for this, but get results about phone number fields :/

Thanks for your time.

**Update**

I have clarified the question to state that I want to visually number the components, the numbers themselves would not be related to the component id, rather, they would be for the benefit of the user. It would be used to number the questions e.g.:

1. Question
2. Question

etc.

# Answer
> 2 votes
You could use an entirely front-end solution with CSS counters: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters

I believe components are siblings of each other which would make this quite easy.

---
Tags: 7, webforms
---


title: Get only Taxonomy from $content array

text:
# Question
Title: Get only Taxonomy from $content array
I need to get the taxonomy from the `$content` array to print in the node template. How can I do it? I tried with $`content['taxonomy']`. Where can I get a guide with all params in `$content` array?

# Answer
> 0 votes
`$content` contains the renderable elements of your node (see documentation on node.tpl.php). This contains the node body, links, and other custom fields you've added to your node type. As Andrew suggested, the `drupal_render()` function can print individual fields or all fields (`render($content)`).

---
Tags: 7, nodes, theming, taxonomy-terms
---


title: Content type Images not displaying

text:
# Question
Title: Content type Images not displaying
I have created views to display images. Clicking on the image takes to content. View displays the image but when clicking on image it takes to content where image is not displaying. Please help me.

# Answer
> 2 votes
This is almost certainly a permissions issue. You need to ensure the web user (apache?) has access to these files. I typically just

```
chmod -R www-data:www-data sites/default/files

```

and it does the job.

---
Tags: views, entities, nodes, media
---


# Question
Title: How can i load a table on changing a select option using AHAH callback
I have drop down in a form as follows and i want to load a table of data using the drop down value , here is i have tried ,

```
function list_user_form(){
     $form['howmany'] = array(
    '#title' => t('List all the users in a group'),
    '#type' => 'select',
    '#options' => select_usergroup_dropdown_options(),
    '#default_value' => $default,
    '#ahah' => array(
      'path' => 'mailusers/listuserstable',
      'effect' => 'fade',
    ),

  );
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );
   return $form;
}

function listuserstable(){
//make html for the table and rendering it
}

```

But unfortunately it gives me `403 error` , please help

# Answer
> 0 votes
Try to add some wrapper to your table:

```
function list_user_form(){
   $form['howmany'] = array(
      '#title' => t('List all the users in a group'),
      '#type' => 'select',
      '#options' => select_usergroup_dropdown_options(),
      '#default_value' => $default,
      '#ahah' => array(
         'path' => 'mailusers/listuserstable',
         'effect' => 'fade',
         'wrapper' => 'mytable'
      )
   );

   $form['mytable'] = array(
      '#title' => t("Generated table"),
      '#prefix' => '<div id="mytable">',
      '#suffix' => '</div>',
      '#type' => 'fieldset',
      '#description' => t('This is where we get automatically generated table')
   );

   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Click Me')
   );
   return $form;
}

function listuserstable(){
   // make html for the table and rendering it
}

```

---
Tags: 6, forms, ajax
---


# Question
Title: Adding nofollow to specific internal paths
I am looking to add nofollow to specific internal paths when they appear within text anywhere in the posts.

I tried using the text filters but I only get the options to either nofollow all links within a post body or nofollow all external links.

What I am trying to achieve is to nofollow all links following this pattern (/user/\* ) when they appear within text body.

What are my options? Custom filter? or a preg replace through preprocess. I will appreciate a bit detailed explanation as I am new to programming.

Thanks in advance.

# Answer
Since you want to **add this attribute only to custom URLs (those matching /user/\*) within your content**, you might have to write custom code, as I'm not aware of any module which does this.

You could use hook\_preprocess\_field() and then execute a regular expression to match your pattern and add the `rel="nofollow"` attribute. However, this could be highly inefficient, as you have to do it every time you render a node, besides the fact that parsing HTML with regular expressions is not a bullet-proof solution.

Here it's a *very* simple example that just adds rel="nofollow" to all links in the body field (you will have to adapt it to use your own regular expression).

```
/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
     $markup = $variables['items']['0']['#markup'];
     $variables['items']['0']['#markup'] = preg_replace('/href=/', 'rel="nofollow" href=', $markup);
  }
}

```

Another alternative would be using the Path Nofollow module, that does something *similar*:

> Specify paths on which a metatag is added to prevent search engines from indexing the page.

So you could specify the path /user/\* and it will add a metatag in the head of your html `<meta name="robots" content="noindex">`. As I said, not exactly the same, but it might help or complement your goal.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: how to uninstall custom database table in drupal 6
I want to create custom table for my custom module "custom\_module\_table"

```
/**
 * Implements hook_install().
 */
function custom_module_install() {

 drupal_install_schema('custom_module');

}

function custom_module_schema() {
    $schema = array();
    $schema['custom_module_table'] = array(
    'description' => t('The base table for iframe site builder nodes.'),
    'fields' => array(
      'sid' => array(
        'description' => t('The primary identifier for a iframe site builder.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE),
      'title' => array(
        'description' => t('The {node_type} of this node.'),
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''),

      'uid' => array(
        'description' => t('The primary identifier for a iframe site builder.'),
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE),

      'created' => array(
        'description' => t('The site_password of this node, always treated a non-markup plain text.'),
        'type' => 'timestamp',
        'length' => 255,
        'not null' => TRUE,
        'default' => 'NOW()'),
      ),
    'unique keys' => array(
      'sid'     => array('sid')
      ),
    'primary key' => array('sid'),
    );

    return $schema;
}

/**
 * Implements hook_uninstall().
 */
function custom_module_uninstall() {
     drupal_uninstall_schema('custom_module_table');
}

```

This code write in .install file in my module and table is successfully created but when I am uninstall the module, table is not delete.

Please help me..

# Answer
> 1 votes
1. Check that the DB user has "DROP" privilege.
2. try to use direct query instead of *drupal\_uninstall\_schema*

update\_sql('DROP TABLE {custom\_module\_table}');

---
Tags: 6, hooks, database
---


title: Revoke flag access to node author

text:
# Question
Title: Revoke flag access to node author
I have a workflow system for my nodes, where one of the states is *Disabled*. There are some flags on those nodes as well; I'd like to to revoke access to flags to the node author when the workflow state is changed to *Disabled*.

I'm looking for any solution, contributed modules or custom modules, or just a combination of modules.

I'm not sure if `hook_flag_access()` is relevant here or not.

# Answer
If you need custom module, you can try this code

```
/**
 * Check status of node
 * @param $nid
 * @param $fid
 * @return $result
 * if node have status disable return array()
 * if node have status active return NUll
 */
function check_workflow_status($nid, $fid){
  $result = db_select('flagging', 'fg')
    ->fields('fg', array('entity_id'))
    ->condition('entity_id', $nid, '=')
    ->condition('fid', $fid, '=')
    ->execute()
    ->fetchAssoc();
  return $result;
}

/**
 * Implement hook_flag_access()
 *
 */
function YOURMODULE_flag_access($flag, $entity_id, $action, $account) {
  // Change flag id with your flag's ID
  // You can dpm($flag) to see flag id of status node.
  $result = check_workflow_status($entity_id, 1);
  if (!empty($result)) {
    // You need check special use have permission use flag status
    if (user_access('flag node_status'))
      return TRUE;
    else
      // Deny access to all other flags of the node.
      return FALSE;

  }
}

```

You can get string in user\_access() at here.
> 2 votes

# Answer
`hook_flag_access` and `hook_flag_multiple_access()` do seem to be the way to go. You will need to write a small custom module for that, which you can read more from here.

An example implementation is below:

```
<?php

function MYMODULE_flag_access($flag, $entity_id, $action, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') {// Change flag name with your flag's machine name.
    $node = node_load($entity_id);
    if ($node && $node->uid == $account->uid) {
      return FALSE;
    }
  }

  return NULL;
}

function MYMODULE_flag_access_multiple($flag, $entity_ids, $account) {
  if ($flag->name == 'NAME' && $flag->entity_type == 'node') { // Change flag name with your flag's machine name.
    $nodes = node_load_multiple($entity_ids);
    foreach ($nodes as &$node) {
      $node = $node->uid == $account->uid ? FALSE : NULL;
    }
    return $nodes;
  }
  return array();
}

```

You will need to change "`MYMODULE`" with a module name of your choice, and use the same name and save it as `MYMODULE.module`. Accompany with the `MYMODULE.info`, drop in a folder and activate the module. Above is a sample code for you to start with the module. It checks if the Flag's entity type is `node`. If it's `node`, the relevant node(s) will be loaded, and the user ID will be matched against the provided account's user ID. If they match, it returns `FALSE`, indicating access should be denied. It does not explicitly return `TRUE`, to allow the basic Flag access checks and potential other modules to determine the access.
> 1 votes

---
Tags: 7, flags
---


title: Path aliases more than one

text:
# Question
Title: Path aliases more than one
I could explain everything, but that will take me a while, so, long story short.

I need one node to have 2 path alises (Not re-direction) 2 path aliases, and this is what I need to do, to show some fields in my view or hide them.

The idea is if I access from one view I need to show some fields, or If I join from another one I should hide it

# Answer
Its not good idea to have one page or node with 2 different url, what i suggest to you is to override node view page with panel and create 2 variants.

Create the 2 different views panes and drop them each one in variant.

In the link to that node add GET variabile and switch the right variant based on that

Example /my-url will show the first variat /my-ulr?show=1 Will show the second variant

You control that with panel visibility rule and use php code to check the $\_GET array
> 1 votes

---
Tags: path-aliases
---


title: Images are not appearing on Front Page

text:
# Question
Title: Images are not appearing on Front Page
I've looked far and wide and am unable to resolve why my article images are not appearing on the Front Page. (Even disabled my CSS to see if that was interfering with it, but no.)

I have created a simple test Article and uploaded an image, yet when it's promoted to the front page, the image does not display.

Only the title, and body displays. When I click on the article, it displays the image, is there a setting I'm missing for this to display?

# Answer
> 1 votes
I resolved it by changing the custom display settings from `teaser` to `full content`. Once the image appeared on the front page, I changed it back to `teaser` and the image now displays correctly on the front page.

I'm guessing it's some bug or conflict with some modules that was causing this.

---
Tags: media
---


# Question
Title: Making an ecommerce photography competition website
This has been bugging me for days, I just can't wrap my head around this situation/process and how to make it work in Drupal.

I'm making a photography competition website where a user who signs up and buys a role has the choice to upload 3(costs £4), 10(costs £6) or 20(costs £10) images but each image needs to be a part of a competition category, so say someone uploads 3 images, one is for black and white category (taxonomy term), one is for wide angle and one is for sport, each image needs to be tagged with the correct category, of which im using taxonomy terms. But how do i go about this?

Firstly limiting the user to said amount of photos? I was thinking they buy a role (there are 3 roles), role one allows to upload 3 images using the content type 3 images, role two allowed to upload 10 images on a node and the final content type is '20 images' and they can upload up to 20 images using that content type, each user though must be able to categorise each individual image using the taxonomy vocab already created called Photo Categories. How the hell do i tag each individual image so that they are categorised and ready for viewing/judging later on??

Should I do this on the user profile instead? So that when they buy their role, they can then upload the amount of photos that they are allowed to? This will still mean I have the problem of assigning each image to a taxonomy term.

Also, is purchasing a role the best way to go about this? Now that you know what I am after what are your thoughts? I know Drupal can do this 'out of the box', i'm just struggling to see what workflow the end user will go through to achieve all of this.

# Answer
> 1 votes
I would look at Node Limit. So the user buys roles and that gives them access to create more content.

Then create a content type for Entry with all the appropriate tag fields.

I like the purchasing the role structure. I wouldn't do this directly on the user

# Answer
> 1 votes
There are different ways to go about this, but this doesn't have to be that difficult.

I would go for a process, where the user creates the nodes during checkout. This is a simple approach, as he can only create the nodes during purchase time. It sounds like that could work well for your situation.

There is a module that does something like what you explain: https://www.drupal.org/project/commerce\_node\_checkout

You should also be able to set this up with Rules and fields.

You could create a field collection on the line item for buying images. The field could be unlimited values where each item would be an image that needs to be created. You would then attach fields on the field collection that you require for each image, (the image file, category, and other data about the image)

You could create a price rule that would count the number of items on the field collection and calculate the price based on that.

You could create another rule executed at checkout complete where you loop through each item in the field collection and create a node with the values supplied. Then it's just a matter of requiring the user to input terms or other meta data you want/need in the field collection.

---
Tags: taxonomy-terms, commerce, users
---


# Question
Title: Multiple Relationships in CiviCRM Views Integration
I have been trying to set up a Drupal View of a a 3-way relationship in CiviCRM.

The view I wanted was that showed a list of contacts that are provided services from the current user's employer, as below

(current user) contact a =\> (is employed by) =\> organisation =\> (is a provider of) =\> contact c

I created a view of CiviCRM Contacts, and could not see a way of getting this relationship to display what I wanted without building a custom module, which is explained below.

# Answer
You can do this with a custom module and using the preprocess views hook to pass in the contextual filter. The filters are passed into the $args\[\] variable.

You also may need to enable multiple values in a contextual filter, if you have more than one relationship from Contact A to Contact B, in this case this is multiple employers. This is under Contextual Filters \> Advanced \> Allow multiple values.

You do not add % to the path as you would normally do with a contextual filter as we are programmatically inserting it.

Create a custom Drupal module with the following code

```
/**
* @implements hook_views_pre_view().
*/
function HOOK_views_pre_view(&$view, &$display_id, &$args){

if($view->name == "my_view") {
      // Check that we are altering the correct view based on and $view->name
      civicrm_initialize();
      require_once 'api/api.php';
      //get the matching civi id for the current user
      //This is using Civicrm version 4.4.6

      global $user;
      //first get the current user's Civicrm record
      $params = array(
         'version' => 3,
         'sequential' => 1,
         'uf_id' => $user->uid,
      );
      /*The contact ID is in $result['values'][0]['contact_id']*/
      $result = civicrm_api('UFMatch', 'get', $params);

      $params = array(
          'version' => 3,
          'sequential' => 1,
          'relationship_type_id' => 5, /*get your relationship ID from /civicrm/admin*/
          'contact_id_a' => $result['values'][0]['contact_id'],
      );
      $result = civicrm_api('Relationship', 'get', $params);

      //temp stores the string which will be passed to the $args[] array
      $temp = "";

      //loop through the a => b relationships, and append all the ids of contact b
      foreach ($result[values] as $key => $value ) {
         if ($key > 0)
            $temp .= "+";
         $temp .= $value['contact_id_b'];
      }
      // populate the $args contextual filters array with the ids.
      $args[] = $temp;
   }
}

```
> 4 votes

# Answer
You can do this without a custom module. In Views Relationships your first add a Views Relationship for the CiviCRM Relationship, and then add the Contact at 'the other end' of the Relationship. So for each Civi Relationship you will create 2 Views Relationship. Hence to daisy chain A to B to C, you will have 4 Views Relationships

Not easy to explain especially when both Views and CiviCRM are using the term Relationship.

Add Views Relationship 1 (VR1) of type "Connects a contact (as contact A) to a relationship." (eg employer of) Add Views Relationship 2 (VR2) of type "The contact B" use select VR1 as the 'Relationship'

So you have now connected person X to Org Y

Add Views Relationship 3 (VR3) of type "Connects a contact (as contact B) to a relationship." (eg Provider of) - select VR2 as the 'Relationship' Add Views Relationship 4 (RV4) of type "The contact A" select VR3 as the 'Relationship'

So now you should have connected person X to Org Y and then Org Y to person Z.

For creating RV3, you need to work out whether to use "starting from A" or B as it will depend on how you created your "is a provider of" Relationship. Clear? Not that easy to explain ;-)
> 3 votes

---
Tags: views, civicrm
---


# Question
Title: Add an attribute to a specific tag in text body of page
I would like to add an attribute to a specific **tag** in the text **body** of a page.

I was thinking in this direction:

* add `MYTHEME_preprocess_field(&$variables)` to **template.php**
* apply regular expression to the right field (but which one? `$variables['items'][0]['safe_value']`?)

Can anyone give me a specific working example of applying a regular expression to the body field of a page?

Thanks!

# Answer
> 2 votes
Since you are just looking to add an attribute to a **tag**, you could do your changes to the field `#markup` instead. A simple example:

```
/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
    $markup = preg_replace('/href=/', 'title="foo" href=', $variables['items']['0']['#markup']);
    $variables['items']['0']['#markup'] = $markup;
  }
}

```

---
Tags: theming, entities
---


# Question
Title: Override node.tpl.php for the Front Page
I am trying to override the front page node, however after following the guide from the official site, it's not working.

Guide: https://www.drupal.org/node/1585528

I have taken `node.tpl.php` and renamed it to `node--front.tpl.php` and made changes to the layout, saved and cleared cache. The changes are not being displayed.

Now if I edit node.tpl.php directly it shows the changes, anyone know what I am doing wrong to override specific node templates?

**EDIT:** I want to move the title below the image being displayed in the front page.

See below: Moving the title block under the content block, moves the title down as I want it to do, however how do I specify this for just the front page and not all nodes? (renaming `node.tpl.php` to `node--front.tpl.php` does not work as mentioned above)

In node.tpl.php: (title block)

```
<?php print render($title_prefix); ?>
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
  </h2>
<?php endif; ?>
<?php print render($title_suffix); ?>

```

(content block)

```
<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
?>

```

# Answer
You have to create **page--front.tpl.php** from **page.tpl.php**. You are changing your front page, not the node.
> 1 votes

---
Tags: nodes
---


title: variable Panels image page element

text:
# Question
Title: variable Panels image page element
I'm not sure if this is possible, but I want to create a panel with a header image.

The way I'm planning to do this is to add a new Page element within panels called "Banner" (in this menu http://puu.sh/jfBbm/8c09cfe2fe.png).

Is it possible to have it so then when a user clicks the *"Add Panel -\> Page Elements -\> Banner -\> **Chose image?**"* **or is it not possible to have a variable image with this way?**

# Answer
First install Fieldable Panels Panes module. This module allows you to create different fields for Panels pane. Then go to `admin/structure/fieldable-panels-panes`, Click on *Manage Fields* of *Panes Pane*

Add an *image field*, It is going to be like this

Now click on `Add Entity` tab and create a new entity. You must also create a `Category` in `Reusability`, This *Category* will be displayed in the Panels Content menu, I called it *My own Panels Pane*

Now save it.

If you open a Panel and click on *Add content* the *My own Panels Pane* is available, click on it and select the content you created.

From the list of *Panels Pane* in *Fieldable Panels Pane* there is a direct link to edit this image. I mean this (for testing I created `3` entities ):

Now you can easily edit the image and use it's direct link.
> 1 votes

---
Tags: media, panels
---


# Question
Title: How to upload multiple images as multiple nodes?
I built a social network website that is like Instagram (users can follow each other, upload images and ...) but it focuses on some event. People send us tens of thousands of images every year and we present them on their profile in the website.

Every thing is fine with this website. The only problem is for users who send many images (usually more than 50), It is difficult for them to click on `Create New Content` link for every image and save that image and create new content again. To solve this problem I allow the `images` content type to have unlimited number of image field and used Multipleupload Imagefield Widget to allow users to select multiple files at once.

But every content must have exactly one image, so if a user selects multiple images for a content, we need to have a mechanism to separate every image as a distinct content, we can also share the `Title` of the content among all of them.

The only solution I found so far is to build a module that check for the number of images and create new content for each one on `node save` hook. I would like to know is there any other solution? any module or strategy to handle this requirement?

Thanks.

---

**UPDATE**

as @Gokul N K recommended I installed Bulk File Nodes Module, I also installed Plupload module. After selecting the Image field in `Bulk Photo Node Settings` vertical tab, This is what I see in `node/add/image`

and I can't add any image, By clicking on `next` button this page is reloaded.

# Answer
Check out Bulk File Nodes Module

> Bulk File Nodes allows a user to upload or import many files at once, and have many individual nodes created, one for each file . Where this module significantly differentiates from other modules like Bulk Media Upload is that after uploading/importing the file(s), the user is given the opportunity to edit all of the fields for each node in a single form.
>
> Another form to the right acts as a bulk settings form where each field that has a value is applied to each node's corresponding field, except where the user has overridden the bulk settings form by specifying a value in the field of an individual node.
> 2 votes

---
Tags: 7, nodes, media
---


title: Views content in search results page

text:
# Question
Title: Views content in search results page
I have created a content type and used this in Views. Means this content type is always display via Views only . When searching for a keyword these nodes are displaying in the search result page which is fine.

When clicking on the result it opens the individual node content page but I want to open the Views page where these nodes are in use. Please help if anybody know the solution.

# Answer
> 1 votes
Copy the file `your_site/modules/search/search-result.tpl.php` to your theme and modify the code.

You can read more about this in:

Customizing search-results.tpl.php and search-result.tpl.php

---
Tags: views, search
---


title: Search module in drupal 7

text:
# Question
Title: Search module in drupal 7
I am using drupal 7 built in search module, when I searched for example `mechanics` it will filter out the results successfully but when I used to write only `mech` or `mechan` something like this, **it displays no results**.

For this I have installed Apache Solr Autocomplete and Porter-Stemmer but I unable to figure out **how can I improve my search filtration**.

# Answer
> 1 votes
Look at the module **Fuzzy Search** , this may solve your problem.

> This module provides drupal sites with a fuzzy search engine to allow for broader keyword matches including partial or misspelled keywords.
>
> Fuzzy matching is implemented by using ngrams. Each word in a node is split into 3 (default) letter lengths, so 'apple' gets indexed with 3 smaller strings 'app', 'ppl', 'ple'. The effect of this is that as long as your search matches X percentage (administerable in the admin settings) of the word the node will be pulled up in the results.

---
Tags: 7, search
---


title: Drupal as mobile application backend

text:
# Question
Title: Drupal as mobile application backend
What I try to achieve is create a simple Form where I will be able to add new content (like "Question" objects for instance) and access the information through Services 3.x. My problem is that I am new to Drupal and some guidance will be very helpful. I have tried to create a new custom content type, but as I need grouping of the fields, I used the "field collection" module. The problem there was that when using the node service I couldn't get the content of this field collection. So I am actually stuck now. The following questions appear in my head now:

1. Do I need to write my own module to be able to extend the NODE object or I can achieve it by creating custom content type?
2. Can I customize a service to return only desired properties (like only the id and the title of a node without returning all other properties like createddate, modifieddate, etc.) or should I create my own module to achieve this?
3. If I need to create a custom module, can you point me to an example? (I have read the Drupal article for creating a resource for Services 3.x, but there they using a new custom object and not the NODE object)
4. How can I have both a form to enter content and a service resource for the basic CRUD operations in one module? Using hooks?

Basically my point is to skip writing code for CRUD operations if it is possible and just use the ones from the NODE, but expose to the mobile app only some of the NODE properties and have a form where I can enter new content.

I am using Drupal 7.

I want to apologize for the messy post, but it really represents the thoughts in my head...

# Answer
That's 4 questions in one ;-) For #2 checkout my previous question that has just been answered. Services Views would be another solution to do it without code.
> 1 votes

# Answer
though this is kinda old it might be interesting for a few. ive been using this excellent library https://github.com/jbeuckm/drupal-client that saves you tons of time as it handles the communication with a REST/Services enabled Drupal as a backend for a mobile app.

calling a view via the library, for instance, is a simple as

```
function loadView(view) {
    var viewName = view;
    var args ="";
    var headers ="";
    drupal.getView_custom(viewName, args, function(response) {
    Ti.API.info("response " + JSON.stringify(response));
    },
    function(error) {
    Ti.API.info("error " + JSON.stringify(error));
    }, headers);
};

```
> 0 votes

---
Tags: nodes, forms, hooks, services, theming
---


# Question
Title: Render/display Panel's page outside 'content'
I'm fairly new with Panels. By default Panels content will be displayed inside

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

```

Is it possible to display it outside the content? For example if I made another placeholder and display inside it?

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

```

**NOTE:** I'm using Drupal 7.

The reason I want to do this because the `<?php print render($page['content']); ?>` is sitting inside

```
<div class="container content-main">
  <?php print render($page['content']); ?>
</div>

```

All `contents/pages` will be displayed inside `content-main` except 1 page which I don't want it to be inside the `content-main` div.

The `content-main` class have `css` which I don't need it in the panel.

The 1 page I want it to have its own `<?php print render($page['content_panel']); ?>` so that I can assign the panel to it and located outside the `content-main` div.

# Answer
> 0 votes
I think you need to use mini panels, mini panels shiped with panel module and you can use it as block, any mini panels you create will be listed under blocks, just assign it to the region you want

---
Tags: panels
---


# Question
Title: How to customize Carousel in Bootstrap theme?
I am new to Drupal and want to know how I can customize a certain feature on the site.

I am using the Drupal Bootstrap theme and I have added the Bootstrap Carousel in `\sites\all\themes\bootstrap\theme\system\page.tpl.php`

The thing is I have hard coded the images for the carousel like so:

```
<div class="item">
      <img src="<?php print $base_url . '\sites\all\themes\bootstrap\screenshot.png'; ?>" alt="...">
      <div class="carousel-caption">
        ...
      </div>
    </div>

```

What I want is to set it up so that the user can choose the images for the Carousel from the user interface under Appearance \> Theme Settings.

How do I achieve this?

Thanks

# Answer
> 0 votes
First of all this is not the right way to use such theme, you should not touch drupal core or any contribute module or theme. For example in bootstrap theme you create sub theme that based om bootstrap theme, if you read the documentation of bootstrap theme you will find the instruction how to do that. For the second part, you may need to create a content type first, add image field and then use views module to display your slide show, you can find a module called views bootstrap to make the used of bootstrap elements.

Drupal is powerful CMS but its not easy one.

# Answer
> 0 votes
The best solution is that don't play with core files. Just disable **Carousel** in theme and add your own one. For this purpose;

1. Create a **Content Type** (including images or other fields if you want).
2. Install Views Slideshow.
3. Create a **Views**(Block type) and select a format as **slideshow**.
4. Go to **admin/structure/block** and place your recently created **slideshow** block in desired region.

---
Tags: theming
---


title: Best practice for installing Drush?

text:
# Question
Title: Best practice for installing Drush?
I have been a Drupal site builder for some time, but I kind of got started with it backwards. Recently, I have begun learning more server-end things like Drush, Git, etc. I'm playing around with a Digital Cloud virtual server, and I'm not having a problem per se, but I have found at least 4 ways to install Drush:

* Through Pear
* Through apt-get
* Through Composer
* By downloading the files straight from Github

(If it matters, I am on a Debian environment.)

It *seems* that Pear may be the preferred way from what I can tell, but that's just based on the fact that I found that to be recommended slightly more frequently than the other methods.

Is this just a matter of preference? I admit I am not very familiar with Pear and Composer. Or is there a method that most devs consider to be a best practice?

Thank you.

# Answer
> 2 votes
You have to install Drush through composer because it provides all the depencies which are required for drush. apt-get is basically supported by the Linux and Debian.

So use this link to install using composer : https://github.com/drush-ops/drush

---
Tags: drush
---


# Question
Title: How to print drupal module version with drush 6.5.0
Here's an example of a module in one of my make files:

```
projects[views][version] = "3.8"
projects[views][type] = "module"
projects[views][subdir] = "contrib"
projects[views][download][url] = "git://testurl.org/drupal/modules/views.git"
projects[views][download][tag] = "7.x-3.8

```

Drush 5.7.0 adds information about the module to every module .info file:

```
; Information added by drush on 2015-01-20
version = "7.x-3.8"
core = "7.x"
project = "views"
datestamp = "1421783211"

```

I can't find a way to append this information with Drush 6.5.0 and since I am using a git repo, the version is always missing from the .info file.

Is there a way to print that information with Drush 6.5.0?

# Answer
> 0 votes
You can use the following command to check all the info about a module. For this command is :

```
drush pmi module_name

```

This command provide info like this :

```
Extension        :  module_name
 Project          :  module_name
 Type             :  module
 Title            :  module_name
 Description      :  Improves Drupal's login system.
 Version          :  7.x-1.5
 Date             :  2015-05-01
 Package          :  Other
 Core             :  7.x
 PHP              :  5.2.4
 Status           :  enabled
 Path             :  sites/all/modules/module_name
 Schema version   :  7000
 Files            :  none
 Requires         :  none
 Required by      :  module_name
 Permissions      :  none
 Configure        :  admin/config/system/module_name

```

---
Tags: drush
---


title: Drupal TB mega menu is so slow

text:
# Question
Title: Drupal TB mega menu is so slow
I am developing a website using **Drupal** and **TB Mega Menu** for my main menu, when I used **Devel** to check the execution time I found that **TB Mega Menu** is taking about **23978.991 ms** on the following query;

> SELECT m.load\_functions, m.to\_arg\_functions, m.access\_callback, m.access\_arguments, m.page\_callback, m.page\_arguments, m.delivery\_callback, m.title, m.title\_callback, m.title\_arguments, m.type, m.description, ml.\* FROM menu\_links ml LEFT JOIN menu\_router m ON m.path = ml.router\_path WHERE ml.menu\_name = :menu ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC

Any idea why ?

# Answer
> 1 votes
Could be you're missing a mysql index... The 9 "ORDER BY" clauses in the query would run really slowly without an index called "menu\_parents". To find out if you have it, run the following:

```
SHOW INDEX from menu_links

```

If everything is set up correctly then you should get something like:

```
+------------+------------+------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table      | Non_unique | Key_name               | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+------------+------------+------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| menu_links |          0 | PRIMARY                |            1 | mlid         | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | path_menu              |            1 | link_path    | A         |        1286 |      128 | NULL   |      | BTREE      |         |               |
| menu_links |          1 | path_menu              |            2 | menu_name    | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_plid_expand_child |            1 | menu_name    | A         |          67 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_plid_expand_child |            2 | plid         | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_plid_expand_child |            3 | expanded     | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_plid_expand_child |            4 | has_children | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            1 | menu_name    | A         |          61 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            2 | p1           | A         |         428 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            3 | p2           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            4 | p3           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            5 | p4           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            6 | p5           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            7 | p6           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            8 | p7           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |            9 | p8           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | menu_parents           |           10 | p9           | A         |        1286 |     NULL | NULL   |      | BTREE      |         |               |
| menu_links |          1 | router_path            |            1 | router_path  | A         |        1286 |      128 | NULL   |      | BTREE      |         |               |
+------------+------------+------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

```

If you're missing the "menu\_parents" rows then you can run the following:

```
CREATE INDEX menu_parents ON menu_links (`menu_name`,`p1`,`p2`,`p3`,`p4`,`p5`,`p6`,`p7`,`p8`,`p9`)

```

If that doesn't help then it might be worth posting the result of an EXPLAIN of your query:

```
EXPLAIN SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.delivery_callback, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.* FROM menu_links ml LEFT JOIN menu_router m ON m.path = ml.router_path WHERE ml.menu_name = "main-menu" ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC

```

(assuming that "main-menu" is the menu being queried).

---
Tags: navigation
---


# Question
Title: How to change the theme for a particular admin page in drupal?
I have a page with `url ?q=admin/settings/history` . Is there any way by which I can change the `template` for this page alone. I tried using `hook_preprocess_page` but I was unable to change the layout of page. Could someone please lead me in the right direction?

# Answer
> 10 votes
Yet another solution, in a couple of lines of code, is:

`hook_custom_theme`

> Return the machine-readable name of the theme to use for the current page. This hook can be used to dynamically set the theme for the current page request. It should be used by modules which need to override the theme based on dynamic conditions

e.g

```
/**
 * Implements hook_custom_theme
 */
function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'admin/settings/history') {
    return variable_get('custom_theme', 'theme_name');
  }
}

```

Core example: `system_custom_theme`

*Update*: To use a specific template you can override `page.tpl.php`

* copy `page.tpl.php` to `page--admin--settings--history.tpl.php`, clear caches (theme registry) and use that.

More info: https://drupal.org/node/1089656

# Answer
> 5 votes
It looks like you might be looking for a ThemeKey module:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic **selection of a theme depending on current path**, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules

Emphasis mine.

You can either use it directly, or use it's source code as an example - it's GPL, so you have the right to do it.

# Answer
> 3 votes
In a simple way you can change the theme key by checking the condition,

```
/**
 * Implements hook_init().
 */
function <module_name>_theme_init() {
    global $theme_key;

    if ($_GET['q'] == "admin/settings/history") {
        $theme_key = '<Your new Theme key>';
    }
}

```

# Answer
> 2 votes
You can use Page Theme module

> The Page Theme module is a simple and easy module to use which allows to use different themes than the site default on specific pages.

# Answer
> 0 votes
I would suggest to implement a custom module that changes the theme being used for specific pages. It is enough to implement hook\_custom\_theme() as follows:

```
function mymodule_custom_theme() {
  if (arg(0) == '' && is_numeric(arg()) && arg(3)== history
) {
    return 'go theme page what you want yo use';
  }
}

```

---
Tags: 7, theming
---


# Question
Title: Is it possible to create a panalized node in code?
Is it possible to create a Panelized node programatically?

Perhaps something like the following:

```
$node = new stdClass;
// ... Set other properties
node_save($node)

// Then somehow add panalizer , layout, panels
// Something like:
$panelizer = array ( 'nid' => $node->nid )

//save it
panelizer_save_node_panelizer($panelizer)

// add existing panels/panes to the node
?>

```

# Answer
1. Make sure that your content type is *panelized* (you've *panelizer* link at `/admin/structure/types`).
2. Double check the Panelizer settings of that content type, for instance whether to '*Provide an initial display named "Default"*' (at `/admin/structure/types/manage/%`).

Above 2 steps can be achieved programatically by either exporting `panelizer_defaults` component into Features code:

```
features[panelizer_defaults][] = node:my_content_type:default

```

or define them using `hook_panelizer_defaults` manually.

At this point all your created nodes should be panelized automatically and the settings should be available in node object at `$node->panelizer['page_manager']`.

Still not sure if your node is panelized or not? Run this via `drush` (where 123 is your node id):

```
$ drush eval "print_r(node_load(123)->panelizer['page_manager']);"

```

and if you'll see an object printed out, your node is panelized.

Then if you would like to create/re-create panel display associated with the node, try the following code:

```
$node = node_load($nid);
$old_display = $node->panelizer['page_manager']->display;
$new_display = panels_save_display($display);
$node->panelizer['page_manager']->display = &$new_display;
$node->panelizer['page_manager']->display_is_modified = TRUE;
node_save($node);
// Clear caches just in case.
ctools_include('object-cache');
ctools_object_cache_clear('panels_node_display_cache', $node->nid);
$did = is_numeric($new_display->did) ? $new_display->did : FALSE; // Your display id.

```

The same thing can be achieved on newly created code by creating a `panels_new_display();` instead and assign it to `$node->panelizer['page_manager']->display`. Also note that the display should be only saved once (not on every node save), then it can be modified based on your needs.

See also:
> 3 votes

# Answer
I haven't tried myself, but taking a quick look at the Upgrade path from Panel Nodes to Panelizer, we can find that the step that seemingly converts Panel Nodes into Panelized Nodes, is `db_insert('panelizer_entity')`.

This is further confirmed by a look into Panelizers `PanelizerEntityDefault.class.php`, where the method `public function hook_entity_insert($entity)` also does a `drupal_write_record('panelizer_entity', $panelizer);`

Hardly a nice step by step guide, but hopefully this should get you going.
> 1 votes

# Answer
I use a workaround using a db\_select and a db\_update.

```
$nid = $node->nid;
$p_name = 'node:*panelizername*';

//Get the panel-info
$p_defaults = db_select('panelizer_defaults','d')
->fields('d')
->condition('d.name', $p_name, '=')
->execute()
->fetchAssoc();

//Remove fields that are node in the panelizer_entity
unset($p_defaults['pnid'],$p_defaults['name'],$p_defaults['title'],$p_defaults['panelizer_type'],$p_defaults['panelizer_key'],$p_defaults['access']);

//Update panelizer_entity
$u_query = db_update('panelizer_entity')
->fields($p_defaults)
->condition('entity_type', 'node')
->condition('entity_id', $nid)
->condition('name', $p_name);

/*dpm($u_query->arguments());
dpq($u_query,FALSE,'Update');*/

$u_query->execute();

```
> 0 votes

---
Tags: 7, panels
---


title: Hide Edit View link in Newsletter

text:
# Question
Title: Hide Edit View link in Newsletter
I have created a view and sending the view as newsletter to users. But received mail contains **EDIT VIEW** link. How to remove the edit view link from newsletter. I have added the screenshot of received email. I am using Mime Mail for sending email.

# Answer
> 0 votes
Remove permission for anonymous users to edit views from yoursitesname.com/admin/people/permissions

It kind of a long page, so try "ctrl+f" and there type "administer Views" and uncheck the right permission.

If it's not helping, try using another Newsletter module (It's maybe a bug since there is no logical reason to give to email subscribers edit your views, of course).

Please update in comment what worked for you.

# Answer
> 0 votes
Finally found the solution

In views, Under Advanced tab, Select yes option in **Hide contextual links**. I have added the screenshot

---
Tags: views, emails
---


# Question
Title: Filter view results by day of the week instead of the date - Date Module
I have a view which includes a date field, and I'd like to provide a filter for users to show only items from a certain day of the week. From what I can see, though, the date filter only allows you to select the date by which to filter. Is it possible to create a filter which will allow users to show, say, all nodes which have a date that falls on a Wednesday?

# Answer
> 1 votes
I think you have to use the Views Day of Week module to filter the result by day of week. Here is a quote from it's project page:

> ... Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.
>
> **Example**: With this module you can select that some content should be visible only on Mondays, some on Tuesdays and Thursdays and some only on Fridays.

---
Tags: views, datetime
---


# Question
Title: Regions do not display in "Demonstrate block regions"
I wonder why some regions of my theme don't display in section 'Demonstrate block rerions'.

This happens with some themes which I downloaded from Drupal.org, for example with the Software theme.

Here is part of its 'info' file (showing multiple regions):

And this is what 'Demonstrate block rerions' for this theme looks like:

**My question**: What could be causing this?

I use SEVEN as admin theme. On page admin/structure/block I see the link "Demonstrate block regions (Software Responsive Theme)" and all regions that defined in .info file. But when I click this link, I see ONLY SOME OF IT BUT NOT ALL . I try to change admin theme, but it is not help.

Maybe problem in this particular theme?

# Answer
Try switching the administration theme you're using, to a theme shipped with Drupal core.

Or refer to the article "Demonstrate block regions" missing in Drupal 7 for some more hints about this. Here are some quotes from it:

> On a fresh install, you should see "Demonstrate block regions" when you go to admin/structure/block. If somebody has played around with the block settings on your Admin theme, this selection might disappear.
>
> Make sure that “System help” is assigned to a region (probably ‘Help’) in your Admin theme (probably 'Seven’). Go to 'configure’ for the 'System help’ block and make sure that the visibility settings are not restricted in some way.

Another possibilities you may want to try (haven't had a chance myself to try that, sorry):

* inspired by Issue # 996214, which is about another theme though:

> Verify if the "System Help" block is placed in the help region.
* inspired by Issue # 1392206, which is about another theme though:

> You might need to **turn on the Help module** in core modules.
> 0 votes

---
Tags: theming
---


# Question
Title: How do I avoid unwanted users create accounts?
I am using Drupal 7 and use the User verification module for blocking (prohibiting) unwanted users in our site, but a user is creating an account every second.

How can I stop that from happening?

Is it possible to first send an email to the users, with a verification link included? When that link is clicked, users will be registered on the site.

# Answer
> 3 votes
Consider adding either of those modules (quotes are from their project pages):

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on a Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

> Invisible antispam without CAPTCHA, questions, puzzles, counting animals, math and etc. Just install and forget.
>
> CleanTalk is a SaaS spam protection service for Web-sites.
>
> CleanTalk uses protection methods which are invisible for site visitors. Using CleanTalk eliminates needs in CAPTCHA, questions and answers, and other methods of protection, complicating the exchange of information on the site.

> BOTCHA Spam Prevention is a highly configurable non-CAPTCHA spam protection framework.
>
> BOTCHA, doesn't abuse human users, BOTCHA protection is completely transparent to them and non-intrusive.

If these modules still don't help to reduce your issues, then I would go for plan-b, i.e:

* consider reviewing (extending if needed) your registration form, by adding 1 (or more) field(s) so that it becomes AbitMORE difficult to complete registration requests. Either some obvious question for which your target audience should know the answer by heart, or something for which the answer can be found by first browsing around on your site. Yet another option is to ask some question about their real name or address, which may help later on how "serious" the request is.
* make admin approval required for every new user registration request. This will reduce the speed of "registered" users to the speed of an admin approving / reviewing such requests.

Pretty sure this plan-b will help a lot ... up to you to decide if it fits with "the entire point of your site".

# Answer
> 2 votes
It depends on what kind of control over user accounts you want. By default Drupal allows visitors to register new accounts. If you want to disable that, you can set *Who can register accounts?* to *Administrators only* at `/admin/config/people/accounts`.

# Answer
> 1 votes
Create custom module and check user ip if this ip user already register in or already they can create account set restriction on using this function

```
function user_login_authenticate_validate($form, &$form_state) {
/**********/
}

```

https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_login\_authenticate\_validate/7

or using this module https://www.drupal.org/project/ip

# Answer
> 0 votes
> Is it possible to first send an email to the users, with a verification link included? When that link is clicked, users will be registered on the site.

Yes, go to admin/config/people/accounts, and select "Require e-mail verification when a visitor creates an account."

---
Tags: 7, users
---


title: Get node view count for each day

text:
# Question
Title: Get node view count for each day
I have site with thousands of user and logins each day. I need to track each page views of each user to generate a report.

If a user 'A' visits a page 'P' today, a new entry daycount is added to the DB. If the same user 'A' visits the same page 'P' on same day, the daycount will increment by one. If a user 'A' visits page 'P' tomorrow, a new entry daycount is added to the DB.

I am using drupal 7. The insert and update works properly if there is no date comparison. Once i added `if($TimeNow > $UpdateTime)`, the page load never ends. Can anyone help me to fix this.

```
if(db_query('SELECT daycount FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid))->rowCount() == 0) {

    $ChQry = "(SELECT timestamp FROM {report_page_view} WHERE id = 9999999990 AND uid = :uid )', array(':uid' => $GLOBALS['user']->uid)"; // Get the previous timestamp
    $ChResult = db_query($ChQry);

    while ( $ChGetResult = $ChResult->fetchAssoc() ) {
       $TimeStm = $ChGetResult['timestamp'];
    }
        $UpdateTime = $TimeStm + 86400; //Get the next day
        $TimeNow = time();
        if($TimeNow > $UpdateTime) { // Compare current time and tomorrows date
        // insert if condition works
        $insert_page = db_insert('report_page_view')->fields(array('title', 'memberorg', 'id', 'type', 'timestamp', 'daycount', 'uid', 'fname', 'lname'));
            $insert_page->values(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,

          ));
        $insert_page->execute();
    }
    } // else update
    db_update('report_page_view')
    ->fields(array(
            'title' => $Title,
            'memberorg' => $MemberOrg,
            'id' => 9999999990,
            'type' => 'views',
            'timestamp' => REQUEST_TIME,
            'daycount' => 1,
            'uid' => $UserId,
            'fname' => $FName,
            'lname' => $LName,
    ))
    ->expression('daycount', 'daycount + 1')`

```

# Answer
Consider using the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

> ... allows to count node views. Unlike statistics module, this module **records each view of node with user uid and timestamp**. So now you can know **how many times a user viewed node by day, week, month and etc**.
>
> This module is **integrated with Views module**. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

By using this module, and to the extend it should be needed, you can then further refine / extend what you get (out-of-the-box) from this module via a custom module(s) and/or view(s).
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How can access the Question from its Course when using the E-learning module?
I am using Drupal 7 and I have installed the "E-learning" module.

I have created these items:

* a Question.
* an Exercise (which includes the Question).
* a Unit (which includes an Exercise).
* a Course (which includes the Unit).

How can access the Question from the Course I have created?

# Answer
> 0 votes
This module creates an hierarchical structure COURSE \> UNIT \> EXERCISE \> QUESTION.

These are entity types connected with each other using an Entity Reference field. You can attach and reuse different units to each course, different exercises to each unit, etc.

So to access the Question from the Course, you follow the "links" that are created via the Entity Reference field. Obviously, for that you must first have entered the data (entity references) for each Question (and its related Exercise), and for each Exercise (and its related Unit), etc.

---
Tags: 7
---


title: safest way to redo aliases

text:
# Question
Title: safest way to redo aliases
So a site in production wants certain aliases to be redone. If there's another way to do this other than `Home » Administration » Configuration » Search and metadata » URL aliases > Delete aliases`, please let me know. I dont want to run that if it's going to break the site since it is in production. I can always rebuild using `Bulk Update > Content Paths` after `Delete aliases` . Please advise. Thanks.

# Answer
You'll find "Update URL alias" as one of the choices for bulk operations for nodes under admin/content

This way you can select which specific nodes that needs URL aliases rebuilt instead of deleting and rebuilding all.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Joomla to Drupal: how to use migrate module
I want to move my website from joomla to drupal. I read that the **migrate** module is the appropriate but i don't know how to use it. Can someone give guides to do this.

# Answer
Use **Joomla to Drupal** Module

> This module enables the import of the following content from a Joomla website into Drupal.
>
> * Users
> * Sections & Categories into Taxonomy Vocabularies and Terms
> * Content items to nodes

If you want to use Migrate module, Here is the link Getting started with Migrate
> 1 votes

---
Tags: migrations
---


# Question
Title: How to add a script to checkout (for affiliate partner programme)?
Original question:
I want to add a script to an order on checkout completion or even better with the rule 'when an order is first paid in full'. But I don't know how or where exactly.

*Why I need it:* we want to use an external affiliate partner programme for PPS (pay per sale). So when a customer is coming from site A to our shop and orders somthing, the owner of site A gets a certain percentage of the sale. In order for that to work, I need to add a script to the checkout. Or better add the script when the order is paid in full. I use tokens for the UID, order number and total amount in the script I got from the external affiliate partner.

The script looks like this:

```
<script type="text/javascript" src="https://track.adcocktail.com/tracking_sale.php?t=s&kid=xxxx&lv=0&bestid=[commerce-order:order-number]&wert=[commerce-order:commerce_order_total]&beschreibung=[commerce-order:mail-username]"></script>

```

I tried adding it *by a rule* "add a variable" (on checkout completion) but that doesn't do anything. When I add the script to the order as *a text field in the checkout*, I can't use the tokens (they aren't recognized) and the script is run every time I do something to that order so it appears more than once in the affiliate overview.

Does someone know how I can make this script work ?

(I hope my question is clear. If not, just ask.)

* Drupal Commerce Kickstart 7.x-2.25
* Drupal 7.38

EDIT:

I don't need to activate the script on checkout completion, but 30 days after the order is paid in full. So after the 30 days the customer legally has to return goods. And that's not so easily done as adding the script on checkout completion.

Does anyone has an idea on how to make a rule for it ?

# Answer
I would add the script by implementing hook\_commerce\_checkout\_complete in a custom module. You also have access to the order in the function.

```
function MYMODULE_commerce_checkout_complete($order) {
  drupal_add_js(
   'https://track.adcocktail.com/...',
    array('type' => 'external')
  );
}

```

You need to debug the variable `$order` to find the values you stated, \[commerce-order:order-number\] etc.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to pick the most expensive shipping rate
I have a Drupal 7 site with Drupal Commerce e-shop. For most of the products I charge a flat rate, in 3 tiers, some products cost € 5 to ship, some € 6 and some € 25, implemented as three flat rate shipping services.

I have set up rules to apply the correct shipping rate. These rules check for the presence of applicable products and - if found:

1. Delete all shipping line items from an order
2. Apply shipping rate to an order

I've set the weight of the rules so they are evaluated cheap-to-expensive. I figured the expensive shipping would then replace the cheap shipping.

I get both though. My check-out form shows:

-- Article listing --
Subtotal € 20
Shipping € 6
Shipping € 25
Order total € 51

Instead I just want to charge € 25 for shipping. Is the current behavior the expected behavior? Is my current approach wrong and misguided?

# Answer
> 0 votes
seems like your 6€ shipping rate does not have a maximum, so it gets listed again ?

---
Tags: rules, commerce
---


# Question
Title: Overwrite Taxonomy Term page display settings with custom URL's
I would like to define the display settings of my Taxonomy term page. As I understand, this is possible by configuring the Taxonomy view provided by the Taxonomy module.

However, I use custom URL's and by so, my taxonomy pages doesn't have the URL `taxonomy/term` but something like `products/tents`.
Is there a way to customize these pages with the provide view?

# Answer
> 1 votes
You can set the patterns used for Taxonomy URL aliases.

http://drupal.org/node/120631

Sounds like you want to use: \[term:vocabulary\]/\[term:name\]

If you have it enabled, you should be able to see the patterns here: www.yoursite.com/admin/config/search/path/patterns

# Answer
> 1 votes
First thing, For customize path you can use `Pathauto` module where you can provide customize path according to your requirements for Node, Taxonomy terms pages etc. Go to this path for customize paths : `admin/config/search/path/patterns`

Second thing, for customize `Taxonomy Term` pages you have to enable `Page Manager` which is available in `Ctools` module and then go to the admin/structure/pages and then enable the default `Taxonomy term template`. After enabling, click on edit. It will open a panel page. Then add the view that you want to show on this panel page.

---
Tags: 7, views, taxonomy-terms, theming
---


# Question
Title: Can I create nodes through drush for particular content type
I have different content type in my site. For testing purpose, I want to add content to all content type form, but manually its not possible in such short term.

So, is any Drush command available to create node?

# Answer
Just a note to point out a new module called Faker which can be used in conjunction with Devel Generate :

> Use the PHP Faker library to generate **more meaningful sample content**.
>
> Devel Generate is great for creating a lot of sample content in a hurry, but sometimes you want samples that are more meaningful, or closer to the content you expect users to generate. This is where Faker comes in.
>
> Faker is a PHP library that generates fake data for you
>
> Faker (the library) can generate **real looking names, addresses, emails, domains and more**. Faker (the module) combines the library with quick content creation abilities provided by Devel Generate, to give you the power to easily generate real looking sample content.
> 3 votes

# Answer
you can use devel generate module to generate content for testing purpose.Not sure this can be achieved using drush.
> 1 votes

# Answer
There are `drush genc` command, if you write `drush help genc` you will see next thing.

```
Create content.

Arguments:
 number_nodes                              Number of nodes to generate.
 maximum_comments                          Maximum number of comments to generate.

Options:
 --feedback                                An integer representing interval for insertion rate logging. Defaults to 500
 --kill                                    Delete all content before generating new content.
 --languages                               A comma-separated list of language codes
 --skip-fields                             A comma delimited list of fields to omit when generating random values
 --types                                   A comma delimited list of content types to create. Defaults to page,article.

```

So you can create nodes like `drush genc 10` and also you can pass --types option(to create nodes of c.types you want). I guess you will need to install Devel module to use this command.
> 1 votes

# Answer
```
drush genc 5 --types=article

```

create 5 article type node.
> 1 votes

# Answer
Try with `drush generate-content`.
> 0 votes

---
Tags: drush
---


title: Drush on an already existing project

text:
# Question
Title: Drush on an already existing project
First, I apologise for this question, it'll probably look very simple to a lot of you, but I am quite new at this and can't seem to figure it out.

I am working on a project that requires that I import a lot of data from a wordpress site. For that I want to use wordpress migrate. This module recommends me to use drush to transfer the data.

After having had quite a lot of problem installing it (thank you windows) I finally managed it. Now I'd like to use drush on one of the projects that's in my wamp\www file.

How do I do that? I've been looking but can't find the solution

I tried the commands from this: https://www.drupal.org/node/1958170 but it says : "Command variable-set needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. Command variable- set requires Drupal core versu=ion 6 or 7 to run."

I am working with drush 7 and I am hoping to use it on a drupal 7-\*...

Please help!!!!!

==== EDIT ====

Once I'm in the right place I no longer get the "needs a higher bootstrap level".

After reading a few things to sort out my problem (and probably messing things up) it came back, even if I am inside the sites folder.

I can download new modules but cannot enable them I cannot activate the migrate module and commands

and I don't see the PDO drivers listed when I do drush php-eval "phpinfo();"

What's wrong with drush ?

# Answer
> 1 votes
The "needs a higher bootstrap level" error means that you're not in the right directory to call drush.

Where's your drupal source directory ? `cd` to that directory , and try your drush command again...

---
Tags: drush
---


# Question
Title: How are node and field tables related in MySQL?
I am working on a query that involves the field\_data\_body Drupal table, and I have been asked to return corresponding node ids for the relevant rows in field\_data\_body.

However, after reaching a copy of what I think is the accurate database diagram for Drupal databases here -

https://www.drupal.org/files/er\_db\_schema\_drupal\_7.png

I don't see how the node table relates to the field\_data\_body table, so I don't know what kinds of joins I could do to connect them.

I am a DBA working with the database so I am using only SQL. Although if there is a better way to return a report linking these two (in PHP, etc.) I'd be grateful if someone could let me know that, too.

Thanks for any help, jrdevdba

# Answer
> 2 votes
Fields belong to entities; entities are generic, and the same field can be shared amongst any number of different entity types. So you'll find potentially data from a number of different entity types in any given field table.

All field tables take the same basic form, with the entity\_type, entity\_id, language and deleted columns used as the differential (with delta added to make up the primary key, and allow multiple cardinality).

So a manual join for a node to the body table might look like this:

```
SELECT title
FROM node n
INNER JOIN field_data_body b ON b.entity_type = 'node' AND b.entity_id = n.nid AND b.language = 'und' AND b.deleted = 0

```

Regarding a "better way", the Views module is usually the best solution for such things. I've never used it but I also understand Forena Reports might be useful too.

---
Tags: nodes, entities, database
---


# Question
Title: How do I assign variables from FormatterBase-Interface to hook_page_attachments()?
I have created new field-types in drupal.

Therefore I have an Instance of FormatterBase, which gets the values from the database and tries to render the values.

but i want to pass the variables #wkt and #zoom also to the \_page\_attachments-hook of the .module file, because I need the variables in the drupalsettings variable. (js neededs this variables)

```
class GeoObjectWKTFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = array();
    foreach ($items as $delta => $item) {
      $elements[$delta] = array(
        '#theme' => 'myosm_block',
        '#wkt' => SafeMarkup::checkPlain($item->value),
        '#zoom' => SafeMarkup::checkPlain($item->zoom_level),
      );
    }
    return $elements;
  }
}

```

My hook:

```
/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
    $attachments['#attached']['drupalSettings']['mymodule']['zoom'] = //here I want to assign the value;
    $attachments['#attached']['drupalSettings']['mymodule']['wkt'] = //here I want to assign the value;
}

```

# Answer
> 0 votes
No, you don't want to do this.

You can set #attached everywhere. hook\_page\_attachments() is just the global hook that allows to add attached things to all pages.

But you don't need this if you want to use #attached for own structures, just add them to your render array that you return.

---
Tags: theming, hooks, 8
---


# Question
Title: modifying results displayed for Search API Live results module
I really like the SEARCH API and have been playing with Search api live results. I have two questions about this though:

Is there a way to bold the the part of the live search result that matches what i've typed so far? Ex: if i've written "cat" and there's a node with the title "caterpillar" the live search results will show "**cat**erpillar" I know that Search api autocomplete does something, but I was wondering how to do so with this module. I did check out this tutorial but I want to modify the content that appears below the search box, not in the search page.

My second question is: Is there a way to have the results (again, not the ones on the search page, but the ones generated below the search box) organized in subsections, by contentype.Ex: I type cat and there are results of content type a, content type b, content type c.

Contenttype a
**cat** a1
**cat** a2
Contenttype b
**cat** b1
Contenttype c
**cat** c1
**cat** c2

Would I be able to do this with a view or would I have to write code to do this?

----------------UPDATE------------------
I think I found the function that generates the html for the live results. I’ve attached an image of it.
In this function, I can see how a live-result-search-item div is created but I haven’t quite fully figured out how they generate the href inside it. I feel like it's done in another jquery function which I've also attached an image of.
I posted an answer. I still haven't figured out how to group items by content type though.

# Answer
```
for(key in matches){
   var endOfUrl = matches[key].search('>')+1;
   var url = matches[key].substring(0,endOfUrl);
   var rest = matches[key].substring(endOfUrl);
   var regex = new RegExp( '(' + searchString + ')', 'gi' );
   bolded= rest.replace( regex, "<b>$1</b>" );
   matches[key]= url+bolded;
}

```

right before the line

```
db.cache[searchString] = matches;

```

This bolds all occurrences of the word in the Title and makes sure the bolding goes into the cache for when it's pulled up again.

Another update: I was able to get my results grouped by content type by installing and enabling Search API grouping and modifying my index's filter (admin/config/search/search\_api/index/node\_index/workflow) so that under "enabled processors" i checked grouping.

Once I did that, I also modified my search page so that my view mode was Live Result Search. This gave me access to the node content type in the js file I was modifying so that I could then parse the html string for the node-type and add an element to the live results list that was the content type label. Comment if my JS file interests you.
> 1 votes

---
Tags: views, search
---