# Question
Title: Is responsive.desktop.css for desktop & laptops design?
I am also using the Adaptive theme and same question raised. I checked their documentation, but they do not have point to point instruction.

Its css file has following file,

```
global.base.css
global.styles.css
responsive.custom.css

1. responsive.desktop.css
2. responsive.smalltouch.landscape.css
3. responsive.smalltouch.portrait.css
4. responsive.tablet.landscape.css
5. responsive.tablet.portrait.css

```
1. So, if we see that five different screen size listed in adaptive theme as above, **Do we have to use response.desktop.css for desktop/laptop design or just global.style.css?**
2. Another thing when we see the adaptive theme setting at admin/apperance/ATthem(sub)/setting.....we see three option Standard Layout, Tablet Layout and smalltouch layout....**So Tablet and Smalltouch are understable, they have their own css which means last 4 files, but for standard it is responsive.desktop.css?**

# Answer
> 2 votes
I'll quote from the adaptive theme documentation:

> * Global styles always load.
> * Responsive styles load in media queries.

So, you don't need to use **responsive.desktop.css** if you can declare all your styles in **global.style.css**. This is most probably the case if you don't follow the *"mobile first"* approach. But if you do, you probably have additional styles for devices larger than tablets, and that's when responsive.desktop.css comes into play. And of course this is also for laptops. It's the screen size that defines this, not the "wording"...

> **Global Stylesheets**
>
> These load by default. Using a mobile first approach you would only place styles that are going to be used for all devices. You need to be ruthless about this and cut down on what is going into these files - its very easy to assume you will use this or that everwhere, but in reality you are merely falling into the familiar routine of desktop first theming. On your average site these files will be rather small. If they start getting really big, and if you find yourself overriding stuff later in the responsive sheets - then you know you have a problem and need to re-think what you are doing.

\[...\]

> **Responsive Stylesheets**
>
> Adaptivetheme provides five responsive stylesheets - one for each breakpoint set in your theme settings. During development (see sidebar Development and Production Modes) each of these files is loaded in a link element and places the media query inside the link element itself, as opposed to inside the actual file as an @media declaration. **The media queries are those you set in the Appearance settings for each device type. Adaptivetheme automatically uses these so your styles will match to your layout breakpoints.**

And do not forget about this setting in the theme settings (css):

> **Mobile First or Desktop First** Adaptivetheme supports both mobile first and desktop first design approaches. This setting fundementally alters what CSS is loaded and how it is loaded. At the most basic level if you select Mobile first the Smartphone portrait layout will load as the default, if you select Desktop first the Standard layout will load as the default. Many other changes take place regarding loading of CSS for Internet Explorer, Responsive Gpanels and Panels as well.

---
Tags: theming
---


# Question
Title: Is there a way to add a dynamic URL token to images so that the move from local host to live doesn't require code change?
Is there a way to add a dynamic URL token to images so that the move from local host to live doesn't require code change?

When uploading images in content, the path changes form localhost to live, how can I have it consistent so the database can be exported without changes?

I would like to leave out the name of the site in the path

# Answer
Handling of the links in the field having a WYSIWYG editor, or any other long text field is a common issue when the site moves from one server (say dev) to other (say stage or production).
The links should be saved in such a way that they do not break.

**Pathologic** module does that for you.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.
> 5 votes

# Answer
AFAIK there's no such token. Even if it exists it will be hard to use: think in all places that the token should be used and token must be processed: inside content texts, link fields, even variables.

You should to use the same path for all enviroments.

If you really need different paths (for example, to hide a name) I suggest you to use a symlink in one of the environments: For example, if your local path is `/NAME/path` and live path is `/NAME-TO-HIDE/path` you can create a symlink that points from `/NAME/` to `/NAME-TO-HIDE/` in the live site. Nobody will see the NAME-TO-HIDE string but webserver will reach the right files thanks to the symlink.
> 2 votes

---
Tags: media
---


# Question
Title: How to change position & amount of fields in content type dynamically (means by editors)
I have a content-type, that can be structured like this:

* content-type A

+ title
    + summary

    ---
    + part one title
    + image
    + text

    ---
    + part two title
    + image
    + image
    + image
    + text
    + image

    ---
    + part three title
    + text
    + image
    + text

I have no control about the position and the amount of elements that can occur. I just have the types, like heading, text, image. Actually i have only fields or rather field-groups.

How can i give the editors the possibilty to move these fields or field groups inside the content type so they can determine the position? Is there something like nodequeue for fields?

Or should i alternatively cut the content-type to smaller pieces and organize it with nodequeue? I haven't worked with nodequeue before, is it possible to give a queue a menu-entry for example?

edit: Just before i asked my question i was watching a tutorial of Display Suite and if i understood correctly i can change the layout of a content-type globally. I'm looking for a solution that gives more control over each "article" created with a content-type. Maybe i was unprecise in my question...?

# Answer
If I get your question right you want both the number of parts, the combination within the parts and order within the parts to be different. This may be a little difficult to implement but definitely doable.

I am assuming that you are going to have only title, text and image type in each of these parts.

Using fieldset module create three field collections name weighted title(containing textfield with cardinality as one and weight\[integer value with cardinality as one\]), weighted image(image field and weight field) and weighted text(containing a text field and weight field)

Now create a field set named type, add weighted title, weighted image and weighted text as the fields in this fieldset. Make sure that you keep the cardinality of these fields as infinity. To make sure that it is not confusing, we will need to remove the drag and drop option withing the type fieldset.

The UI needs to be worked on to make it more intuitive. Without these enhancements to implement

part two title

image image image text image

We will have to do it as

Solution : title 1 image 2
image 3 image 4 image 6 text 4

and for

part three title

text image text

Solution : title 1 text 2 text 4 image 3

Hope you are not lost :P
> 2 votes

# Answer
If I get it right, you would like to let users set the position of the field-groups when they edit a node.

If that is what you want, then I would add a "position" field to every field group (hide it on the node display, but make it visible on the node edit page).
Then you can use the value of the "position" field in template files (node.tpl.php) to add classes to the field-groups for example. Then use these classes in CSS to position the field-groups.
> 1 votes

# Answer
This sounds like a problem better solved by multiple content types with role and/or user specific permissions. You can easily group content of various types with views, nodequeues, or taxonomy to name a few - any of which can of course be assigned to a menu item.

Otherwise, your best bet if you choose to stick with this is to use Panels as nodes, let editors create panels on the fly, arrange them how they want in predefined layouts, etc - but this is likely a training and maintenance nightmare.
> 0 votes

# Answer
With Panelizer you can can allow users to customize the position of a nodes fields and other content. The settings are specific for a node.

You can also setup one or more default variants with fields and other content (blocks etc) placed in regions. Users can then choose one of your default variants to be used for their node.

You can setup what content a user should be able to place in a node.
> 0 votes

# Answer
I recently found the Paragraphs module, which is another great way of accomplishing the tasks of my original question. It's like creating mini-content-types that you can add and move around. Fancy.
> 0 votes

---
Tags: 7, entities, nodes
---


# Question
Title: List all users who voted on a node with their ratings
I am using fivestar module for voting on nodes. For each node I would like to create a list of users who have voted on this node and the rating they have given. I am trying to do this using **Views 3** but I don't see any relationship which can give me this.

I tried doing this using both the node base table and user base table in Views.

Any ideas how I can go about this?

# Answer
> 3 votes
If you use node as your base table, you can add the relation `Content: Votes`. This will expose all Votes on that node. From there you can add the fields `Votes: User` and `Votes: Value` that can be displayed in a table or something.

---
Tags: views, rating
---


# Question
Title: Calendar - Adding relationship to contextual date filter
I would like to create an Calendar view of some interships for a certain student. But when I change the Contextual (Date) filter to use an relationship no results are shown in the calendar. When I construct a similar view page in a list instead of an calendar view mode, with identical filters, the results get returned.

Below an image of my attempt to get the relationship in a contextual date filter.

# Answer
> 0 votes
As J. Reynolds suggested some settings in the Calender Entities must be set. Changing the relationship fixed my problem.

---
Tags: views, datetime
---


# Question
Title: Get title field from another content type in exposed filter
I have two content types: `Project` and `Task`. `Project` has an node reference field of `Task` \- when you create a `Task`, you add reference to one of Project.

I need to create a view of `Project` and add the expose filter of title of the Task. I've selected both content type like Project and Task in a filter, I can see all of the fields from the Task content type EXCEPT Title. The only `Content: Title` that's available is the one from the Project nodes.

Need help.

# Answer
> 1 votes
You need to create views of one content type ie `Project` and add a `relationship` to your views which should say something like this Task `Content referenced from Project`. Require this relationship to exclude those projects which don't have tasks.

Now come to your filters and add title. In the setting now you will see use relationship dropdown. Select the relationship you added and you will get the required results.

---
Tags: views
---


# Question
Title: How to add an existing field to an user account?
I created a vocabulary in **Structure\>Taxonomy\>Add Vocabulary**. Then I add terms to it.

My Vocabulary fields look like this :

I want to display this vocabulary into accounts fields, I want to add existing fields but I can't find the term reference.

# Answer
> 3 votes
You have to use "Add new field" until you haven't used your term reference field for the Departements at least once before.

If have created this field once, you can reuse it for other content types.

# Answer
> 2 votes
You don't need to **Add an existing field**, you need to **Add a new field**

See the picture

Edit (thanks to NoSssweat comment): After you add this field, it will allow you to select your vocabulary.

# Answer
> 2 votes
You must be wondering why the fields are not appearing in the existing fields, although it has the same table field\_data\_field\_ and has some data in it. And creating another field will create another table which you think would be an overkill.

But if you could look closely at those field data tables which are linked to taxonomies and with nodes you would clearly see the difference in entity types.

So, Drupal can list those field in existing dropdown which has the same entity type as the one you are adding the field to. So in your case they are different. that is why it is not been listed there.

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


# Question
Title: I want to re-order the default fields on registration form
I want to change the order of the default fields on the user registration form like E-mail adress, password ect ...

I have no idea how to order these. (I'm a noob at Drupal by the way)

# Answer
> 5 votes
You will need to write a custom module for this, there is some good reading here. https://www.drupal.org/developing/modules/7.

You should create a folder like `/sites/modules/<module_name>`.

Create a `<module_name>.info` file

```
name = Custom order of fields
description = Customizes field orders
core = 7.x

```

Also create a `<module_name>.module` file an add the following code. The weights control the order, lower is higher on the page.

Please note that this might cause some problems with the field ordering if you add or change fields with the manage fields UI, so you might have to tweak the values a bit later on. You can go the the manage fields page and in the right top click `Show row weights`, this allows you to change the weights of the fields created with the UI.

```
function <module_name>_form_user_register_form_alter(&$form, &$form_state) {
  // Move the whole group.
  $form['account']['#weight'] = -10;

  // Move a single property within the group.
  $form['account']['name']['#weight'] = -10;
  $form['account']['mail']['#weight'] = 5;
  $form['account']['pass']['#weight'] = 15;

  // Move a value out of the group and order it.
  $form['name'] = $form['account']['name'];
  unset($form['account']['name']);
  $form['name']['#weight'] = -10;
}

```

Finally if you want the order to persist on the account edit page, copy all code again into a function named `<module_name>_form_user_account_form_alter(&$form, &$form_state)`

---
Tags: users
---


# Question
Title: How to add a view dependency to a Drupal 8 functional test
I'm working on a contrib module port to Drupal 8 and am currently adding additional test coverage (#2586125). The module provides both a field formatter and a views style plugin. I have good working test coverage for the field formatter and am now focusing on several views test cases (simpletest based on Drupal\simpletest\WebTestBase).

I have built a simple view, that uses my module's views style plugin along with a few other simple dependencies (some field storage conf, etc.), and exported this as a couple yml conf files. What's not clear to me however is the best practice way to load this bundled view during each functional test case.

A couple ideas come to mind:

**Method 1: Bundle View as Config in Test Module Dependency**

I Drupal 7 the standard method appeared to be to export a view and then bundle it inside a test-only module (with hook\_views\_default\_views()) which is installed as part of the test case setup. In D8 the exported view yml can just be placed inside a test module's config/install directory and then the module made a dependency inside the $modules property of the test class.

**Method 2: Add View Explicitly during Setup with ViewTestData::createTestViews()**

Some of the D8 views module's own tests use Drupal\views\Tests\ViewTestData::createTestViews(), along with a $testViews property array to directly enable a specific view inside the test setup. Something like:

```
  public static $modules = array('node', 'field', 'image', 'my_module', 'views');

  // Views used by this test.
  public static $testViews = array('my_test_view'); // Exported yml inside config/test_views of my_test_views_module

  /**
   * Define setup tasks.
   */
  public function setUp() {
    parent::setUp();
    ViewTestData::createTestViews(get_class($this), array('my_test_views_module'));
    // Additional setup...
  }

```

**Other Factors**

The way configuration is loaded and cached, and related dependencies are resolved during tests is slightly mysterious. I've noticed that test cases which also programmatically add configuration that a view depends on (using something like `$this->drupalCreateContentType()` for a content type config or `entity_create()` for field storage config) can be tricky. In these cases Method 1 could be problematic as the view may get loaded from conf before it's dependencies are programmatically prepared. This is leading me to think that Method 2 is potentially preferred, but all the factors are not yet clear.

# Answer
> 2 votes
Sometimes the code in core is not as pretty and consistent as we would like, which can make it a but tricky to find out what is best practice.

For views, it seems that this is pretty consistent. You should create a test module and have the view config yml files be placed inside a test\_views folder of the module.

There are examples of this in node and rest modules.

---
Tags: views, 8, testing, configuration
---


# Question
Title: Regarding term clarification in the database api
So I was making a custom block, and implemented the build() method.

```
public function build() {
    $result = $connection->db_query("SELECT n.title, u.uid, n.created    FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
        'type' => 'article',
    ));
    $content = '';
    if ($result) {
        while ($row = $result->fetchAssoc()) {
            $content .= '<li>' . $row['title'] . '</li>';
        }
    } else {
        $content .= 'No blog posts to show';
    }

    return array(
        '#markup' => '<ul>' . $content . '</ul>',
    );
}

```

So this is a pretty basic helloworld kind of example calling the database. But db\_query is deprecated with the following surgestion:

```
     * @deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get
     *   a database connection injected into your service from the container and
     *   call query() on it. E.g.
     *   $injected_database->query($query, $args, $options);

```

The surgestion seemed kind of spacey not entirely knowing all of the expressions but i eventually fixed it with the following code:

```
    $connection = \Drupal::database();
    $result = $connection->query("SELECT n.title, u.uid, n.created FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
        'type' => 'article',
    ));

```

to call the database.

My question is, \Drupal::database() is a static method, and i call it from inside of my own block, am i doing it wrong? or am i misunderstanding their meaning of dependency injection? if i had to do DI in other web programming i would find the DI container and configure it to give the database into my constructor or via a accessor method right?

Follow up questions is

1. What exactly constitutes my container?
2. What is "my service" referring to? my module maybe?

# Answer
Yes, you are doing it wrong by calling `\Drupal::database`.

Look at `Drupal\block_content\Plugin\Block\BlockContentBlock` in core as an example. The `create()` method gets the **services** and passes them to the `__construct()` method. That is the proper way.
> 3 votes

---
Tags: 8, blocks, services
---


title: Drush make SVN repository

text:
# Question
Title: Drush make SVN repository
I want to add a checkout of an SVN project in the .make file. However, the checkout only concerns a specific folder (new profile added). Has anyone made this before ?

edit : Folder and not file. My bad.

# Answer
> 1 votes
The following will do a svn export (unless you provide the --working-copy flag to drush) into `DRUPAL_ROOT/profiles/contrib/myprofile`

Drush make old-style syntax:

```
projects[myprofile][type] = profile
projects[myprofile][download][type] = svn
projects[myprofile][download][url] = svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile
; This would place the checkout into /profiles/contrib/myprofile
projects[myprofile][subdir] = "contrib"

```

Drush make YAML syntax:

```
projects:
    myprofile:
        type: "profile"
        download:
            type: svn
            url: "svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile"
        subdir: "contrib"

```

The drush make documentation is now located at http://www.drush.org/en/master/make.

---
Tags: drush, installation-profiles
---


title: Unable to add custom field to view

text:
# Question
Title: Unable to add custom field to view
I created a new content type called 'Newsletters' and created an image, text and link field.

I then created a view-block and when I try to insert my custom fields they do not show up in the fields list. I checked my permissions of the modules and my folders so that should not be the problem and there are no errors in my logs.

It's a bit confusing. Drupal 7.41 PHP 5.4.45 views 7.x-3.13

Any insight to why I can't insert my custom fields would be helpful.

# Answer
So it appears that the machine names for my custom content types can not be longer than 24 characters. As soon I shortened the names they inserted into the view as normal.

It's odd that I have never had that kind of problem before. But so it is...

Thank you for your efforts!! It is REALLY appreciated!
> 0 votes

---
Tags: 7, views, entities
---


title: Show a popup on home page once a day

text:
# Question
Title: Show a popup on home page once a day
I need a mechanismo to send a pop-up window to my visitor in my home page. But only once a day. How I can do it?

# Answer
Pop-Up Announcement

> The module provides a pop-up announcements in the overlay which will appear for the site visitor on the first, second and fifth visit to the site (customizable).
>
> You may create so much announcements, as You need and define where and when each from them will be appear.
>
> Very useful solution for interaction and communication with site visitors. You may post announcement about conferences, great news, "Tip of day" system, information about coming site maintenance, new goods, sales and much more.
> 1 votes

---
Tags: cookies
---


# Question
Title: Why is loading a field value from a group of nodes taking 30 seconds plus?
I have a D7 site with around 300,000 nodes. I am passing this function an array of 300-500 nids. Sometimes the function runs in under a second. Sometimes it takes 40 seconds or more! I can't figure out what causes the slow runs. How can I get the query consistent and fast?

```
function _load_field_values_for_nids($field_name, $nids)
{
  $field_info = field_info_field($field_name);
  $field_id = $field_info['id'];

  $map = array();
  $nodes_without_required_field = [];

  // Load up the properties from the node table.
  $sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
  $nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

  // Attach the single field to all nodes.
  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

  foreach ($nodes as $nid => $node) {

    if (isset($node->{$field_name}['und'])) {
      $map[$node->nid] = $node->{$field_name}['und'][0]['value'];
    } else {
      $nodes_without_required_field[] = $node->nid;
    }
  }

  $absent_count = count($nodes_without_required_field);
  if ($absent_count > 0) {
    watchdog("vwyw_load_fields", $absent_count." nodes did not have field, \"".$field_name."\" ");
  }

  return $map;
}

```

I noticed this SIX-SECOND query on the main /admin/content page (which took 12+seconds to load):

Here is the expanded XHProf output regarding that Count query:

I think this might be a mysql configuration issue rather that the particulars of a query. For instance, I think this query should run very quickly but it takes a second and a half:

The next time (same page load) it took 120ms and the time after that, 4.8sec!

**UPDATE**

Here is the XHProf output sorted by duration for a simple admin page that calls the function:

# Answer
> 4 votes
I'm guessing that the difference between the fast runs and the slow runs is caching. Within field\_attach\_load is a call to cache\_get\_multiple(). The field values can load from a cache which should be a lot faster: https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field\_attach\_load/7

To investigate further I recommend using devel module's query logger. It can show the amount of time spent within queries. If that is not sufficient you can use a profiler like XHProf or Blackfire to see exactly which function calls are taking the most time.

---
Tags: 7, entities
---


# Question
Title: Search boxes for individuals content types
I'm trying to have a search facility for different content types on their term pages.

So I have a view that lists all the terms that link through to a page that lists all the nodes that has that term. On this page I want to have a search box which can be used to search any node within it's content type. Now this is fine if I only needed to search one content type, using the Custom Search module I can tell Drupal to only search one content type.

However I need to do exactly the same as above but for a different content type. What would be the best way of implementing this?

# Answer
> 0 votes
Found an answer in the end if anyone else comes here searching for a solution. Turns out you could do what I wanted with the custom searech module I mentioned in my question. If you go into modules in the admin area there's also a custom search block module that comes with custom search that can be enabled. This gives you the ability to add as many blocks with different confiurations as you please. You then just go into blocks in structure and configure to your hearts content for each block then use those blocks where you want, job done! Just need to work out how to change the template now!

---
Tags: views, taxonomy-terms, search
---


# Question
Title: Getting the auto summary from a node body
I load an Article node with node\_load() and I'd like to get the summary for the Body field. I know that I can access it with `$node->body[$node->language][0]['summary']` but unless the user explicitly adds a Summary Body, then this field is empty.

I know that drupal will automatically generate a "trimmed body" if they don't add a Summary Body. How can I access that trimmed body?

EDIT:

I'm not interesting in render()ing the content, I just want the text. My module is generating a json feed for an external source.

# Answer
`node_view()` is appropriate when you need to render whole node or many of it's fields.
But sometimes you have to render the only field you need. It can be done with `field_view_field()` or `field_view_value()`:

```
$node = node_load($nid);
// Render array of body field.
$build_body = field_view_field('node', $node, 'body', 'teaser');
// Render it in common way.
echo render($build_body);

```

The interesting thing is that you can pass your own field formatter settings instead of view mode with the fourth parameter. Please, read API docs for more info.
> 11 votes

# Answer
A fairly detailed discussion on this topic is on Drupal 7 How to load a teaser programatically.

```
$teaser = render(node_view(node_load($nid), 'teaser'));
print $teaser['body'][0]['#markup'];

```
> 5 votes

# Answer
I wan't summary field always filled then I use something like this function (in custom module):

```
/**
 * Implements of hook_node_presave().
 */
function mymodule_node_presave($node) {
  // if is summary not empty we can continue
  if (isset($node->body[LANGUAGE_NONE][0]['summary']) && !empty($node->body[LANGUAGE_NONE][0]['summary'])) return;

  // we use module smart_trim to create smart trimmed variant of summary
  $build_body = field_view_field('node', $node, 'body', array(
    'type' => 'smart_trim_format',
    'settings' => array(
      'trim_length' => 8,
      'trim_type' => 'words',
      'trim_suffix' => '...',
      'more_link' => FALSE,
      'more_text' => 'Read more',
      'summary_handler' => 'full',
      'trim_options' => array(
        'text' => TRUE,
      ),
    ),
  ));

  // store created summary
  $node->body[LANGUAGE_NONE][0]['summary'] = $build_body[0]['#markup'];
}

```

Module smart\_trim is used as renderer for summary.
> 2 votes

# Answer
For anyone interested, here is the most minimal solution. I will use db\_select to execute the query rather than node\_load.

```
//first build the query
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'language'));
$query->join('field_data_body', 'body', 'body.entity_type=\'node\' && body.deleted=0 && body.entity_id=n.nid');
$query->addField('body', 'body_value', 'body_value');
$query->addField('body', 'body_summary', 'body_summary');
$query->addField('body', 'body_format', 'body_format');

//fetch a single item as an associative array
$item = $query->execute()->fetchAssoc();

//If an explicit summary has not been provided, we generate it here
if (empty($item['body_summary'])) {
    $summary = check_markup($item['body_value'], $item['body_format'], $item['language']);
    $item['body_summary'] = text_summary($summary, $item['body_format']);
}

```
> 2 votes

---
Tags: 7, nodes
---


title: Add image upload to theme configuration

text:
# Question
Title: Add image upload to theme configuration
I'm trying to add an image upload to the theme settings in a theme I made. The image upload field does appear, however nothing actually gets uploaded and the image never get's saved.

in theme-settings.php I have the function

```
function mytheme_form_system_theme_settings_alter(&$form, $form_state, $form_id = NULL) {
    $form['banner']['banner_image'] = array(
        '#type' => 'file',
        '#title' => t('Banner Image'),
        '#description' => t('Upload a banner image'),
        '#default_value' => theme_get_setting('banner_image'),
    );
}

```

The image upload field does appear, but when choosing the file and clicking 'save configuration' nothing actually gets saved.

# Answer
> 2 votes
The problem with your code is that it needs a submission handler to handle the uploaded file. Using #file as form element type is fine, since that is also done from Drupal core in `system_theme_settings()`.

```
$form['logo']['settings']['logo_path'] = array(
  '#type' => 'textfield',
  '#title' => t('Path to custom logo'),
  '#description' => t('The path to the file you would like to use as your logo file instead of the default logo.'),
  '#default_value' => theme_get_setting('logo_path', $key),
);
$form['logo']['settings']['logo_upload'] = array(
  '#type' => 'file',
  '#title' => t('Upload logo image'),
  '#maxlength' => 40,
  '#description' => t("If you don't have direct file access to the server, use this field to upload your logo.")
);

```

The form submission handler (`system_theme_settings_submit()`) then handles the uploaded file with the following code.

```
  // Exclude unnecessary elements before saving.
  form_state_values_clean($form_state);

  $values = $form_state['values'];

  // Extract the name of the theme from the submitted form values, then remove
  // it from the array so that it is not saved as part of the variable.
  $key = $values['var'];
  unset($values['var']);

  // If the user uploaded a new logo or favicon, save it to a permanent location
  // and use it in place of the default theme-provided file.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

```

You could use similar code in a form submission handler, but as described in When theme-settings.php has a managed\_file field and a submit callback, " Call to undefined function" error is thrown. such form aubmission handler would not be found because Drupal doesn't load the theme-settings.php file automatically.
If you get around that, and you are able to make Drupal automatically load the file containing the submission handler, you could use the following code in your submission handler.

```
  if (!empty($form_state['values']['banner_image'])) {
    $file = $form_state['values']['banner_image'];
    unset($form_state['values']['banner_image']);
    $filename = file_unmanaged_copy($file->uri);
    $form_state['values']['banner_image_path'] = $filename;
  }

```

With `theme_get_setting('banner_image_path')` you will then get the path of the last uploaded file.
I would do as Drupal does, and add a textfield for the path of the last uploaded file.

# Answer
> 0 votes
A `file` element just gets the data to your server - you need to do something with it if you want that data to persist.

Drupal has you covered with the `managed_file` element type, though:

```
$form['banner']['banner_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Banner Image'),
    '#description' => t('Upload a banner image'),
    '#default_value' => theme_get_setting('banner_image'),
    '#destination' => 'public://foo/bar',
);

```

Note that managed files are marked as temporary by default (so that orphan files can eventually be deleted if the associated form isn't actually submitted etc), so there's a bit of work to do in a submit handler:

```
$file = file_load($form_state['values']['banner_image']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

```

---
Tags: 7, theming
---


title: Translate to specified language

text:
# Question
Title: Translate to specified language
I know I can translate to current website language with t() function, but I need translate to specified (not current) language, my site has three languages and I want get English of some of the worlds in some template files when current language is French. **How can I get translate of string according to specified language instead of current language?**

# Answer
> 1 votes
According to t() documentation you can pass specified language it `t()` function.

As Example below code return French translate of `language` string without consider current site language.

```
  $fr_value = t('language', array(), array('langcode' => 'fr'));

```

---
Tags: 7, i18n-l10n
---


title: How do I get last inserted record ID?

text:
# Question
Title: How do I get last inserted record ID?
I want to get the record ID for the last inserted row in a database table. I am trying to use `db_last_insert_id()`, but it is throwing an exception.

> Call to undefined function `db_last_insert_id()`

How do I get last inserted record ID?

# Answer
In Drupal 6 you would use code similar to the following.

```
db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id('mytable', 'id_fieldname');

```

The Drupal 7 equivalent code is the following.

```
$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();

```
> 15 votes

# Answer
If you don't control the particular insert query yourself, you could always use a plain old SQL query:

```
$last_id = db_query('SELECT MAX(id_col) FROM {table}')->fetchField();

```
> 11 votes

# Answer
```
  $id = db_insert('mytable')
       ->fields(array(
       'intvar' => 5,
       'stringvar' => 'hello world',
       'floatvar' => 3.14,
       ))
       ->execute();

```

$id contains the last inserted id of the table. just do echo $id.
> 0 votes

# Answer
If fore some reason you need to get a fields value before inserting it this is a work around to do it with.

```
function _get_id($tableName, $fieldName) {

    $select = db_select($tableName, 'o');
    $fields = array(
        $fieldName,
    );
    $select->fields('o', $fields);
    $result = $select->orderBy($fieldName)->range(0,1)->execute()->fetchAll();
    return $result[0];
}

$lastId = _get_id('table_name' , 'uid');

```
> 0 votes

# Answer
A crude trick, but it works:

```
$myInsertID = db_query("INSERT INTO {fred} (fld1,fld2) VALUES ('a','b')", array(), array('return' => Database::RETURN_INSERT_ID));

```

or

```
$myInsertID = db_query("INSERT INTO {fred} (fld1,fld2) VALUES ('%s','%s')", array('a','b'), array('return' => Database::RETURN_INSERT_ID));

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to assign permissions to roles programmatically?
I have some permissions that I would like to assign to some roles programmatically for easier installation.

Because I'm installing the module and creating both permission and roles, I don't have the role id's, where I want to set the permissions. So far I have only found ways to **assign roles programmatically** that need the role ID.

I wonder if I somehow could look up the roles with their name (string), retrieve the role ID and then assign permission. It just doesn't feel right.

# Answer
Features module does this quite nicely, allowing you to export roles and permissions (and lots of other stuff) in one fell swoop:

http://drupal.org/project/features

But if you want to roll your own check out Permissions API:

http://drupal.org/project/permissions\_api
> 1 votes

# Answer
Features is pretty handy for stuff like this. However, if you do need to create roles and add permissions programmatically, you don't have to go digging through the database on your own.

When you create a new user role with `user_role_save()`, it will update the object you passed in with the new user role id that was assigned. You can see an example of this in the `standard_install()` function in the Standard installation profile.

```
$admin_role = new stdClass();
$admin_role->name = 'administrator';
...
user_role_save($admin_role);
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

```

This example shows that you can create a new user role, then access its `rid` property, which was filled in by `user_role_save()`. It also shows how to add permissions to that role with `user_role_grant_permissions()`. In this case, it's granting the 'administrator' role all available permissions.

If you need to get the id of a user role created by someone else, you can use `user_role_load_by_name()` to get the object for that user role. Then you just grab the id with `$role->rid`.
> 26 votes

# Answer
I'd like to add a code example that is closer to the original question on how to assign permissions to existing roles programmatically.

You can look up the roles with their name, retrieve the role ID and then assign permissions as follows (for example in a hook\_update implementation):

```
function custommodule_update_7001() {
  $permissions = array('view my custom entity');
  foreach(array('anonymous user', 'authenticated user') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

```
> 21 votes

---
Tags: 7, users
---


title: Migrate module, long text issue

text:
# Question
Title: Migrate module, long text issue
I'm trying to migrate rows from a Joomla K2 table.

The issue happens when I add the 'fulltext' field to the field list on my select inside my migration class. This field is a medium text field with html inside. The error only happens when I put this field in the query.

The error is like so:

> Migration failed with source plugin exception: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fulltext FROM j3\_k2\_items n WHERE (catid IN ('43', '45', '46', '51', '68', '7' at line 1,

I have set `$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));` but it didn't help.

Any ideas? I don't know what to do.

# Answer
> 1 votes
Ok, just found the problem.

I was using this select:

```
$query = $this->getConnection()->select('j3_k2_items', 'n')
  ->fields('n', array('id', 'title', 'fulltext'))
  ->condition('catid', array(43, 45, 46, 51, 68, 72, 109, 117),'IN');

```

but the array inside the fields was the problem. When I removed it:

```
$query = $this->getConnection()->select('j3_k2_items', 'n')
  ->fields('n')
  ->condition('catid', array(43, 45, 46, 51, 68, 72, 109, 117),'IN');

```

Which was the same as doing a "SELECT \*" the error gone and the migration worked!

---
Tags: migrations
---


# Question
Title: How to create eshop for product hiring counting price per day
Currently I'm working on specific project which is product hiring and price per day depends on hiring interval. It means 2 days hiring for certain product the per day price differs from 5 days hiring. Also in this case instead of product quantity I'm using days. My question is how can I organize above mentioned structure using commerce?

# Answer
> 0 votes
Look at the Commerce Price Table module which supports the following output for a table of prices/quantity:

> contrib project that allows to have a secondary price field that considers the quantity for displaying and using the prices. It also provides a field formatter to display the price/quantity values as a table.

---
Tags: commerce
---


# Question
Title: How to display a View Block based on number of characters in Body?
I currently have a view that creates an "About the Author" box that pulls information from the user's profile and displays the appropriate author box based on the author of the node (content). I only want to display it on nodes that have a minimum amount of characters in the body of the node. (It currently displays for all nodes the block is enabled for.)

The desired result is that long pieces of content have an "About the Author" box, while short pieces of content do not.

The problem I am having is that when I select the filter criteria for the view, the body field for the node is not listed, so I cannot filter off of it. And I do not see any other way to test how long the content is, in order to determine whether the "About the Author" block should display or not.

How can I make it so the Author Box only appears on long content (i.e. content body \> 1000 characters)?

# Answer
You can use the Views Conditional module. Configure your field to ***Exclude from display*** and ***Apply***

Then add the ***Views: Views Conditional*** field and configure like this (but with your condition) and ***Apply***

**EDIT (after No Sssweat comment)**:You can combine in your view the Views Field View module to embed a view (your block if you want) as a field in the view.
> 4 votes

---
Tags: 7, views, blocks
---


# Question
Title: boost only for front page with cache enabled for other pages?
I know that Boost module works only when drupal cache is disabled.

But is there any way to turn on Boost module for front page only, with cache enabled for other pages.

# Answer
> 0 votes
All the node pages either can be added to exception list with Boost or front page.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.

---
Tags: 7, performance, caching
---


# Question
Title: How to get Node IDs of nodes whose titles contain a certain string?
I'm trying to get a list of nodes whose titles contain a given string, in this case the term name of a term attached to another node.

Based on other answers I've found online, I've thought this could work:

```
$sql = 'SELECT title FROM {node} WHERE title LIKE :title';
$result = db_query($sql, array(':title' => '%' . db_like($term->name)));

```

That's giving me a response but it's all empty, which makes no sense.

Here's what the response looks like:

```
DatabaseStatementBase Object
(
[dbh] => DatabaseConnection_mysql Object
    (
        [needsCleanup:protected] =>
        [target:protected] => default
        [key:protected] => default
        [logger:protected] =>
        [transactionLayers:protected] => Array
            (
            )

        [driverClasses:protected] => Array
            (
                [SelectQuery] => SelectQuery
                [MergeQuery] => MergeQuery
                [UpdateQuery] => UpdateQuery
                [DatabaseSchema] => DatabaseSchema_mysql
            )

        [statementClass:protected] => DatabaseStatementBase
        [transactionSupport:protected] => 1
        [transactionalDDLSupport:protected] =>
        [temporaryNameIndex:protected] => 0
        [connectionOptions:protected] => Array
            (
                STUFF
                    (
                        [default] =>
                    )

            )

        [schema:protected] => DatabaseSchema_mysql Object
            (
                [connection:protected] => DatabaseConnection_mysql Object
*RECURSION*
                [placeholder:protected] => 0
                [defaultSchema:protected] => public
                [uniqueIdentifier:protected] => 5670ef6385b8e5.94304345
            )

        [prefixes:protected] => Array
            (
                [default] =>
            )

        [prefixSearch:protected] => Array
            (
                [0] => {
                [1] => }
            )

        [prefixReplace:protected] => Array
            (
                [0] =>
                [1] =>
            )

    )

[queryString] => SELECT * FROM node WHERE title LIKE :title
)

```

Do I need to do something like this using CONTAINS instead?

```
$sql = 'SELECT title FROM {node} WHERE CONTAINS(title, :title)';
$result = db_query($sql, array(':title' => '%' . db_like($term->name)));

```

# Answer
> 1 votes
You need iterate over the node collection, you can use this code to do so:

```
$sql = 'SELECT title FROM {node} WHERE title LIKE :title';
$result = db_query($sql, array(':title' => '%' . $term->name . '%'));

foreach($result as $node) {
    //dpm($node);
    //$node is your object
    echo $node->title . '<br>';
}

```

**Edit:** If you want only specifics content types use this:

```
$sql = "SELECT title FROM {node} WHERE title LIKE :title AND type = 'your_content_type'";

```

---
Tags: nodes, database
---


# Question
Title: How to store a single array value into a session variable?
I have

```
Array ( [0] => cid [1] => TN201501HP )

```

Now I want to store "TN201501HP" into some session variable. How to store this value to a session variable?

# Answer
When you store array(object) in variable use serialize function. and unserialized unserialize So

```
session_start();
$arr=array(0 => cid ,1 => TN201501HP);
$_SESSION['myvar'] =serialize($arr);
$myarr= unserialize($_SESSION['myvar']);
echo $myarr[1];

```

and if you only want one variable in array try

```
session_start();
$_SESSION['myvar'] = $array[1];
echo $_SESSION['myvar'];

```
> 1 votes

# Answer
```
<?php
//If you want store the value in a session, you need first start the session
session_start();
//I suposse that your array is named $array,
//then if you want get the position 1 use the following line
$_SESSION['var'] = $array[1];
//checking the stored value
echo $_SESSION['var'];

?>

```

Output:

> TN201501HP
> 1 votes

---
Tags: external-scripts
---


# Question
Title: What is the fastest way to get node title from nid?
Say I have an nid (or a lot of them). Would it be faster to load the node to access get the title, or do the very simple db\_query required to get the node title?

# Answer
You said fastest.

If you can compromise two things, this should be the fastest one. Now, note that you have to compromise:

* If you are only trying to get the node `title`, and if you are sure that there are no other `hook_node_load` implementations (basically module handlers that would alter the node load at the time they are loaded), you can skip using the `node_load()` or `node_load_multiple()` functions and go for this solution.
* When loading a node from the database, it's advised that you use a query tag to make sure that the user has access to those nodes. If you don't use any node access modules, you can go down for this solution.

With both above points in mind you can uses something like this:

```
function MYMODULE_node_get_title_fast(array $nids) {
  $titles = &drupal_static(__FUNCTION__, array());
  $return = array();
  $unavailable = array();
  foreach ($nids as $nid) {
    // Lookup static cache of self.
    if (array_key_exists($nid, $titles)) {
      $return[$nid] = $titles[$nid];
    }
    else { // Set NULL, so unavailable nodes will have NULL as their return value.
      $unavailable[$nid] = NULL;
    }
  }

  if ($unavailable) {
    $results = db_query("SELECT nid, title FROM {node} WHERE nid IN (:nids)", array(':nids' => array_keys($unavailable)))->fetchAllKeyed(0, 1);
    if ($results) {
      $return = $results + $unavailable;
      $titles = $return + $titles;
    }
  }

  return $return;
}

```

You can pass an array of node IDs, and the above function will return their titles without the overhead of `node_load`, `field_attach`, or `entity_load` overheads. It also skips node access checks, so do not use this in sites that you want any sort of access restrictions.

Usage example:

```
 $titles = MYMODULE_node_get_title_fast(array(256, 258, 54898));

```

You would return an array, with all given array values as keys, and the title as their value. `NULL` if the node is unavailable.
> 7 votes

# Answer
Use node\_load\_multiple to get nodes with your set of nids.

From the documentation page:

> This function should be used whenever you need to load more than one node from the database. Nodes are loaded into memory and will not require database access if loaded again during the same page request.
> 5 votes

# Answer
the better way to do this is:

```
      <?php
         $node_title = node_load($nid)->title;
    ?>

```

and i think that if there is a way to do it with out direct query to DB. then you must go to that way.as in most cases these ways are perfect,easy and optimized.
> 3 votes

# Answer
Loading whole node data for just a title is overkill, if you apply entity\_load() or node\_load() it involved a bunch of joins to render the data from fields tables which obviously is not a good solution. I would rather suggest to apply `db_query("SELECT title from {node} where nid = :nid and status and status = :status" , array(':nid' => <Your nid>, ':status' => 1 ( //for published nodes)))`
> 2 votes

# Answer
The Easiest way to get it using node\_load function.very simple and clean ;)

```
$node=node_load($nid);
// So $node->title contatile title

```

Learn this useful function.

> node\_load($nid = NULL, $vid = NULL, $reset = FALSE)
>
> Loads a node object from the database. Parameters
>
> $nid: The node ID.
>
> $vid: The revision ID.
>
> $reset: Whether to reset the node\_load\_multiple cache.

**Also** if you want get fetchField by query use db\_select

```
$result = db_select('node', 'n')
->fields('title')
->condition('nid', $nid,'=')
->condition('status', 0,'>')
->execute()
->fetchAssoc();

```

Also you can get it by db\_query\`

```
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.nid = :nid', array(':uid' => $nid));

```

**But you can try it by yourself speed test of getting one node with `db_select` `db_query` is very tiny.**

> Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db\_select() instead.
> 0 votes

# Answer
Also if you want get it by query use db\_select With fetchField

$result = db\_select('node', 'n')

-\>fields('title')

-\>condition('nid', $nid,'=')

-\>condition('status', 0,'\>')

-\>execute()

-\>fetchField();
> 0 votes

---
Tags: 7, nodes, database, performance
---


# Question
Title: How to get a term from the translated term name?
I have a translated taxonomy term whose name is *Autos Y Motores* (Spanish). How can I get the taxonomy term object from it?

If the term name were in English, I would use `taxonomy_get_term_by_name('Vehicles & Motors')` to get the taxonomy term object.

How can I do with a translated taxonomy term name?

# Answer
> 4 votes
I don't find any function in Drupal which can translate the translated string into actual string. So, what I did was hit db to get the actual string and hence the string.

```
    $translated = 'Autos Y Motores';
    $query = db_select('locales_target', 'lt');
    $query
      ->condition('lt.translation', $target)
      ->fields('lt', array('translation'))
      ->fields('ls', array('source'))
      ->join('locales_source', 'ls', 'ls.lid=lt.lid');
    $results = $query->execute()->fetchAll();

```

# Answer
> 5 votes
You can try to translate it before pass it to `taxonomy_get_term_by_name` function, try some thing like

```
$string= 'De Lema'; // string in not default site language I suppose in French
$default_lang_short = 'un'; // I supposes you default site language is english change it to your default
$en_value = t($string, array(), array('langcode' => $default_lang_short));
taxonomy_get_term_by_name($en_value);

```

# Answer
> 3 votes
If you have this set:

* ES: *Autos Y Motores*
* EN: *Vehicles & Motors*

Use this code:

```
 $term = taxonomy_get_term_by_name('Autos Y Motores');
 //getting the term object
 $term = array_values($term)[0];
 //searching the translation
 $translated_term = i18n_taxonomy_term_get_translation($term, 'en');
 //$translated_term is your term in English
 echo $translated_term->name;

```

Output:

> Vehicles & Motors

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: How do I keep unique form id for ajaxified form?
I have a form(which is extending the FormBase class) that requires entity as argument(but I am not manipulating with this entity so that's why I am not using the EntityForm which is irrelevant to this issue but just FYI). The form uses data from the entity to build the form id. I am instantiating the form as object and I am keeping the entity as property on the form.

Due to the fact that I have multiple such forms on a single page I need the form id to be unique and matching the provided entity object to avoid collision of submitted values. In Drupal 7 this was taken care of via hook\_forms().

Now I want to ajaxify this form but ***there is an issue that after the first submission the entity object is no longer available to the form. I have stored the data I need in the $form\_state but I cannot access this in the getFormId() method***.

So I have made the form id non-unique and each form instance has the same id. I have tried to get around this issue by setting the form id in the form array itself as #id attribute but that did not helped.

So my question is how to have an ajaxified form with unique form id that is based on data from provided argument to the form?

---

This is how I am invoking the form(in lazy loader):

```
$entity = $this->entityManager->getStorage($entity_type)->load($entity_id);
$form = new MyForm($entity);
return $this->formBuilder->getForm($form);

```

and the form itself:

```
class MyForm extends FormBase {

  private $entity;

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

  public function getFormId() {
    return 'my_form_' . $this->entity->getEntityTypeId() . '_' . $this->entity->id();
  }

}

```

# Answer
> 1 votes
So the issue was that I was calling the getFormId() in the form itself to build the html id for the ajax wrapper. For rebuilt form the entity object that I provided as argument to constructor was not available anymore so calling this method caused it to look for that entity object to extract data to build the id from and since it no longer exists it caused this issue.

# Answer
> 1 votes
I had a similar issue in D7 and finally solved it by wrapping all form elements with a `'#type' => 'container'` element which got prefixed/suffixed with a div holding a unique `drupal_html_id($id)`.

Then in the AJAX callback (added to a `'#type' => 'select'` element) I returned the whole container instead of just returning the one element I needed ajaxified. That way `drupal_html_id($id)` ensured the id being unique for every single AJAX action.

---
Tags: forms, 8, ajax
---


title: The styled image is not displaying

text:
# Question
Title: The styled image is not displaying
I have created a thumbnail like image style in Drupal 7 (glossy\_footer\_sublogo).Also i have coded a module that has a block to display the 'logo.png' file that comes with my theme and converted by 'glossy\_footer\_sublogo' style. after enabling the block and clearing cache no image is displayed although the 'sites/all/themes/glossy/' path created in my style directory. Following are the codes that i used to display the block:

```
/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  switch ($delta) {
    case 'glossy_footer_sublogo':
            $img_url = 'public://sites/all/themes/glossy/logo.png';
            $style = 'footer_sublogo';

            return array(
                'subject' => '',
                'content' => "<img src=" . image_style_url($style, $img_url) . ">",
            );
      break;
  }
}

```

Can anyone point me to what is the problem? Thanks!

# Answer
If you go to `admin/config/media/file-system` what is your public path set as?

If your public path is set as `sites/default/files` then I think your code is generating the following link:

> http://yourdomain/sites/default/files/sites/all/themes/glossy/logo.png

Try changing your $img\_url to the following

> $img\_url = drupal\_get\_path('theme', 'glossy') . '/logo.png';

On another note, is the block rendering at all (just without the image)? Your implementation of hook\_block\_view looks incorrect.

I think it should be more like the following:

```
/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  $block = array();

    switch ($delta) {
      case 'glossy_footer_sublogo':
              $img_url = 'public://sites/all/themes/glossy/logo.png';
              $style = 'footer_sublogo';

              $block['subject'] = ''
              $block['content'] = "<img src=" . image_style_url($style, $img_url) . ">",

              );
       break;
    }

  return $block
}

```

*Edit*

Change $img\_url as I previously mentioned, but rewrite your block content as follows:

```
$block['content'] = '<img src="' . image_style_url($style, $img_url) . '" />';

```

There aren't any quote marks around the image URL that is being returned by the function.
> 2 votes

# Answer
The `public://` stream wrapper maps to your site's public files directory: trying to access themes outside of it isn't going to work. That is, this will never work:

```
$img_url = 'public://sites/all/themes/glossy/logo.png';

```

Because it gets expanded to:

```
$img_url = DRUPAL_ROOT . '/sites/<sitename>/files/sites/all/themes/glossy/logo.png';

```

Instead, to build the correct path to your theme's file, you need to use `drupal_get_path()` like Chapabu mentioned:

```
$img_url = drupal_get_path('theme', 'glossy') . '/logo.png';

```

However, as you noted in the comments, `image_style_url()` requires a stream wrapper URL, and more specifically, a `public://` stream wrapper URL.

### Creating a styled version of your theme's logo by copying the logo

So, the easiest way to do what you want is to copy your theme's logo to your public files directory and use `image_style_url()` that way:

```
$img_path = file_unmanaged_copy($img_url, 'public://', FILE_EXISTS_REPLACE);
$block['content'] = theme('image', array('path' => image_style_url($style, $img_path)));

```

### Creating a styled version of your theme's logo without copying the logo

Alternatively, you could manually create the derivative using `image_style_create_derivative()`:

```
$img_destination = 'public://logo-' . $style . '.png';
image_style_create_derivative($style, $img_url, $img_destination);

```

Then reference the file's URL by calling `file_stream_wrapper_get_instance_by_uri()`:

```
$image = file_stream_wrapper_get_instance_by_uri($img_destination);
$block['content'] = theme('image', array('path' => $image->getExternalUrl()));

```

In either case, you want to make sure at some point you add some logic to deal with repeatedly copying the logo (or generating the derivative) every time someone accesses the block uncached.
> 1 votes

# Answer
Use below two function to create images based on image style.

```
//new_style is image style
//image_uri is public path of existing image
 $new_image_destination=image_style_path('new_style',$image_uri);
    $new_image_path=image_style_create_derivative(image_style_load('new_style'),$image_uri,$new_image_destination);

//use drupal_realpath to get public uri as below
//$new_image_public_uri= drupal_realpath($new_image_destination);

```
> 0 votes

---
Tags: 7, theming, media
---


title: How to check entity is already created?

text:
# Question
Title: How to check entity is already created?
I have the code that create entity named "Victory" in entity type, my problem is how to prevent user creates the entity with the same name again.

```
function commerce_services_store_create($data, $flatten_fields) {
  $storeName = $data['store_name'];
  $status = 1;

  $entityType = "fruit_store";       //entity type name Fruit Store
  $entity = entity_create($entityType, array('type' => "store")); //bundle store
  $entityWrapper= entity_metadata_wrapper($entityType,$entity);  // create entity named "Victory"
  $entityWrapper->title->set($storeName);
  $entityWrapper->save();

  $store_id = $entityWrapper->id-> value();
  if($store_id != null){
    $reply= (array('status' => $status,'result' =>"Your store name ". $storeName. " Store id is ". $store_id));
  }else{
    $status = 0;
    $result = "Can't create store.";
    $reply = $reply= array('status' => $status,'result' => $result);
  }

  return $reply;

}

```

# Answer
> 2 votes
Just like validating the user email in any system you check if its already exists or not, in your case we need to check that we have no entity with the same attribute value exists:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'Fruit_Store')
  ->entityCondition('bundle', 'store')
  // this is a condition for the entity field values
  ->fieldCondition('field_title', 'value', 'spotlight', '=');

$result = $query->execute();

if (!empty($result['Fruit_Store'])) {
  // entity already exsits.
}
else{
  // add new entity
}

```

you can find more information about EntityFieldQuery in this page:

https://www.drupal.org/node/1343708

# Answer
> 1 votes
You can validate the entity type with following:

entity\_get\_property\_info($entity\_type = NULL)

Reference:

http://www.drupalcontrib.org/api/drupal/contributions%21entity%21includes%21entity.property.inc/function/entity\_get\_property\_info/7

Updated: Check the below example code for the existing entity

```
  try {
    // account for user entity exists error
    if (!($args['type'] == 'user' && $account = user_load_by_name($values['name']))) {
      $data = entity_property_values_create_entity($args['type'], $values);
    } else {
            $data = entity_metadata_wrapper('user', $account);
    }
    return array('entity_created' => $data);
    }
catch (EntityMetadataWrapperException $e) {
    throw new RulesEvaluationException('Unable to create entity @type": ' . $e->getMessage(), array('@type' => $args['type']), $element);
}

```

---
Tags: 7, entities
---


title: How do I create a simple table?

text:
# Question
Title: How do I create a simple table?
I am working on a module where I need to display content in a table. Though I have created a simple table already, I need to know how to use `theme()`, as the function cannot be called directly.

Basically, What is the equivalent of the following line, which was perfectly fine in Drupal 7?

```
return theme(table,array(header => '$header', rows => '$rows'));

```

# Answer
> 9 votes
As reported in New render element #type 'table' and theme() renamed to \_theme() and should not be called directly, the equivalent of `$table = theme('table', array('header' => $header, 'rows' => $rows))` for Drupal 8 is the following.

```
$form['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

```

(Replace `$form` with the variable containing the rendering array.)

# Answer
> 5 votes
Use

```
return [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

```

---
Tags: theming, 8
---


# Question
Title: specify $form elements to be excluded from display?
I want to hide certain elements in form using form\_alter or a template file. I have read somewhere that in Drupal 7 , we can specify $form elements so it will not display in form, but I can't remember! Not unset() but some other function!

# Answer
> 31 votes
Using `unset()` isn't a good solution for forms (as I think you know), as you never know what submit/validate handlers might be expecting the unset element to exist when they're processed. This can lead to unwanted errors.

There are three methods you can safely use to 'hide' a form element

* Use `'#type' => 'value'` on the element, which will have the effect that the value for the element will still be passed through to the submit/validate functions with its `#value` as normal. This is my preferred method.
* Use `'#access' => FALSE` on the element to denote it should not be outputted to the screen.
* Use `'#type' => 'hidden'` as Bart has suggested (although use of this depends on your use case; I imagine if you're trying to hide the value of a form element you don't want to output it in the form as a hidden input).

# Answer
> 4 votes
If you're using a template file you can hide stuff using hide().

If you want to hide a form element in `hook_form_alter`, `unset()` might be your best option.

If it's just to store a value you could use '#type' =\> 'hidden' as well.

# Answer
> 4 votes
I've found using #access to false can break some forms if used on submit buttons or similar. In those cases i've just used CSS to hide elements:

```
$form['basic']['submit']['#attributes']['class'][] = 'element-hidden';

```

Just another option.

---
Tags: 7, hooks, forms, theming
---


# Question
Title: Where does drush look for the path of the mysql socket (on MAMP)?
After upgrading from `drush 6.5.0` to `8.0.1-dev` through **brew**, the drush terminal command returns the popular

> 'PDOException: SQLSTATE\[HY000\] \[2002\]' error.

The only way to make it work is to add the unix\_socket line to my Drupal `settings.php` files for all my projects:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site',
      'username' => 'user',
      'password' => 'pass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
    ),
  ),
);

```

Even if I use `/var/mysql/mysql.sock`, it will work, because I have a symlink up:

```
lrwxr-xr-x  1 root  wheel    39B Mar 11  2015 /var/mysql/mysql.sock -> /Applications/MAMP/tmp/mysql/mysql.sock

```

But that is exactly the thing I don't understand. And I would like to configure it at one point so I don't have to edit all the current and upcoming project's `settings.php` files.

So my question is: **Where does drush look for the path of the mysql socket (on MAMP)?**

If it's through the `php.ini`, it should be correct too (/Applications/MAMP/bin/php/php5.6.10/conf/php.ini):

```
mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock

```

Currently, my `.bash_profile` contains no alias or export related to this issue because it worked fine with my previous drush installation.

# Answer
> 5 votes
First of all, check which `php` and `php.ini` file is used by `drush`:

```
$ drush status --full
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  root
 Database name                   :  drupal7
 Drupal bootstrap                :  Successful
 Drupal user                     :
 PHP executable                  :  /usr/local/opt/php56/bin/php
 PHP configuration               :  /usr/local/etc/php/5.6/php.ini

```

Then edit its default MySQL socket name for local db connects:

```
pdo_mysql.default_socket=/path/to/mysql.sock

```

as by default it points to `/tmp/mysql.sock` unless PHP was configured with different (`--with-mysql-sock`).

Check by:

```
$ php -i | grep ^pdo_mysql.default_socket
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

```

So probably that's why `/var/mysql/mysql.sock` didn't work, as it was looking for `/tmp/mysql.sock` instead.

Then the symbolic link should work as expected.

If `drush` is using wrong instance of PHP, then add it into `PATH` (as you did) or specify with `--php=</path/to/file>`, so the right `php.ini` would be loaded.

Alternatively specify `unix_socket` in your settings file (as you already did).

# Answer
> 0 votes
Found the solution ...

```
drush status

```

shows the PHP executable path was the OSX native one, which was then symlinked to a PHP installed by brew

adding the following line to ~/.bash\_profile

```
export PATH="/Applications/MAMP/bin/php/php5.6.10/bin:/Applications/MAMP/Library/bin:$PATH"

```

made drush look up into the correct php.ini file

but to me, it is still a mystery why the symlink

```
lrwxr-xr-x  1 root  wheel    39B Mar 11  2015 /var/mysql/mysql.sock -> /Applications/MAMP/tmp/mysql/mysql.sock

```

did not do the trick

---
Tags: 8, drush
---


# Question
Title: Webservices to create (Register) a new user
I am planning to write client apps which connects to Drupal 7. I like to create new users through the app, have come across some literatures but I am not sure if the approach is secure and also whether it considers all possible use-cases.

The first link which I came across is this: https://www.drupal.org/node/1514312

I was able to configure endpoint and successfully post + create user. However, the problem with above approach is, it is not secure because any client app with the POST URL to create user can successfully register a user in the website.

I then followed this link: https://www.drupal.org/node/1871498 through which I created a OAuth authentication context. Below are the configuration details:

```
OAuth Context:
Context Title: App Name
Signature Method: HMAC-SHA1

```

The Service configuration:

```
Endpoint: create_new_user
Authentication:
OAuth Context -> Context created above
Default required authentication -> Consumer key (2 legged OAuth Authentication)
Resources ->
user -> create (Only create in CRUD Operation)
Action ->
user -> request_new_password & register

```

And I created a new user and provided the following role:

By enabling 2 legged OAuth authentication I make sure that only my authorized app with the consumer key and secret is able to access my endpoint successfully.

Using the following POST request I am able to create user successfully from the REST client:

```
Post Request URL: http://ExampleWebsiteBase.com/create_new_user/user/register.json

Post Headers:

OAuth:
OAuth oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_nonce="kXZ3iOtGqD7f350", oauth_timestamp="1450257992", oauth_consumer_key="Lq7r.........", oauth_signature="htvy........"

Content-Type:application/json

Post Body:
{
   "name":"SomeName",
   "pass":"reset123",
   "mail":"SomeName@gmail.com",
   "status":"1",
   "roles":[
      "2"
   ]
}

```

I would need confirmation from experts that this configuration is secure and acceptable.

Questions:

* The user created in this process does not has to verify the email ID. How do I configure the webservice so that the user is not created in backend without verifying the email?
* How do I integrate Social login - Facebook, Twitter and Google for instance?

# Answer
Try using the example reference below which displays the php code using OAUTH library with Services module.

Email verification needs to be done using the rules by adding condition to block user since using oauth it will be activated by default.

You can use the Facebook/Twitter end-point, consumer credentials(key & secret) replaced to Drupal services.

Reference: http://www.covenantdesign.com/blog/drupal-services-rest-server-and-3-legged-oauth
> 1 votes

---
Tags: 7, services, users, authentication-authorization
---


# Question
Title: How to add jquery lower version for a particular drupal page?
I have installed the jQuery Update module and set jQuery 1.10 as default jQuery version, but one of my previous functionality stop working.

I just want to use jQuery 1.8 for a specific page. How can I achieve this?

# Answer
> 6 votes
Add your condition to remove jquery 1.10 :

```
function THEME_js_alter(&$javascript) {
if ($your_condition) {
    $path = drupal_get_path('module', 'jquery_update') . '/replace/jquery/1.10/jquery.min.js';
    unset($javascript[$path]);
    drupal_add_js('path/to/jquery1.8');
}

```

# Answer
> 4 votes
You can use `hook_js_alter` to add, remove JS files and change the source of existing JS files.

Something like this should work:

```
function hook_js_alter(&$javascript) {
  if (arg(0) == 'special-page') {
    javascript['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js';
  }
}

```

---
Tags: 7, javascript
---


title: Are blocks a OK way to model a theme?

text:
# Question
Title: Are blocks a OK way to model a theme?
I am trying to build a new theme. Are blocks a OK way to model a theme? Some sites seem to recommend them, others say that they should be avoided.

# Answer
> 2 votes
Blocks are an important part in Drupal, but you don't model a theme with them.
Blocks are implemented from modules, using `hook_block_info()` and `hook_block_view()` (together other hooks); what themes implement are regions where those blocks are rendered. A theme cannot decide not to implement regions, since there are some regions Drupal requires from themes.

Eventually, a theme can alter how a block is rendered, but themes are not modelled around blocks.

---
Tags: theming, blocks
---


# Question
Title: How to exclude non-physical products from shipping calculations?
I have an show which sells physical products and virtual products like memberships. How can I set up a situation where there is no shipping charge for the virtual products? I know that I could set up free shipping if there are virtual products in the shopping cart, but I don't want the shipment to be free if the cart has both physical and virtual products.

Would the solution be to set the weight of the virtual products to zero? Or is there another way to implement this?

# Answer
Do you have separate product types? Commerce Physical has a function that determines whether a line item is shippable: `commerce_physical_line_item_shippable()`.

This function looks at the weight of an item. If the weight of the item is 0, then it considers it to be not-shippable.

You can also implement `hook_commerce_physical_line_item_shippable_alter()` and define your own logic to determine if something is shippable.

It looks like Commerce USPS implements this functionality and so you should be able to depend on this. Ideally, you'd have different product types for your physical and virtual products and your virtual products would have no weight causing them to not be factored into the shipping calculations.
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Export all views on a site to csv, json, spreadsheet etc
## The Question.

How do I export a spreadsheet documenting all the views from a drupal site?

## More info:

Say you want a summary of all the views on a site, perhaps you are going to rebuild them - maybe there is some iffy php\_views in there. Maybe you are simply documenting a messy site that you've inherited.

While there is support for exporting individual views to various formats it is not as easy to export a comprehensive list of all your views to a spreadsheet.

# Answer
## The Answer.

```
views_get_all_views()

```

## The Script (save this as views\_summarize.php or similar):

```
<?php
$views = [
  [
    'view machine name',
    'view name',
    'view desc',
    'base table',
    'display machine name',
    'display title',
    'display plugin',
    'php field the first',
  ]
];
foreach (views_get_all_views() as $view) {
  foreach ($view->display as $display => $data) {
    $views[] = [
      // 'view machine name'
      $view->name,
      // 'view name'
      $view->human_name,
      // 'view desc'
      $view->description,
      // 'base table'
      $view->base_table,
      // 'display machine name'
      $display,
      // 'display title'
      $data->display_title,
      // 'display plugin'
      $data->display_plugin,
      // 'php value in default field'
      $view->display['default']->display_options['fields']['php']['php_value'],
    ];
  }
}
$fp = fopen('views-summary.csv', 'w');
foreach ($views as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

```

## Notes:

The returned $view object has properties nested within arrays and objects, make sure you shift gears accordingly in your query:

### e.g.

```
$view->display['default']->display_options['fields']['php']['php_value'],

```

### You can run this script with:

```
drush php-script views_summarize.php

```

### Inspect the $view objects returned by views\_get\_all\_views()

```
drush ev "print_r(views_get_all_views());"

```

## Alternative uses

Site documentation is a tricky task, this approach is useful when documenting any pre-existing site configuration or content like rules, contexts etc...

### A few hours later

Refined version of above script - outputs marker to indicate presence and location of php in views - yikes!

https://gist.github.com/gl2748/313b19bce1a99e42d94f
> 1 votes

---
Tags: importing-exporting, views
---


# Question
Title: Monitoring strategies for infrastructure
Lately, I have been facing some downtime on some of the Drupal sites I have deployed. I would want to approach the problem pro-actively, rather than reacting to those downtimes by restarting services or the server itself. I have read about monitoring tools like nagios, munin, cacti, etc to monitor the health of your server/infrastructure, but I haven't really tried one in production. I deal with Drupal almost 99% of the times, and I would like to find out suggestions for both server level monitoring, and Drupal (application code) level monitoring.

Basically, I would like to be notified when the server load is high, possibly being pointed to the culprit (or the victim), so that I could take informed decisions. I would also like to know what people use for Drupal level monitoring (such as emailing) when there is a PHP error/warning. (What happens when the email server itself is down?)

# Answer
> 6 votes
If you want monitor several Drupal sites from the same place with alerts, etc... I can say you are not the only one . It's starting to be a business niche, by now filled by:

Both are commercial SaaS approaches, with free limited options to try the service.

Also there is the Open Source Zabbix monitoring option with its Drupal module http://drupal.org/project/zabbix , but then you should configure and build yourself the server.

All these options have their Drupal modules to send server and drupal-specific information to the monitor server.

UPDATE. Munin has also a specific Drupal Module , with a 2.x branch based on Drush.

# Answer
> 5 votes
Regardless of which you use, the one thing I would definitely suggest is—unless you have a full-time IT staff—do not maintain your own monitoring: rely on a service that's completely independent from your servers. It's one thing to have a public-facing server down, it's another to have it down and not know about it because your monitoring server is also down. Most monitoring services will include all of the requirements you've listed out of the box.

But at the risk of this being turned into a shopping recommendation question, the service I use for the requirements you've listed is Pingdom:

* Tells you if a sites up (of course)
* Measures how long it takes to respond
* Measures responsiveness and availability on any custom TCP/UDP port
* Email availability checking
* Allows for custom HTTP requests, letting you test out different aspects of your application
* Extensive reporting
* Worldwide monitoring, and they add about a dozen more monitoring sites every few months

# Answer
> 2 votes
These are some Drupal-agnostic suggestions:

* Are My Sites Up will periodically ping your server(s) and will email you (or SMS if you get the non-free package) if your site is offline or unresponsive.
* Load Impact is another great free tool that can stress-test your website so you can tell when exactly it starts failing.

As far as the Drupal application itself, I would suggest using Xdebug \+ Webgrind or XHProf to profile the code and keep an eye on this question: Best way to benchmark Drupal stack performance

# Answer
> 1 votes
I like pingdom for small/medium sites because it's useful: it tells you that Something Is Wrong from a customer standpoint, which is actionable. Things like load average don't really mean anything unless you've got a wildly misconfigured stack (which you shouldn't) or you're getting hammered from Digg/Reddit (in which case there's nothing you can do anyway, you should have prepared).

From Ted Dziuba's blog:

> I call these types of alerts Cool Story, Bro for short. These are bits of information that do not indicate any sort of problem state, and do not prompt any action. Cool Stories are things that you should not even have alerts for. They waste your time and make you paranoid. Cool Story Bro alerts are things like:
>
> * The load average on a server is above 20.
> * A job queue has more than X work units in it. Congratulations, dipshit, your queue is doing exactly what it is supposed to do.
> * Some metric is greater than an empirically determined mean. I get personally offended by shit like this.

Read the blog post, it's hilarious.

# Answer
> 0 votes
I am using check\_drupal to monitor various drupal sites. This is a nagios plugin which does not require any code changes to a drupal site itself. Only requirement is that drush needs to be present on the server.

---
Tags: performance
---


title: Manage content type by admin menu link

text:
# Question
Title: Manage content type by admin menu link
I wants to manage content type by admin menu tab, suppose I am having a "news" content type and if I would go to put some news, then I have to go first "content" tab then "Add content option" would appear and after navigate it, it shows all content types where I would select news this is default Drupal functionality but I wants that there should be link in admin menu like news, so when I click on news it directly navigate to news content type page and there should be only news contents not all. So how to do that? Actually I am having a lot of content types that I wants to show, each content type by each admin menu tab and also shows the data particular for its.

Please tell every thing step by step.

# Answer
You can install the Administration menu module. Then you can navigate to your Content Types like this:

Or you can install the Menu block module and create a block with the links to your Content Types like this:
> 2 votes

# Answer
You can manage it while creating or edit content type under Menu settings of that content type. Or you can create custom new menu from structure-\>menu, and put your add content url.
> 1 votes

---
Tags: nodes
---


# Question
Title: How can I limit filter to child terms of selected parent in Views?
I have a View that I am using to allow users to search for nodes on my site, all nodes have a category and a subcategory. I have two filters in the View, call these Parent Term filter & Child Term filter.

Example vocabulary:

-Categories
--Category A
---Item 1
---Item 2
---Item 3
--Category B
---Item 1
---Item 2
---Item 3

I want to implement the following functionality:

1. User selects Category A from list in Parent Term filter.
2. Child Term filter list populates with only Category A child terms.
3. User selects Category B from list in Parent Term filter.
4. Child Term filter list populates with only Category B child terms.

I've looked into Views Dependent modules, but none seem to do this properly. I'd prefer to have something in code (AJAX?) that does this much more efficiently.

At the moment I have the two filters manually limited to parent terms and child terms. However this means the child term filter shows all children irrespective of parent term selected.

# Answer
> 1 votes
I would take a look at Simple Hierarchical Select. From the module page:

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.

---
Tags: views, taxonomy-terms, input-formats
---


title: Show profile field on profile page

text:
# Question
Title: Show profile field on profile page
I created `user-login.tpl.php` file in my custom theme.

Then I add this code :

```
<div class="profile"<?php print $attributes; ?>>
  <h2><?php print ($user_profile['field_nom']);  ?></h2>
  <pre>
    <?php print_r($user_profile); ?>
  </pre>
</div>

```

It display my name correctly but, when I inspect in the browser its look like this ...

```
<h2>
    <div class="field field-name-field-nom field-type-text field-label-above clearfix">

        <div class="field-label">My name: </div>

        <div class="field-items">
            <div class="field-item even">Branquet</div>
        </div>

    </div>
</h2>

```

I just want to have the text, not a bunch of unless divs

# Answer
One option is you can user php function in tpl file before print.

```
strip_tags($user_profile['field_nom']);

```

Refer http://php.net/manual/en/function.strip-tags.php
> 1 votes

# Answer
Take a look at this page, there are numerous ways to do this. To render raw field value without any markup use `$account-><YourFieldName>[LANGUAGE_NONE]`

Another way to do this is to preprocess the profile object using template\_preprocess\_user\_profile

Use any debugging tools to find the raw value of your field
> 1 votes

# Answer
You can use Semantic Views module to strip all the tags.
> 0 votes

---
Tags: users
---


# Question
Title: Permissions checkboxes have disappeared on the Admin page for administrator users
All of the checkboxes on the Permissions page (`/admin/people/permissions`) have disappeared.

**I see the permissions for a split second as the page loads before they disappear, so I think this is a Javascript or CSS issue.**

Also, if I edit a single role's permissions (i.e., `/admin/people/permissions/3`), the checkboxes are there. This only happens when using the main permissions page.

**Example of the disappearing checkboxes:**

**What I've done**

* I've switched my theme and admin theme to Stark to make sure my theme wasn't hiding the permissions.
* I was using the jQuery Multi module to upgrade jQueryUI for some custom scripts, so I disabled that.
* I've searched if anyone else has had this issue, and the only thing I've found is https://drupal.org/node/1649186. I'm not familiar with Organic Groups, and I haven't renamed any machine names, so that post didn't get me very far.

# Answer
Oh my, I just discovered what it is and I feel really ridiculous... I'm using the admin menu module, and in the configuration, under "System tweaks", there is an option "Collapse module groups on the Permissions page". It is checked. The checkboxes weren't hidden after all. The groups were just collapsed... Maybe I just need a break and another cup of tea.
> 12 votes

# Answer
What do you mean by dissappear?

it could be a memory issue

from this link

or are you using the overlay? have you tried disabling it? (the overlay).
> 1 votes

# Answer
I haven't found the cause of this, but the obvious solution to get the checkboxes to appear is to disable Javascript in the browser.

This works, but depending on the browser, can make using the rest of the site a pain (if Javascript is turned off everywhere and you have multiple tabs open).
> 0 votes

---
Tags: users
---


# Question
Title: Views and Panels: Exclude already displayed items from view
I have two views on the frontpage, first one is a gallery and it should show only articles which have "promoted to frontpage" checked. The second view should show all the articles except the ones show in the first view.

I saw this question, but the answer does not help me, because in the second view, i don't want to exclude the "promoted to frontpage" articles, i just want to exclude the first 6 of them, all the other should appear mixed up with the other articles.

I also found this question, but as i use panels, i think it's not working for me.

How can i pass varibales from one view to another, or how to setup conditions to work like that? Or how can i set up more complex filters in a view, like

(promoted\_to\_frontpage== 1 && offset == 6) || (promoted\_to\_frontpage == 0)

# Answer
> 1 votes
Ok in the end, i was able to handle it with the answer of the maclean, which allowed me to configure everything in the views itself:

I have got two different views, not different displays, so in the first view, my gallery, i ad the Content:nid to the available fields and set it to not visible.

In the second view, i use - as he described - the contextual filter content:nid.

Provide default value, enter the code and - also as he described - Under "More" check both "Allow multiple values" and "Exclude".

# Answer
> 1 votes
If your views are not using pager then its easy just add a contextual filter with the following php code

```
$offset = 5

```

However, it is very unlikely. The best path is to use `hook_views_pre_view($view)`

Something like this

```
function YOUR-MODULE-NAME-HERE_views_pre_view($view, &$items) // note the '&' here!
{
  global $pager_page_array;

  // if this is our view...
  if ($views->name == "my-view-name"
       // ..and we're on its first page...
       && $pager_page_array[0] == 0 ) {
    $items = array_splice($items, 0, 5); // ...then eat up the first 5 nodes
  }
}

```

---
Tags: views, panels
---


# Question
Title: Is Filter Contains all words working well?
I have a View and a filter, with "Contains all words". I see that the SQL contains the expression

```
'%word1%' AND '%word2%',

```

but this is making that if I write "angular", just when I start writing the "a", also words which have the character a and not necessarily start with a will appear, for example "matter".

Shouldn't the placeholder % be only in one place, this way:

```
LIKE ( 'word1%' AND ' word2%' ) AND (' word1%' OR 'word2%')  ... [other combinations]

```

I am hurrying on the suggestion, but that way, it will look for a beggining of string as one of the two (or more) words, and the other words must have an empty space before them if they are not at the beginning.

# Answer
> 3 votes
Change your Operator to ***Starts with*** and Apply.

If you need use a specific filter you can alter your view query with this hook:

```
function YOUR_MODULE_views_query_alter(&$view, &$query)
{
    if($view->name == 'NAME') {

    //here modify your query

    }

}

```

---
Tags: 7, views
---


# Question
Title: Couldn't create a subtheme of a core theme
I want to do some customization on seven administation theme, I won't to copy it in my themes folder, I want to create a subtheme of it, it doesn't work for me. this is my info file

```
name = SEVEN SUB
description = a Seven subtheme
base theme = seven
core = 7.x
stylesheets[all][] = style.css

```

when I replace Seven by a theme already exists in my sites/all/themes, my theme inherits it, but for core themes it doesn't. I tried to specify the path of seven, themes/seven and /themes/seven doesn't fix the problem.

# Answer
In Drupal 7 if subtheme is attaching CSS with exact same file name, Drupal thinks you want to override a CSS file. That seems to be the problem for you. So you are overriding the CSS from the Seven theme by attaching `style.css` in the info file.

Easiest way to get over that problem is to rename your CSS file into something else e.g. `seven_sub.style.css`.
> 1 votes

---
Tags: theming
---


# Question
Title: Is is_front variable available in menu.html.twig template?
When the page is actually rendered, the last suggestion is checked. If it exists, that suggestion is used. Otherwise the next suggestion up is checked, and so on. Of course, if none of the overriding suggestions exist, page.html.twig is the final suggestion. This also explains why page--front.html.twig,

# Answer
> 4 votes
is\_front variable is not available in the menu template by default. You can add it there by adding this into your `themename.theme` file:

```
function themename_preprocess_menu(&$variables) {
  try {
    $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  }
  catch (Exception $e) {
    $variables['is_front'] = FALSE;
  }
}

```

---
Tags: 8, theming
---


# Question
Title: Unauthorised users to view homepage without menu
I have installed the Front Page module on my site. I want to show visitors (not-logged in users) to see the same homepage as logged in users but without the navigational bar.

I have used re-direct to the "/home" in the front page settings and removed menu permission in the anonymous users roles section but I am getting an access denied message.

# Answer
> 1 votes
Create a new template for your front page name it `page--front.tpl.php`

Create a variable which assign a role to a temporary variable in your `template_preprocess_page(&$vars)` like

```
function THEMENAME_preprocess_page(&$vars) {
  global $user
  if(drupal_is_front_page()) {
   if(in_array('anonymous', $user->roles)) {
      $vars['navigation'] = false;
    }
  }
}

```

then in you `page--front.tpl.php` just check `if($vavigation) ..`

---
Tags: users
---


title: How to make nested Quick tab in a view?

text:
# Question
Title: How to make nested Quick tab in a view?
I am using Quick Tabs for displaying the image gallery.

In views the FORMAT is Quicktab and the fields are ***Year ,Month ,Title and Images*** .

I have a gallery based on Year and month.I need to display the gallery based on year(main tab) under the year tab the month tab should be displayed.

e.g : here under the year i need to display the months entered in the content type.Now in view's Quicktab format option i gave ***Grouping field Nr.1*** as **Year**.When i tried the ***Grouping field Nr.2*** to **Month**,the tab is not showing anything or the combination not working.

How can i show the nested tab in Quicktab or can you suggest any alternative ways?

# Answer
> 0 votes
Try this: \- create the view for the month (with the pictures) \[field collection module can help you here\] \- Then you create the view for year and call the MonthView inside

(i know this is not the most advanced response you could get, but my knowledge is basic as i been using drupal since last month)

i hope this can help you.

---
Tags: 7, views, blocks
---


# Question
Title: How to remove some comments from a node?
I created a new table in the database to associate comments to the node version they were submitted against. Now when the node renders, I only want to display comments that are associated with the specific node vid. I thought about querying the db in hook\_node\_view to remove the comments that don't apply, but ideally only comments associated with the vid are added to the node in the first place. Is there a better way to implement this? Can I get at the node right before the comments are added to it?

# Answer
Apparently, the comment metadata populated after node\_load comes from comment\_node\_load(). But indeed the comments themselves aren't added until view time at comment\_node\_view(), which calls comment\_node\_page\_additions() which adds the renderable comments, which calls comment\_get\_thread() to load the cids.

So perhaps it would take adding vid column to the comment table, and then adding vid condition in comment\_get\_thread...hmmm.
> 0 votes

---
Tags: 7, comments, nodes
---


# Question
Title: What determines which fields are available in the relationship options?
What determines which fields are available in the views relationship options?

When creating a view, you can use Relationships, choosing from a list of available fields. Are all created fields supposed to be available for relationship in any view? It seems that some fields are available and some are not.

Example: I have Students and School as my Content Types. Students uses a Node Reference to School. When creating a view, I use Relationship, and a bunch of fields are there to choose from. As expected, School is there, because it is referenced in a field. But there are a lot more fields available. Why are those fields available? What criteria do fields fill to be available to use?

# Answer
One thing that affects the choice of the fields that are available is the show box when you first create the view this allows the developer to refine the criteria that is being chosen.
> 1 votes

# Answer
Inherently relational field types will automatically be there (e.g. entity reference, taxonomy). Other fields, like integer or text field, don't have anything to relate to by default.
> 1 votes

---
Tags: 7, views
---