title: Good and basic solution for search page

text:
# Question
Title: Good and basic solution for search page
I'm starting in on drupal search engine and I am looking to create a search page. First I would like the search is on very specific fields of some content types. What can be done with the basic module "Search" Drupal and "Views"?

Here is a draw of the search page I would like :

Filter 1,2, 3 are checkboxes to filter on content-type after the search.

I have no idea where to start :(.

---------- I add some explanations

I installed the module and SearchAPI followed a tutorial at: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages

This module is very powerful to index only the fields you want, thank you for this discovery. Being an intern student, I am not allowed to release details on what the project, but I'll offer you a similar example.

We have 5 different types of content: car, motorcycle, boat, Helicopter and plane. Each type has common fields and fields of its own.

Car: Name, Brand, Fuel, Transmission Moto: Name, Brand, Fuel, Transmission, Max Speed Boat: Name, Brand, Fuel, GPS Helicopter: Name, Brand, Fuel, Number of propellers Plane: Name, Brand, Fuel, Number of reactors

I want to index Name, Brand, Transmission, Number of propellers, and number of reactors. (I think it's doable quite easily with SearchAPI)

On the drawing on the filter tabs, I would like three tabs: Car, Motorcycle and Other which includes: Boat, Helicopter and Airplane.

By default, the validation of the text field reloads the page, such as a GET or POST form. It reload returns the results for the 5 types of content, so the 3 tabs are checked by default. After reloading, the user can check and uncheck the tabs to filter results by content type (Ajax or simple JS filter on CSS class, I do not know yet).

Another difficulty, my project manager wants the search results are like this:

---

Title of the node

Field corresponding to the search results. (Can be Name, Brand, Transmission, Number of propellers, or number of reactors)

---

I hope to enlighten you about my problem. I do not want a ready-made solution, but how to achieve it. Is it doable in the first place ...

# Answer
You are correct. You could perfectly accomplish this with Views. A simple guide, just for illustration purposes, since we don't have the specifics in your question:

1. Create a View
2. In the FILTER CRITERIA section, add the desired filters (make sure to check the "Expose this filter to visitors..." checkbox) by doing that, you are indicating that you want it to be visible in the search page, so your users can change them.
3. In the OTHER area, mark "Use ajax" as "Yes" to submit the form asynchronously.
4. In the EXPOSED FORM area, go to "Exposed Form Style" \> "Settings" and check the "Autosubmit" checkbox (if you wish to automatically submit the form once an element is changed).

Additionally, you could use the Better Exposed Filters module for advanced cool stuff (E.g. hiding the "Send" button, showing filters as checkboxes, etc).
> 0 votes

---
Tags: views, search, 7
---


title: Untrusted Host "localhost" in

text:
# Question
Title: Untrusted Host "localhost" in
From Drupal 8 beta 6 (released today), I have this error :

> Error message UnexpectedValueException: Untrusted Host "localhost" in Symfony\Component\HttpFoundation\Request-\>getHost() (line 1221 of core/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Request.php).

I use this local url to call my site: http://theming.dev

Inside my setting file, I have:

```
     $settings['trusted_host_patterns'] = array(
        'theming\.dev$',
     );

```

Note, this error is displayed only when I uncomment this lines:

```
 if (file_exists(__DIR__ . '/settings.local.php')) {
   include __DIR__ . '/settings.local.php';
 }

```

What is the problem please ? Thanks.

# Answer
> 28 votes
This problem occurred for me when building an 8.0.0-beta6 test site on my Ubuntu 14.04 laptop. I have an Apache web server running locally, with the test site defined using a `VirtualHost` directive. I add the domain name of the test site ("example.com") to my `/etc/hosts` file, pointing to 127.0.2.1, to bypass the need to use real DNS entries.

After installing the site, everything looked fine. However, I noticed a warning message on the Status Report page about not having `trusted_host_patterns` set, so I went into my `/sites/default/settings.php` file and added these lines:

```
$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

```

Upon saving the file and reloading my browser, I got a very generic error page and, after commenting-out the new lines, noticed the `Untrusted Host "localhost"...` log message.

It appears that because I'm web-browsing from the same computer on which the web server is running, the Host is at some point getting converted to `localhost`, and thus is failing to match the set of patterns I had specified. I was able to fix this issue by changing these lines to:

```
$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
  '^localhost$',
);

```

On a site that is intended to be put into production, you might want to utilize a `settings.local.php` file to specify `^localhost$` as a valid host pattern for testing purposes only. Note that if you want to do this, you'll need to uncomment these lines in the default `settings.php`, and move them to the bottom of the `settings.php` file:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

In this case, the `settings.php` file would only contain the actual domain names:

```
$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

```

and `settings.local.php` would contain:

```
<?php
$settings['trusted_host_patterns'][] = '^localhost$';

```

to append `localhost` to the list of valid hosts. With this configuration, you would not copy the `settings.local.php` file when copying the site to the production server.

---
Tags: 8
---


# Question
Title: Insert videos from media module into Ckeditor
I've been working the media module and inserting images with the ckeditor media widget and It's been great.

I've also used some embbed media plugins to add vimeo and youtube media elements wonderfully.

But when I try to insert some of this media into the ckeditor it only inserts the rendered image form this media instead of the widget i get when I render the media in a node.

I need to know if I have to configure the file-types/ output in the media module or config anything in the ckeditor.

Thanks

# Answer
I believe this is just how it works with the media module. You might could experiment with the http://drupal.org/sandbox/DevinCarlson/1823634 to select the view modes for files displayed inserted into wysiwyg editor.
> 1 votes

# Answer
insert\_video module adds an Insert button to video fields managed by the Media module. It allows you to insert video markup into your WYSIWYG by choosing a pre-defined formatter.
> 0 votes

---
Tags: wysiwyg, files, media, nodes
---


title: How to add in-place edit links?

text:
# Question
Title: How to add in-place edit links?
I need to put in-place links to edit nodes and blocks in Panels. I see that there are some modules in Drupal 6, like EazyEdit and Block edit, but I didn't find anything for Drupal 7 yet. So appreciate your hints, whether to pick up an existing project on how to do this.

# Answer
There's an alpha version of Editable Fields for Drupal 7. The module:

> allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

It works for nodes, but not for blocks as far as I'm aware.

There's also the Aloha module:

> This module integrates the excellent HTML5 wysiwyg editor Aloha Editor (http://aloha-editor.org/) to Drupal. Both the module and the Aloha Editor library are under active development but still in the early stages.

But judging from the comments on the module page it might not be ready for use just yet. I did find an article with someone who claims to have got it working so that might be the place to start.
> 4 votes

# Answer
There are at least two more recommendable solution alternatives now:

* **jEditable**. A faster but simpler alternative to the already mentioned Editable Fields module.
* **QuickEdit**. In-place editor for fields that also allows rich text editing via CKEditor. Base of the in-place editing functionality that will be included in Drupal 8 Core.
> 0 votes

---
Tags: 7
---


# Question
Title: Drupal 7 ubercart roles assignment ineffectual
Nothing happens when I test in the sandbox with paypal standards payment and everything set up through ubercart for recurring subscriptions and feature added role assignment, when I edit product subscription roles assign on purchase to go to certain role and the payment goes through the sandbox I get redirected back to site but the role has not changed to reflect the purchase. What am I missing here?

# Answer
> 0 votes
In case this happens to anyone else, when using the sandbox if configured so output becomes payment pending, role assignments will logically not work.

You just need to login to your developer paypal site and click on the test account you are using in settings and switch payment review to off.

---
Tags: users
---


title: Menu added not showing

text:
# Question
Title: Menu added not showing
I have added a menu item in main-menu using following code

```
$item = array(
    'menu_name' => 'main-menu',
    'link_path' => 'my-profile',
    'link_title' => 'Services',
    'module' => 'menu',
    'weight' => 0,
);
menu_link_save($item);
menu_cache_clear_all();

```

this code is placed in lcp\_theme function, lcp is custom module and is working properly except this added menu item. I cant see this menu at top of the site in main menu.

As per the documentation I can use this function anywhere in module.

# Answer
> 0 votes
If all you are trying is to add a menu item in main menu, you can implement `hook_menu`, code something as below.

```
function my_module_name_menu() {
  $items['test'] = array(
    'title'           => 'Tes Page',
    'description'     => t('Test'),
    'menu_name'       => 'main-menu',
    'weight'          => 8,
    'access callback' => TRUE,
    'page callback'   => '_my_module_name_test_page',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function _my_module_name_test_page() {
  return "hi";
}

```

Key is to have `'menu_name' => 'main-menu',` in menu item declaration.

---
Tags: 7, routes
---


title: How to leverage a DB query with views?

text:
# Question
Title: How to leverage a DB query with views?
I have three things:

* A user (User entity)
* A league (Node)
* A league entry (Node, with a numerical field for time and a noderef field to a league)

A user can create a league entry node, and set a time value and a node reference to a league node.

I want to produce a view that takes the league node id as an argument, and produces a table row for each user that has submitted a league entry node. The columns will be the user name, a user field that states the user's team, and finally, for every league entry node raised by them as author, that contains a node reference to the current league nid, a sum of the matching league entries numerical fields.

Now as you can imagine, doing this in views is very problematic because of aggregation issues on a single field; so a simpler alternative is to simple create a new DB table that stores the data I want to display in distinct fields.

So if I have a DB table like:

username, league, total of league entry nodes time value so far

How can I get this info into views so I can take advantage of table display, column sorting, and all that good stuff?

# Answer
There are a couple of ways of doing this. You can create an entity. This requires the writing of a custom module to do so. Entities can be challenging if you have never done them before.

Another way and slightly simpler (still requires a custom module). Is to use the Views API. The first thing you would implement is hook\_views\_data(). This is a really good example of hook\_views\_data borrowed from Drupal Commerce.

Lastly, there are some modules out there that might help. One of them is Schema Views.
> 1 votes

---
Tags: views
---


# Question
Title: Download file field dependent on user role vs role field values
I have a type `downloadable_item` which has a field `field_roles_allowed` that is based on the Role Field Module.

My goal is to have a `field_download` of `file` type that will show the file for download if the user in a role selected in the `field_roles_allowed` and a message that they need to request access otherwise.

I am attempting to add a formatter for the file field type using the Custom Formatters Module. I found this tutorial on how to use the Custom Formatters module, however, they use the "HTML + Tokens" option. I will need to use the PHP option to be able to output either the download button or a message depending on whether the user is in a role in the `field_roles_allowed`.

I cannot figure out how to get the roles that are allowed, download file information, and current user's roles for comparison.

My question is really "How do I do these things that I cannot figure out?", but if someone believes I am going about this totally in the wrong way... I am open to another way.

---

EDIT: I solved my own problem below, but not really in a preferable way. How could this be done without writing PHP logic in field?

# Answer
> 1 votes
As always with Drupal. There are often many solutions to your problem. Here are two ways of doing this.

**Views and Panels** The power of views and panels can be leveraged to do this.

First step would be to build a view containing various panes built for the different displays you want per security role. You would want to use panes because they are only accessible to Panels and cannot be used by anything else on your Drupal website, this will be important for step two. In your case you would have a pane that did not show the download link then a pane that shows the download link. This can be done in one view with multiple panes.

Second step build a panel page. Panels has a unique capability of variations of a page "Called Variants in the Panel UI". The variants can be assigned selection rules to each variant. Here is where the security layer comes in and why you want to build your views as panel panes and not just view pages. Panes ensures that only Panels can access your views you have created with your protected content. The first variation will use a selection rule of User:role with the role you want to use to allow access to the protected content. The second variation will use no selection rules as this will be what the user sees if they do not have the role. Panel variations and selection rules work in the first one satisfied in the order of the variations. The first variation with the user selection rule will be shown before the last variation if the user does not have the role Panels goes to the next variation till it can find one that can be satisfied - if one exists. This has many other applications but I have used this feature to serve protected content to users based on their roles.

**Themeing layer**

Another way to approach this is to use Drupal's themeing layer. If you are using core node displays to show your content to the user this works very well. Using Drupal's node templates you can overide the display of the nodes containing the protected fields and use some simple PHP statements to hide or show the field with the download link. Example core pieces of the code in the template would be:

```
global $user;

foreach ($this_user->roles as $rid => $role) {
  switch ($role) {
    case 'has access':
      print render($content['field_download_link'])
      break;

  }
}

```

# Answer
> 1 votes
After some digging... I found that I am able to get field information like...

```
$variables["#object"]->field_roles_allowed["und"]; //array containing id's of roles allowed
$variables["#object"]->field_download["und"]; //array containing information about the file

```

and that I can get the current user's roles like...

```
global $user;
$user->roles; //array containing current user's roles

```

Then I can compare the field roles allowed with the current user's roles and determine what to output from there.

Still not very happy with this, I would prefer something where I don't have to write PHP logic in a field.

---
Tags: 7, files, users, entities
---


title: Remove old role once new one purchased

text:
# Question
Title: Remove old role once new one purchased
Someone created a module for this called `uc_clear` roles so you can stop what's happening to me now which is when a new role is purchased it is just added to the old one. But this module is only for Drupal 6 and I am using 7.

Logintoboggan preauthorize role if the user neglects to verify it and then buys a role, the new role will replace it but if verified and user makes purchase for upgrade they end up with both free membership status as well as paid. I don't yet know how to write php or create a module but, could the RULES module do the job?

# Answer
Yes, you can use Rules to manage roles.

Rules need Event to react on, Condition to evaluate for truth, Action to perform.

Event: It is hard to tell from from your post what would be your Event. I don't use Ubercart, but I assume it provides some Rules Events like Commerce, e.g. 'After adding a product to the cart,' 'On checkout coompletion,' and so on. There's also 'Before saving a user account,' 'After saving a user account' and so on.

Condition: "User has role(s)"

Action: "Add user role", "Remove user role"

Very simple actually.

\[ Note also that the current version of Rules (2.8) is BROKEN with Commerce 2 ... not sure if the problem also exists with Ubercart ... users of Commerce have to downgrade Rules to 2.7 \]
> 1 votes

---
Tags: ubercart
---


# Question
Title: Create Content Types that create other node for fields
I would like to create a content type, say for example *Podcast*, that would have other pages for some of the fields.

A `field_audio` that is a *file* would automatically generate a `/node_url/audio` page, a `field_transcript` that is a *Longtext* would be \`/node\_url/transcript etc.

My initial hypothesis is to use a views page to set the path but I am really confused with the interface and how best to solve this problem.

`EDIT`

In order to clarify, I'll go step-by-step for the desired functionality.

A content type is configured to publish at `domain.tld/podcast/podcast-title`. This content type has a lot of fields that are removed from the display using Display Suite.

What I would like to do is to use URLs that automatically generate displaying content based URL parameters, similar to how Drupal tags do but for individual nodes.

Example website: `http://codepen.io/inkovic/pen/qEXJpo` is the original content. `http://codepen.io/inkovic/pen/qEXJpo.css` is the css `http://codepen.io/inkovic/pen/qEXJpo.html`is the HTML and so forth.

I could do this manually with a contextual view + block on the actual node-url, but `Views -> Contextual Filter -> Content: Nid -> Content ID form URL` would break if the url is different from the actual node.

So `podcast/podcast-name/transcript` would render a view based on the **podcast-name** part of the URL.

I do not want to create a custom content type of transcript, mp3, links etc and use Entity Relationship because that would ruin the content authoring experience.

# Answer
> 0 votes
You don't want to make a new node - just to show field value on separate page. Use Views module to accomplish that.

1. Create new View based on Content with Page display (path node/%/test\_field).
2. Set Contextual Filter to Node NID (and make it global with "All display" option). Provide default value: Content ID from URL.
3. Choose field you want but remember to set "This page (override)" option.
4. Create as many page displays as you want with new path (based on the same rule - node/%/some\_name) and select another field (under Fields)

That is how it should looks like:

\[EDIT\] Install Sub-pathauto module for second level path aliases.

---
Tags: views
---


title: Service links - Facebook "like" error

text:
# Question
Title: Service links - Facebook "like" error
I am using the Service links module in my Drupal 7 site.

When using the Facebook "like" widget, I get the word "error" (in red color), in the place where the Facebook "Like" button should be.

When clicking on the word "Error", a Facebook popup window is opened with the error like so:

> The href URL must be absolute

Note: I am using the Service links widgets inside a view. Other Services links widgets are working great, such as the Facebook share widget, Twitter, Google+ and Pinterest widgets.

What is the problem of the Facebook "like" button?

# Answer
> 0 votes
Replace this line(in sites\all\modules\service\_links\js\facebook\_like.js):

```
iframe.src = $(this).attr('href').replace('http://', '//').replace(/http[s]*\%3A\/\//, '');

```

with the below line:

```
iframe.src = $(this).attr('href').replace('http://', '//');

```

# Answer
> 0 votes
I also had the problem that the button was not showing up. I tried the patch mentioned by Astha chauhan and pachabhaiya, but it still didn't work. I found the problem after comparing the code given by Facebook Developers with the code generated by the widget: The `appId` was not included in the iframe `src`. My fix was to replace the line (in `sites\all\modules\service_links\js\facebook_like.js`):

```
iframe.src = $(this).attr('href').replace('http://', '//').replace(/http[s]*\%3A\/\//, '');

```

with:

```
iframe.src = $(this).attr('href').replace('http://', '//') + "&appId=" + Drupal.settings.ws_fs.app_id;`

```

see also: Facebook Like Widget Broken - App ID not included \[#2417729\] | Drupal.org

---
Tags: social-network
---


# Question
Title: Language detection URL domain on localhost
I built a website in German on al local drupal installation. Now, I try to add English as a second language. As language detection method I am using URL. Using the path prefix option everything works well but when I try to use the domain option it doesn't work.

The domain option is what I want to use when the website is finally online.

mywebsite is in German and en.mywebsite is in English.

On my localhost I access my site with localhost/drupal722. I tried to configure the English URL as localhost/en.drupal722 but this does not work.

I deleted the path prefixes of both languages. Regarding the German domain configuration I tried both, leaving blank and insert localhost/drupal722/.

Does somebody has an advice on how to get this working?

# Answer
> 1 votes
It is better that you configure a subdomain or even a complete domain. For example, `site1.localhost` and `site2.localhost` and that you change your apache or web server to point to the Drupal root folder. Even you can change your OS hosts and link to fake domains, for example, `site1.example.com` and `site2.example.com`.

For multi-domain and multi-language I would recommend these modules which work like a charm:

You can add new sites and in each site have one or more different languages. These would solve all your problems as it works very well and it is pretty good in configuring content served from a single installation to several different domains and languages.

---
Tags: i18n-l10n
---


# Question
Title: Is there any way to display an image as background?
I have a picture in a field and I want to be displayed in its exact look but as a CSS background... is this even possible? Is there any mechanism how does that?

# Answer
> 2 votes
You can use Background Images and Background Images Formatter modules to achieve this. Note in the Background Images Formatter description that it can take images from a field and add it to the background.

Otherwise you can create your own module that generates the appropriate css and adds it to the page with drupal\_add\_css

# Answer
> 1 votes
AFAIK, you'd have to add it to your theme.

Alternatively, you could use CSS Injector.

---
Tags: media
---


# Question
Title: The website encountered an unexpected error. Please try again later
When creating a new user account, as a **visitor** or **unregistered** user, I get the following message:

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

and the account is not fully created.

The log *(admin/reports/dblog)* gives the following description of the error:

> *PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 150752 \[:db\_insert\_placeholder\_1\] =\> 1422513054 \[:db\_insert\_placeholder\_2\] =\> a:6:{s:7:"contact";i:1;s:20:"l10n\_client\_disabled";b:0;s:17:"mimemail\_textonly";i:0;s:34:"user\_relationships\_ui\_auto\_approve";a:0:{}s:34:"user\_relationship\_mailer\_send\_mail";b:1;s:40:"user\_relationships\_allow\_private\_message";s:12:"on all users";} ) in drupal\_write\_record() (line 7239 of /home3/zacteyc1/public\_html/includes/common.inc).*

The referer is: user/register

However, if I am the super user (user/1) I can create a complete new user account with no error.

I have disabled all the modules I could (including core ones) one by one to find the culprit but even with all modules disabled, the error persists.

I have also uploaded a fresh copy of the core files, but to no avail.

I have then uploaded, one by one, backups of my database going as far back as September 2014. It is with the September 14, 2014 (and prior) that the error disappears.

I need to fix the current database otherwise I will have lots of angry users who will have lost all the pictures they uploaded, all they have written in blogs, messages, etc. since September!

Does anyone know how to do this (like comparing a "good" database with a "bad" one to isolate the error?)

Any and all suggestions to fix the current database is greatly appreciated!

Thanks. :)

# Answer
The issue was created by rules.

I had read somewhere on two or three occasions that the Rules module could generate such error but I thought disabling the module would be enough to show if rules were involved or not. It didn't. Apparently, the rules are still active when the module is disabled (a diehard, at least in my case!)

I also had to disable the rules one by one until I found the culprit. It was a rule automatically making the new authenticated user a member of a welcome group. Somehow, the data in the rule had shifted and it was no longer the *account* but the *site:logged-in-user* that was made a member of the group.

The lesson here is about Rules and that the rules need to be disabled. Disabling the module alone is not enough. I hope this helps someone.
> 1 votes

---
Tags: database, users
---


# Question
Title: PDOException: SQLSTATE[42S02]: Base table or view not found
I am getting a PDO error which seems related to the Mass Contact module. I installed, played with and then disabled the Mass Contact module. Now when I run cron I get the error:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'drupal.field\_data\_field\_mass\_contact\_category' doesn't exist: SELECT field\_data\_field\_mass\_contact\_category0.entity\_type AS entity\_type, field\_data\_field\_mass\_contact\_category0.entity\_id AS entity\_id, field\_data\_field\_mass\_contact\_category0.revision\_id AS revision\_id, field\_data\_field\_mass\_contact\_category0.bundle AS bundle FROM {field\_data\_field\_mass\_contact\_category} field\_data\_field\_mass\_contact\_category0 WHERE (field\_data\_field\_mass\_contact\_category0.deleted = :db\_condition\_placeholder\_0) AND (field\_data\_field\_mass\_contact\_category0.bundle = :db\_condition\_placeholder\_1) LIMIT 10 OFFSET 0; Array ( \[:db\_condition\_placeholder\_0\] =\> 1 \[:db\_condition\_placeholder\_1\] =\> mass\_contact ) in field\_sql\_storage\_field\_storage\_query() (line 585 of /var/www/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module)

If I try to uninstall Mass Contact I get the error:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'drupal.field\_data\_field\_mass\_contact\_category' doesn't exist: UPDATE {field\_data\_field\_mass\_contact\_category} SET deleted=:db\_update\_placeholder\_0; Array ( \[:db\_update\_placeholder\_0\] =\> 1 ) in field\_sql\_storage\_field\_storage\_delete\_field() (line 312 of /var/www/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

The table 'field\_data\_field\_mass\_contact\_category' does not exist. It is not even created if I enable the Mass Contact module and create a category.

I have tried clearing all cache tables (using phpmyadmin) both with the Mass Contact module enabled and disabled.

I am using Drupal 7.32 on ubuntu localhost.

I have no idea how to proceed. I have found no relevent solution searching the questions here with "PDOException: SQLSTATE\[42S02\]: Base table or view not found". Any help/advice about how to proceed to track this problem down appreciated.

# Answer
> 2 votes
I just had the same similar situation happen just today. I'm not sure if you resolved your issue, but in case you or others have the problem again, there's a simple solution that worked for me.

I'll post it here, but please go to this link (https://www.drupal.org/node/2417855) as a reference to my situation... thanks!

> This is the error message I was getting PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'dbxxx.xxxfile\_metadata' doesn't exist: SELECT * FROM {file\_metadata} WHERE fid IN (:fids\_0); Array ( \[:fids\_0\] =\> 38 ) in file\_entity\_file\_load() (line 201 of /sites/all/modules/file\_entity/file\_entity.file.inc)

Here's what I did:

> UPDATE
>
> I did my own recon work ... somehow, I was able to get out of the situation and the error message disappeared. I am either very resourceful or EXTREMELY lucky!! lol
>
> Here's what I did before the error message ... I Installed and enabled the following modules:
>
> Media and File\_Entity ... then the error showed up and froze me I then tried to disable, but it wouldn't let me. Here's what I did AFTER the error message to fix the problem:
>
> I went directly to the database and disabled the two modules within then I ran the "update.php" from my site It then processed the "file\_entity" module All is good now I'm guessing the module did not upload properly ... I don't know, but I'm back online again... whew =)

I hope this helps =)

# Answer
> 0 votes
I have been there before. What I recommend is that you create a 'fake' table so the uninstaller can run. Just add these two tables to your database and any subsequent one it is trying to find:

"field\_data\_field\_mass\_contact\_category" "field\_revision\_field\_mass\_contact\_category"

Then run the un-install.

There are a few other ways you can do it but think this is the easiest.

# Answer
> 0 votes
Definitely, Install file is not properly addressed or there may be spelling mistake in it. Install file. Please provide snapshot of that file, or fix that error manually, usually problem may be hook\_uninstall schema is not properly configured to wipe out the table when Uninstaller is clicked in module administration page.

---
Tags: database
---


# Question
Title: Change the default image based on certain condition
I wonder if I could provide two default images -one for boys & other for girls.

In the registration form they can choose their sex from a Boolean field.

Is it possible with conditional fields ? How? I'm not a programmer, so please make your answer detailed.

# Answer
I would suggest using Rules as follows:

You can either include Conditional Rules for a single Rule, or use two rules:

Event: After user registration

Condition: image field is empty (only want it to run if they don't upload an image)

Condition: sex field is girl

Action: set image field to url location of girl default image

New Rule:

same as above except for the condition of sex changes to boy

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
> 1 votes

---
Tags: media
---


# Question
Title: How can the Panels IPE "add content" modal be customized?
I have a content type rendered via Panels IPE (In Place Editor) which allows authenticated users to customize the layout of their node. When users click to "add content" I would like to be able to control what appears in the modal dialogue. By default it is not very user friendly:

Ideally I would like to be able to choose what can be added, for example only "nodes", or only "views" and "widgets". I'm not sure where this can be changed or if a module exists that does this already. The only module I have found that attempts to do this is Panopoly Magic which requires an entire suite of modules called Panopoly to be installed. I don't need the majority of the functionality that Panopoly adds and hence I don't think it is a very light solution. Here is the result that can be achieved:

Is there a way the IPE add content modal can be customized?

# Answer
You can do that for all panels pages from admin/structure/panels/settings/panel-page

Also if you use panelizer you can customize what appear in IPE for every content type. admin/structure/types/manage/\[content-type\]/panelizer

Also you can install panopoly\_magic module without other panopoly features, only the module "panopoly\_magic.info" since it does not deponent on any thing in panopoly distribution.
> 2 votes

---
Tags: 7, panels
---


# Question
Title: Add Attribute to Textfields in Admin Theme
I'm often working with Pages in RTL Languages where the default Theme and also the admin theme are using RTL languages.

What often bothers me, is to use LTR texts like Tokens or Paths in Textfields, because the specialchars like `/` or `[` are shifted.

To solve this, i would like to add the dir=auto attribute to all Textfields in admin Theme.

So the textfields should look like this:

`< input type="text" id="edit-file-public-path" name="file_public_path" value="sites/default/files" size="60" maxlength="255" class="form-text" **dir="auto"**>`

My idea was to create a Subtheme of Seven and use the template\_preprocess\_field function to add the dir attribute to all fields.

My issue is, that my Preprocess function is never called.

Are the preprocess functions called in admin Theme? And is there an another way to do this?

myseven.info file:

```
name = My Seven
description = Admin theme based on seven admin Theme
package = Core
version = 1.0
core = 7.x
base theme = seven
stylesheets[all][] = css/myseven.css
settings[shortcut_module_link] = 1
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

```

template.php Function

```
function myseven_preprocess_field(&$variables, $hook){
    dsm($variables);
    watchdog("Hello World!","The preprocess_field Works!"); //if this function is ever called there should be an entry in Reports
    }

```

# Answer
template\_preprocess\_field is for field output themeing not input field themeing, you maybe looking for theme\_textfield or hook\_field\_widget\_form\_alter
> 0 votes

---
Tags: hooks, theming
---


title: Why does "drush migrate-manifest" fail?

text:
# Question
Title: Why does "drush migrate-manifest" fail?
I'm trying this migration: https://github.com/amool/migrate\_drupal7

but with this command:

```
drush migrate-manifest modules/contrib/migrate_drupal7/config/install/
migrate.migration.d7_user.yml --legacy-db-url=mysql://DrupalAdminUser:mydrupalpass@127.0.0.1/myddbb

```

I get this:

```
PHP Fatal error:  Call to a member function getLoadPlugin() on a non-object in /www/drupal8/core/modules/migrate_drupal/src/MigrationStorage.php on line 73

```

Any idea?

full log:

```
    substr() expects parameter 1 to be string, array given MigrationStorage.php:34                                                              [warning]
array_flip(): Can only flip STRING and INTEGER values! MigrationStorage.php:47                                                              [warning]
array_flip(): Can only flip STRING and INTEGER values! MigrationStorage.php:47                                                              [warning]
array_flip(): Can only flip STRING and INTEGER values! MigrationStorage.php:47                                                              [warning]
array_flip(): Can only flip STRING and INTEGER values! EntityStorageBase.php:220                                                            [warning]
array_flip(): Can only flip STRING and INTEGER values! EntityStorageBase.php:220                                                            [warning]
array_flip(): Can only flip STRING and INTEGER values! EntityStorageBase.php:220                                                            [warning]
PHP Fatal error:  Call to a member function getLoadPlugin() on a non-object in /www/drupal8/core/modules/migrate_drupal/src/MigrationStorage.php on line 73
PHP Stack trace:
PHP   1. {main}() /opt/drush7/vendor/drush/drush/drush.php:0
PHP   2. drush_main() /opt/drush7/vendor/drush/drush/drush.php:16
PHP   3. Drush\Boot\DrupalBoot->bootstrap_and_dispatch() /opt/drush7/vendor/drush/drush/drush.php:76
PHP   4. drush_dispatch() /opt/drush7/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php:46
PHP   5. call_user_func_array:{/opt/drush7/vendor/drush/drush/includes/command.inc:178}() /opt/drush7/vendor/drush/drush/includes/command.inc:178
PHP   6. drush_command() /opt/drush7/vendor/drush/drush/includes/command.inc:178
PHP   7. _drush_invoke_hooks() /opt/drush7/vendor/drush/drush/includes/command.inc:210
PHP   8. call_user_func_array:{/opt/drush7/vendor/drush/drush/includes/command.inc:359}() /opt/drush7/vendor/drush/drush/includes/command.inc:359
PHP   9. drush_migrate_manifest() /opt/drush7/vendor/drush/drush/includes/command.inc:359
PHP  10. entity_load_multiple() /opt/drush7/vendor/drush/drush/commands/core/migrate.d8.drush.inc:48
PHP  11. Drupal\migrate_drupal\MigrationStorage->loadMultiple() /www/drupal8/core/includes/entity.inc:203

Fatal error: Call to a member function getLoadPlugin() on a non-object in /www/drupal8/core/modules/migrate_drupal/src/MigrationStorage.php on line 73

Call Stack:
    0.0006     238800   1. {main}() /opt/drush7/vendor/drush/drush/drush.php:0
    0.0451     290784   2. drush_main() /opt/drush7/vendor/drush/drush/drush.php:16
    0.3256    2469480   3. Drush\Boot\DrupalBoot->bootstrap_and_dispatch() /opt/drush7/vendor/drush/drush/drush.php:76
    1.2927    6020640   4. drush_dispatch() /opt/drush7/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php:46
    1.6091    8205856   5. call_user_func_array:{/opt/drush7/vendor/drush/drush/includes/command.inc:178}() /opt/drush7/vendor/drush/drush/includes/command.inc:178
    1.6091    8206344   6. drush_command() /opt/drush7/vendor/drush/drush/includes/command.inc:178
    1.6097    8207512   7. _drush_invoke_hooks() /opt/drush7/vendor/drush/drush/includes/command.inc:210
    1.6113    8242520   8. call_user_func_array:{/opt/drush7/vendor/drush/drush/includes/command.inc:359}() /opt/drush7/vendor/drush/drush/includes/command.inc:359
    1.6113    8243040   9. drush_migrate_manifest() /opt/drush7/vendor/drush/drush/includes/command.inc:359
    1.6271    8274032  10. entity_load_multiple() /opt/drush7/vendor/drush/drush/commands/core/migrate.d8.drush.inc:48
    1.6364    8355688  11. Drupal\migrate_drupal\MigrationStorage->loadMultiple() /www/drupal8/core/includes/entity.inc:203

Drush command terminated abnormally due to an unrecoverable error.                                                                          [error]
Error: Call to a member function getLoadPlugin() on a non-object in /www/drupal8/core/modules/migrate_drupal/src/MigrationStorage.php, line
73

```

# Answer
Note that the Github repo you're trying to use hasn't been updated since Jul 1, 2014, which means a lifetime in the D8 development cycle.

You should probably read Will migrating content types be possible? which gives some pointers about D7 to D8 migrations. However, note that https://www.drupal.org/upgrade/migrate will hold best practices for migrations once it's ready in Core. Currently it isn't, thus why instead of trying to help you with this Github repo directly I'd like to encourage you to help with the migrate\_upgrade module efforts and IMP initiative first, which aim at unblocking D6 to D8 migrations for 8.0.0

IIRC D7 to D8 migrations will be supported not before 8.1.x and you can follow the development and help in chx's IMP sandbox. Make sure to also follow issues with the D8 Migration Component tag. All in all, I think there are so many moving pieces at play in a D7 to D8 migration that it'd be better if you could wait that the community has vetted an official upgrade path.
> 4 votes

# Answer
The problem is how you're trying to run the migration, eg:

```
drush migrate-manifest modules/contrib/migrate_drupal7/config/install/
migrate.migration.d7_user.yml --legacy-db-url=mysql://DrupalAdminUser:mydrupalpass@127.0.0.1/myddbb

```

That isn't the manifest Migrate is looking for. Manifest files in the config/install directory of a Drupal 8 module are config entities that are copied into the Drupal 8 site when the module is enabled.

What Migrate wants is a manifest that lists the migrations you want run so to simply run the user migration, create a file called "manifest.yml" in your site root that looks like this:

```
 - d7_user

```

And then run like so:

```
drush migrate-manifest manifest.yml --legacy-db-url=mysql://DrupalAdminUser:mydrupalpass@127.0.0.1/myddbb

```

The user migration is simple enough, the Yaml file in that Github repo, while not complete, looks like it would work to me.
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: How to create a new entity that is fieldable
I am currently learning how to create entities in Drupal 7. I have successfully defined a new entity and made it fieldable. My question is how do a create a new instance of that entity? I understand that if I want to create a form in a normal module I use the field API to create the form to collect the information that I want. Since the entity is fieldable, I am assuming that there must be a function that creates the form for you based on the form elements that you have defined. I mean that would make sense considering the field definitions are stored in a consistent format in the database so it would stand to reason that a function could be created to automate the process of creating the form from that information. I assume this is what happens when you create a new article that has had fields added to it.

Does anyone know what this function is or what the proper procedure is to accomplish this task?

# Answer
> I am assuming that there must be a function that creates the form for you

Not quite - you need to create the form yourself with the API as normal, but you can use `field_attach_form()` to have the field elements added automatically. You'll also need the complementary `field_attach_validate()` and `field_attach_submit()` in your form's validate and submit handlers respectively.

Elements for your entity type's properties need to be added manually.

The best place to look for code examples is the entity example module in the Examples project, it has all of this in it and is pretty well commented.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Why do only some of my hooks get called?
I made a test module and only a few of my hooks seem to get called. I get the Javascript console messages for the block\_view, form\_alter and form\_user\_login\_alter hook functions when I do the corresponding actions. However, when I login, logout, view a node, create a node or delete a node I get nothing in the console. Shouldn't these hooks get called when I do those things? I reset my cache, disabled and enabled my module multiple times. Here is the code for test\_module.module:

```
<?php

function console_log ($stringIn) {
    print "<script>console.log('" . $stringIn . "');</script>";
}
function test_module_help ($path, $arg) {
    switch($path) {
        case "admin/help#test_module":
            return '<p>' . t("This is just a test module right now.") . '</p>';
            break;
    }
}
function test_module_insert ($node) {
    console_log("node inserted");
}
function test_module_user_login_submit (&$form, &$form_state) {
    console_log("login submitted");
}
function test_module_block_view ($delta = '') {
    console_log("block viewed");
}
function test_module_user_login (&$edit, $account) {
    console_log("user logged in");
}
function test_module_user_logout ($account) {
    console_log("user logged out");
}
function test_module_view ($node, $view_mode) {
    console_log("node viewed");
}
function test_module_form_alter (&$form, $form_state, $form_id) {
    console_log("form altered");
}
function test_module_delete ($node) {
    console_log("node deleted");
}
function test_module_form_user_login_alter(&$form, &$form_state, $form_id) {
    console_log("user login form altered");
}

```

Here is the test\_module.info file:

```
name = Test Module
description = just a test module
package = ZZ Test category
core = 7.x

```

Those two files are in sites/all/modules/test\_module/

What am I doing wrong?

# Answer
I'm surprised doing a 'print' works at all and does not produce a headers already sent error.
Your hooks may well be being called.
Instead of calling your own console.log function, install the devel module and call dpm('my message');
It will give you a much better idea of what hook is and is not being called.

eg. (your module with devel enabled).

```
function test_module_help ($path, $arg) {
    switch($path) {
        case "admin/help#test_module":
            return '<p>' . t("This is just a test module right now.") . '</p>';
            break;
    }
}
function test_module_insert ($node) {
    dpm("node inserted");
}
function test_module_user_login_submit (&$form, &$form_state) {
    dpm("login submitted");
}
function test_module_block_view ($delta = '') {
    dpm("block viewed");
}
function test_module_user_login (&$edit, $account) {
    dpm("user logged in");
}
function test_module_user_logout ($account) {
    dpm("user logged out");
}
function test_module_view ($node, $view_mode) {
    dpm("node viewed");
}
function test_module_form_alter (&$form, $form_state, $form_id) {
    dpm("form altered");
}
function test_module_delete ($node) {
    dpm("node deleted");
}
function test_module_form_user_login_alter(&$form, &$form_state, $form_id) {
    dpm("user login form altered");
}

```
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How do you add captions to each image of Flexslider? (already tried Google!)
First of all, I tried to search the answer in Google, there weren't many results and those who were weren't very informative, clear, stepped, or guiding. I've also checked Youtube, and I found something that seem too general and too long for this purpose.

What I look for is the simplest way to add **overlay captions** to Flexslider images. The captions should be different **per image** and I need these captions to contain **both** a **headline** and a **body** texts (That's why I've guessed that the image title field won't be enough by itself and that the solution should come from another place).

Please give me some guidance, for example, where do I even start to get this, what is the logical place to put the text in per image? (I guess it wouldn't be CSS content), what are the ways to do it, etc... And I hope that your good and didactic guidance will endure for all users to come.

# Answer
> 0 votes
Well, after investigating for a short solution, and one that involves the minimal number of modules, it seems that as of 2/1/2015 there are 2 main ways to give per-images captions, to the images of the slider. It's good to Install Flexslider and creating a working slider-View of images, and right afterwards, implement one of these ways below.

**The first way:**

Install the module Image Field Caption. It's install is simple but you might have to do about 10 minutes of CSS:

After you have installed the module your images will now have (besides the potential ALT\Title attributes) a third attribute named Caption. You can easily edit it and it can also integrate with CKeditor.

After you have printed the captions you could add some CSS. as of 2/1/2015, the captions appear naturally under the picture, but if you want it to be over the picture (not above, but flying over, in it's bottom for example) with some nice transparent background, just edit the CSS property "Blockquoute" and make sure you give it:

`"Position: Absolute; right: 0; left: 0; bottom: 0; rgba(#,#,#,0.#); width: #%; height: auto;`. The rest is rather simple...

**The second way:**

2 CSS guys I spoke seem to would have preferred this option, though bear in mind that it contains 2 modules instead of 1, in the first solution:

Make the images of the Slider appear as CSS **backgrounds**. This could be achieved via the module CSS Injector. After the images been presented as backgrounds, a way must be found to print a caption attribute below or on the Image. one way to print it is via the module mentioned above - **Image Field Caption**. The other is to print the image's very own Title attribute via the module image caption formatter.

All luck, Ben.

---
Tags: javascript
---


title: Required for Publishing

text:
# Question
Title: Required for Publishing
For my drupal I want an article always to have an image when it's published, however the authors do no have the rights to upload images (due to copyrighting issues, I only let this be done by a few people who have access to our photo partner, just to be sure that people don't download images from google)

So I want the image field to be required when publishing, but if I put it on required, then the authors have to fill it in during the draft as well, and they don't have the access for it.

I found the following module:

https://www.drupal.org/project/required\_for\_pub

But it requires a module "content" which I can't seem to find anywhere. Does anyone have a suggestion for me?

Thank you very much

# Answer
> 2 votes
You can use the required by role module: https://www.drupal.org/project/required\_by\_role to make sure the publishers have to add an image. The downside is publishers will need to upload an image, even when not publishing.

---
Tags: nodes
---


# Question
Title: Limit the number of uploads per image field depending of role
I need a hook (or something similar) where I can set the number of image uploads depending of the role of the user.

In the settings of the field there is no way to set the maximum number of values users can enter, just one value for all roles. For example, for role #1 I want the users can upload just 3 images, for role #2 just 5 images.

I tried several ways but none worked. I tried using #element\_validate but the validation never worked.

Is there some way to do that? I forgot to mention is for Drupal 7.

# Answer
> 0 votes
**Solution1** Limit on the form:

```
function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    global $user;
    // Only allow to upload 2 images for role = staff
    if (in_array('staff', $user->roles)) {
      $center_image_limit = 2;
      $form['#field_info']['field_center_image']['multiple'] = $center_image_limit;
      $i = 1;
      foreach ($form['field_center_image'] as $key => $value) {
        if (is_numeric($key)) {
          if ($i > $center_image_limit) {
            unset($form['field_center_image'][$key]);
          }
          $i++;
        }
      }
    }
  }
}

```

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 1

**Solution2** Limit in validation:

```
function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    // Add the extra validation
    array_unshift($form['#validate'], '<module>_addtional_validate');
  }
}

function <module>_addtional_validate($form, $form_state) {
  $count = 0;
  foreach($form_state['values']['field_center_video'] as $video) {
    if (!empty($video['value'])) {
      $count++;
    }
  }

  global $user;
  // Only allow to upload 2 videos for role = staff
  if (in_array('staff', $user->roles)) {
    if ($count > 2) {
      form_set_error('field_center_video', t('You cannot upload more than 2 videos'));
    }
  }
}

```

Source: DRUPAL – LIMIT THE NUMBER OF VALUES OF A CONTENT TYPE FIELD BY ROLE @ 2

# Answer
> 0 votes
Check if File Field Role Limit module works for image field as well, the module page says

> The Filefield Role Limit module works also with ImageField module.

But since image field is moved to core so I am not sure if this module will work out of the box. In case not, it can give you a starting point for building this functionality, best would be to create a issue for feature request on module page and start fixing the module to make it work and contribute back :)

---
Tags: 7, media, users, files
---


# Question
Title: How do I control the available options for an exposed filter?
I have an exposed filter "country" for my member list view (I'm using addressfield module to store the country). I would like to only show countries in my exposed filters where I have members. I can manually restrict the filter by select countries.

Which one would be the best option, between the following ones?

* theming views-exposed-form.tpl.php
* using `hook_form_alter()`
* hiding some fields with CSS

# Answer
I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

```
<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

```

Then, in your module's .info file, add the file containing this class (in this example, 'custom\_handler\_filter\_countries.inc') to the .info file's files array (`files[] = includes/custom_handler_filter_countries.inc`).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in `hook_views_pre_view()`, I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.
> 11 votes

# Answer
My team once attempted to do the same, in D6. Details are a bit hazy by now, but I'll share my experience and solution.

Initially, we went with a `hook_form_alter()` solution that removed all non-existant entries.

In our particular case however, we had several displays with exposed blocks, and as far as we could determine, views gave them the same form-id, making the solution "unstable". For this reason, we implemented the form ourselves. This may or may not be an issue for you, depending on Core/Views version, and number of displays.

We ended up implementing a new block, copied the form structure from Views so it would be recognized as an exposed form, and *added* the existing entries instead of *removing* the non-existent ones.

The solution works, but if I were to do it again, I would look at the Views Selective Exposed Filters module first, and see how it's done.
There is also an "official" attempt to solve this.
> 4 votes

# Answer
First of all, what do you mean by programmatically? I have a sense that you don't mean that you ABSOLUTELY NEED to write code in order to achieve your goal, but you basically want your view to "automatically" filter the exposed filters for you (based on which ones are being used).

What you actually need to do is get a count of the countries that have members. There was a module for that kind of thing in Drupal 6 (Term Node Count) which was specifically targeted to retrieve the number of nodes attached to a particular term.

The thing is, though, that you don't even need a module for that. With Views 3 you can use Relationships and the "Group By" option (Group Type: Count) to have your View determine on the fly if there are any nodes that are using this country.

If you absolutely need custom code for your solution, I would recommend taking a look at the attempt for D7 Port for Term Node Count or a very simple (rather general though) explanation of how to setup your Views with relationships to achieve your goal can be found in this comment from the same Term Node Count port discussion.
> 3 votes

# Answer
The Views selective filters module will only show options that are present in the result set, perfect for this use case.

> This module allows to have an exposed filter only show options that belong to result set.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Display articles on home page in a news site - layout style.
We are creating a new site for our online news platform with drupal 7, and want to display al our recent news articles in a news site layout style. (like our local news paper and many other news paper websites (http://www.demorgen.be/)). Until now, the articles were displayed in a list-style-layout, each article below another, but we want to change that...

# Answer
> 0 votes
Drupal7's default frontpage is not very configurable. You need to create your own front page in order to have it your way. One of the best way to do this is with the views module.

The general steps are: Create a new view. Add the fields that are relevant to your display (images, titles, etc) then change the homepage of your site to the link of your new view in /admin/config/system/site-information. To be more specific:

* Go to /admin/structure/views/add
* Enter a title for your view, choose content, of type (choose the relevant type where your news are stored) and the sort you wish
* Check create a page
* Enter a title and a path. Remember this path (could be ex: myfrontpage) as this will be the path you will enter in /admin/config/system/site-information
* Choose display format as unformatted list of fields and choose number of items to display on your frontpage
* Click continue & edit, this will allow you to add more fields (such as images, etc) to your view under the 'Fields' section (first column)
* Save your view
* Go to /admin/config/system/site-information and enter the path of your view

There's also an example frontpage view available in the disabled views at admin/structure/views. You can enable it instead and work with this one. This one has 'frontpage' as path that you need to enter in /admin/config/system/site-information

Views has a quite steep learning curve but once you start mastering it, it becomes your best Drupal friend :). Here are some excellent tutorials:

Good luck

---
Tags: nodes
---


title: Views: Show All Distinct Dates

text:
# Question
Title: Views: Show All Distinct Dates
I have a custom content type with a date field that includes year, month, day, hour and minute. If I create a view of all the node start dates I get something like this

```
2014-10-23 13:00:00
2014-10-24 18:30:00
2014-10-24 21:00:00
2014-10-25 09:30:00
2014-10-25 10:00:00
2014-10-25 13:00:00
2014-10-25 18:30:00
2014-10-25 21:00:00

```

I want to create a view that lists only the unique *days* in ascending order. If possible I'd also like to rewrite these as links. Ideally I'm looking to generate something like

```
Thursday, October 23 2014
Friday, October 24 2014
Saturday, October 25 2014

```

or even better

```
<a href='date-2014-10-23'>Thursday, October 23 2014</a>
<a href='date-2014-10-24'>Friday, October 24 2014</a>
<a href='date-2014-10-25'>Saturday, October 25 2014</a>

```

I've tried aggregating but I have to install extra modules to get the day granularity and even then I can't sort by date ASC. I've tried grouping but that just add extra headers I can't rewrite as links plus it means I still output a line for each node like this

```
Thursday, October 23 2014

Thursday, October 23 2014
Thursday, October 23 2014
Thursday, October 23 2014

Friday, October 24 2014

Friday, October 24 2014
Friday, October 24 2014

Saturday, October 25 2014

Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014

```

because the view is only using one field and if I hide it the view doesn't work. I've also used 'Distinct' and 'Pure Distinct' but they don't seem to do anything.

Is there something I'm misunderstanding? I don't get why this is so much trouble to do.

# Answer
This video https://www.youtube.com/watch?v=Cp2SPiwA2Qg shows exactly wat you want. I ussualy follow these steps:

1. Add a second date field to the view.
2. In the configuration of that field

1. Configure the field to only display the year
    2. Exclude the field from display
3. In the format settings of the view, group by this field.
> 0 votes

---
Tags: datetime, views
---


# Question
Title: How to add alt and title attributes to an image gallery View?
I am using Views to generate an image gallery. Each image is linked to the content the images comes from, but what I would also like is to add alt and/or title attributes to each of the images. How would I go about doing this?

# Answer
You can modify the output by selecting the option to re-write output of the field.

Likely, you will want to change the output of your image field from an image to the "URL to file" option. You will also likely need to add other fields to your view (e.g., image title), which you will want to hide (an option in for views fields). Make sure these occur before your image field in the views fields dialog box.

Next you will want to rewrite your image field (check the "Rewrite the output of this field" option for your image field). Views will now show you a box where you can specify the format of your image field, you will likely what to use something such as

```
<img src="[field_gallery_image_fid]" title="[title]" alt="[title]" />

```

Views will then replace the `[field_gallery_image_fid]` macro with the "URL to file" info, and replace the `[title]` macro with the node title (assuming you added that field ahead of the image field.

In the field rewrite interface views will provide you with a list of macros/fields you can add, all of these fields must occur prior to the field you are rewriting. If you don't want those fields displayed (other than in the rewrite) make sure to check the "Exclude from display" option on a given field.
> 4 votes

# Answer
Go to each content type having image field used in views :

```
<YOUR_SITE>/admin/structure/types/manage/<YOUR_CONTENT_TYPE>/fields/<YOUR_IMAGE_FIELD>
Eg :
/admin/structure/types/manage/gallery/fields/field_gallery_images

```

Check :

```
Enable Alt field
Enable Title field

```

This will provide 2 additional fields on each image to specify the alt and title attributes.
Views will add them automatically.

Credits : http://www.inmotionhosting.com/support/edu/drupal-7/working-with-content/enable-image-alt-text
> 0 votes

---
Tags: views, media
---


# Question
Title: Custom #ajax "Add another" button only adds 1
This form consists of 1 textfield, and 1 ajax button.

I'm trying to make it add another text field with each click.

It works for the first one, to get a total of 2 text fields. I cannot get more than 2 to appear though.

I suspect the dom is being updated, but not the form. So the subsequent callbacks add an element based on the original form build.

I'm not sure how to approach this in Drupal 8. Any insight would be appreciated.

Here is my form control

```
<?php
...
class MyModuleForm extends FormBase {
  ...
  public function buildForm(array $form, array &$form_state) {
    $form['foo'] = array(
      '#type' => 'container',
      '#tree' => TRUE,
      '#prefix' => '<div id="foo-replace">',
      '#suffix' => '</div>'
    );
    $form['foo'][0] = array(
      '#type' => 'textfield'
    );
    $form['add'] = array(
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => t('Add'),
      '#ajax' => array(
        'callback' => array($this, 'addMore'),
        'wrapper' => 'foo-replace',
        'effect' => 'fade',
      ),
    );
    return $form;
  }

  public function addMore(array $form, array &$form_state) {
    $form['foo'][] = array(
      '#type' => 'textfield'
    );
    return $form['foo'];
  }
}

```

# Answer
> 4 votes
I spent more time with `WidgetBase` from the field module.

The solution was to define a `#submit` handler on the ajax button. In the submit handler, set `$form_state['rebuild'] = TRUE`. This will allow the form to rebuild with `buildForm`.

Based on core code comments, this is the proper way to gracefully degrade so it works without JS as well. I like it, no need read `$form_state` for `triggering_element`.

Note that adding `$form_state['rebuild']` to `submitForm` will not trigger a rebuild from an ajax button. (from my testing anyway)

Once the form is rebuilding, it's like D7. You can add the handler logic in `buildForm` as Mołot pointed out, and return just the target element in your callback.

Here's the final working form:

```
<?php
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;

class MyModuleForm extends FormBase {

  public function getFormId() {
    return 'mymodule_form';
  }

  public function buildForm(array $form, array &$form_state) {
    // Initialize the counter if it hasn't been set.
    if (!isset($form_state['fields'])) {
      // Nested this deep to avoid conflicts with other modules
      $form_state['fields'] = array(
        'mymodule' => array(
          'foo' => array(
            'items_count' => 1
          )
        )
      );
    }

    $max = $form_state['fields']['mymodule']['foo']['items_count'];
    $form['foo'] = array(
      '#tree' => TRUE,
      '#prefix' => '<div id="foo-replace">',
      '#suffix' => '</div>'
    );

    // Add elements that don't already exist
    for ($delta = 0; $delta < $max; $delta++) {
      if (!isset($form['foo'][$delta])) {
        $element = array(
          '#type' => 'textfield'
        );
        $form['foo'][$delta] = $element;
      }
    }

    $form['add'] = array(
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => t('Add'),
      '#submit' => array(array($this, 'addMoreSubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addMoreCallback'),
        'wrapper' => 'foo-replace',
        'effect' => 'fade',
      ),
    );
    return $form;
  }

  public function addMoreSubmit(array &$form, array &$form_state) {
    $form_state['fields']['mymodule']['foo']['items_count']++;
    $form_state['rebuild'] = TRUE;
  }

  public function addMoreCallback(array &$form, array &$form_state) {
    return $form['foo'];
  }

  public function validateForm(array &$form, array &$form_state) {

  }

  public function submitForm(array &$form, array &$form_state) {
  }
}

```

# Answer
> 4 votes
You made a common mistake. In Form API, `['#ajax']['callback']` has only 2 purposes:

* Make one-time changes to form, that are *not* meant to persist form reload, submit or second Ajax request. Good example is adding some classes to freshly modified element.
* Return proper part of the form.

To have persistent changes, you need to keep the number of elements you want somewhere, for example in `$form_state`, and add them in form builder function, `buildForm` in your case.

My approach would be to check `$form_state['triggering_element']` to see if it was your Ajax button to invoke form building, and if so, increase counter. Then simply `for($i = 0; $i < $element_counter; ++$i)` to add required number of elements.

# Answer
> 3 votes
Some of the nuts and bolts of this answer have changed as the Drupal 8 APIs have evolved and "solidified". While the general approach of manipulating the form works. The $form\_state param can not be used as an array, and must be an object of type FormStateInterface. The method signatures should look like:

`public function buildForm(array &$form, FormStateInterface &$form_state)`

The $form\_state class also has methods getting for setting arbitrary data. Simply,  `$form_state->get(property, value)`  and  `$form_state->set(property, value)`  in this context. Here's a link to get started with the set method: FormStateInterface::set. And a link to a Gist

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


title: Block field to referene a view

text:
# Question
Title: Block field to referene a view
I am struggling to find a way for a custom block type of mine to reference a view. Basically I want a field of the block to show some of the newest articles.

Using the entity reference field and an entity reference view I must select the articles to show manually.

Is there a simple way to use the entity reference field to render the contents of a view or a view block? Or do I need to code it myself? Thanks in advance.

# Answer
> 0 votes
You can use https://www.drupal.org/project/viewfield to reference views and even pass arguments.

---
Tags: views, blocks, entities, 8
---


title: Override contributed module function

text:
# Question
Title: Override contributed module function
I'm wondering if it's possible to override a contributed modules hook\_menu function.

```
/**
* Implementation of hook_menu().
*/ function jquery_ajax_load_menu() {   // Admin settings.   $items['admin/config/development/jquery_ajax_load'] = array(
    'title' => 'JQuery AJAX Load',
    'description' => 'Shows any page on a AJAX link',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('jquery_ajax_load_admin'),
    'access arguments' => array('administer site configuration'),   );   // Only to generate a TAB   $items['admin/config/development/jquery_ajax_load/link'] = array(
    'title' => 'JQuery AJAX Load',
    'type' => MENU_DEFAULT_LOCAL_TASK,   );   // Prefix for AJAX requests   $items['jquery_ajax_load/get'] = array(
    'page callback' => 'jquery_ajax_load_callback',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'delivery callback' => 'jquery_ajax_load_delivery_callback',   );   return $items; }

```

Essentially I want to override the **'delivery callback' =\> 'jquery\_ajax\_load\_delivery\_callback',** So that it calls a modified version of the same function, as apposed to hacking the module. **'delivery callback' =\> 'mymodified\_jquery\_ajax\_load\_delivery\_callback',**

# Answer
> 2 votes
Use `hook_menu_alter(&$items)`.

```
function yourModule_menu_alter(&$items) {
  $items['jquery_ajax_load/get']['delivery callback'] = 'yourModule_jquery_ajax_load_delivery_callback';
}

```

That's clean and "Drupal way" to solve your problem.

# Answer
> 0 votes
```
<?php
/**
 * Implementation of hook_menu_alter().
 */
function jplayer_helper_menu_alter(&$items) {

  // Unset menu item
  unset($items['jquery_ajax_load/get']);

  // Add modified menu item
  $items['jquery_ajax_load/get'] = array(
    'page callback' => 'jquery_ajax_load_callback',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'delivery callback' => 'modified_jquery_ajax_load_delivery_callback',
  );
  return $items;
}

```

---
Tags: routes
---


# Question
Title: How can I remove the "The image was resized to fit within the maximum allowed dimensions..." message without hacking core?
By default, Drupal prints out a notification message that images exceeding the maximum dimensions were resized. I want to disable this message.

The relevant line is located in file\_validate\_image\_resolution():

```
  drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));

```

Obviously, the quick way to do this is to put two little slashes right before the line. But I am trying to do this without hacking core. I copied the entire function into `MYMODULE_file_validate_image_resolution()`, then commented the lines out, but this had no effect. What's the right way to do this?

# Answer
Disable Messages module helps you to disable any type of message in drupal.

It module has following features.

* Filter out messages that match a full text string exactly.
* Filter out messages that match a regular expression.
* Permissions to specifically hide all messages of a given type from any role.
* Disable all filtering for specific users.
* Disable all filtering for specific paths.
* Apply filtering only for specific paths.
* Debug system to get messages in the HTML without showing it to the end users.

Once you install the module you can see the configuration options at admin/config/development/disable-messages.

For your requirement just enter following text in "Messages to be disabled:" textarea.

```
The image was resized to fit within the maximum allowed dimensions of .*? pixels.

```

Note : Make sure necessary permission to be set like below.
> 6 votes

# Answer
You can use hook\_file\_validate like this.

```
function mymodule_file_validate($file) {
  if (form_get_errors()) {

    // Save errors
    $form_errors = form_get_errors();
    $drupal_errors = drupal_get_messages('error');
    // Clear form errors
    form_clear_error();

    foreach($drupal_errors['error'] as $key => $error) {
      if (in_array($error, $form_errors)) {
        // Unset form errors
        unset($drupal_errors['error'][$key]);
      }
    }

    // Rebuild drupal errors
    foreach($form_errors as $key => $message) {
      if(strpos($message, 'old message') !== false) {
        $message = str_replace('old message', 'new message', $message);
        $_SESSION['messages']['error'][$key] = $message;
        form_set_error($key, $message);
      } else {
        form_set_error($key, $message);
      }
    }
  }
}

```

I think it helps you.
> 0 votes

# Answer
1) You can remove the message in `hook_file_validate`, `hook_theme_registry_alter` or on page load:

```
  $message = t('YOUR MESSAGE');
  foreach ($_SESSION['messages']['status'] as $status => $statusmessage) {
    if ($message == $statusmessage) {
      unset($_SESSION['messages']['status'][$status]);
    }
  }

```

2) You can try to replace core validator of your image field widget with a custom one in `#upload_validators` using `hook_field_widget_form_alter`.

3) You can remove `file_validate_image_resolution` from `#upload_validators` and do your validation without message in `hook_file_validate`.
> 0 votes

# Answer
Another way to do this would be to use a hook\_form\_user\_register\_alter to add your own submit handler, and within it be sure to call drupal\_get\_messages() with the clear\_queue variable set to true. This will also clear out messages from the queue. Hope this helps!
> 0 votes

# Answer
alter the form your submitting

add another function in the $form\[#submit\] like so

```
$form['#submit'][] = 'yourFunction';

```

then and your function

```
function yourFunction(){
    drupal_get_messages();
    //you can also set your messages here.
}

```
> 0 votes

---
Tags: hooks
---


# Question
Title: Panels in-place editor shortcut won't appear from gear wheel
I use Drupal 7.34, and Panels module suit version 3.4.7.

The Panels in-place editor shortcut refuses to show up after I click on the gear wheel of a Mini-Panel...

1. Tried to reinstall, didn't help.
2. Tried to change Render mode from Default to "In-place editor" in the settings page. Didn't help.
3. Tried to clear cache afterwards. Didn't help.
4. No serious solution appeared in a Google search...

Is it bug?... What else can cause it not to appear?

# Answer
Tried to reproduce this with Drupal 7.34 and Panels 7.x-3.4. I created a page, selected In-Place editor for Renderer under General tab of the Panels edit page, added some blocks and added a Mini panel with blocks in it, went to the page and all the gear icons work. Maybe some JS issue is causing this?

**Update**

Based on checks, I think Contextual links displays the edit link for the "renderer" only. Ex. if Blocks is displaying the Mini-panel, the contextual link module displays the "Configure block" link. Same for Panels with mini-panels rendered inside it. So that's the explanation why the "Edit mini-panel" link isn't displayed under the "gear" icon.

**NOTE: Please correct me if I'm wrong with this analogy though because this is just based on observation**

**Solution 1**: Using the Custom Contextual Links. Though this uses Tokens it doesn't get the mini-panel's name so if you had 10 mini-panels you should create 10 CCLs also w/c would be quite tedious though but of course if it's needed, nothing is tedious I guess? :)

**Solution 2**: Creating a custom module that would check each rendered "block" in a page is a mini-panel and if it is, display both the "renderer's" link and add the mini-panels link.
> 1 votes

---
Tags: panels, theming
---


title: Setting event date in views

text:
# Question
Title: Setting event date in views
i have events page on my Drupal and it is showing events until the relative date (is greater than) "now" which means the event disappears from the table on the starting date of the event.

Can you please help me with setting that date **to the last day of the event** \- so that the event stays on the table until the last day. I have multiple events, so i really dont know how to do this. I checked other relative formats, but i am no developer, so i am puzzled. Thank you in advance.

# Answer
If your node contains Date field than you can set start and end date (you can turn on/off end date field in field settings). Both are available in Views so instead of building your Views filter on start date, build it on end date.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: drupal 7 profile 2 how to create field profile url as NAME
Why is it so hard to create a view so others can see it? I just read the instructions at dupal.org documentation and checked out ep#33 of daily dose but neither are helping.

My view is set up with a grid of fields filtered by type main profile. I can't get the names as link to profile; all I can get is profile:url which looks ridiculous.

How can I get my profile:url field to be the link for a name?

\[url\] == Profile: URL \<--- how is this inputed for replacement field?

# Answer
> 0 votes
Worked it out finally.

You need to add fields in correct order to then use replacement which is \[url\]

for link to profile name.

---
Tags: users
---


# Question
Title: Additional validation after successful login
I want to implement some additional validation steps right after a user has logged in to a Drupal site.

So far, I have implemented the additional validation inside `hook_user_login`. If the validation fails, I am forcing the logout by calling `user_logout`.

---

**EDIT**: Part of the users are authenticated through an external SSO, so altering the login form to add an additional validation does not seem to be a good solution.

---

Is this the most standard way to do it, or is there a better way?

# Answer
> 1 votes
Thanks Marcin and skh for your answers. Unfortunately, it seems my case is quite specific. I will post below my solution in case someone else has a similar situation:

**NOTE**: This solution assumes the site is receiving logins not coming from the standard login form. If all the logins are coming through the standard login form, it is much better to add a `#validate`in hook\_form\_alter, as mentioned above.

If logins to the site come from different places (such as SSO), my solution has been to implement `hook_user_login`:

```
function MYMODULE_user_login(&$edit, $account) {
  $additional_validation_result = MYMODULE_additional_validation($account);
  if ($additional_validation_result === TRUE) {
    // Additional validation passed. Just return
    return;
  }
  else {
    // Additional validation failed. Force logout
    module_load_include('pages.inc', 'user');
    user_logout();
  }
}

```

Comments and improvements are welcome.

# Answer
> 4 votes
If You want to abort login I think You should try to add own validate function to user\_login whith hook\_form\_alter (https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7)

```
<?php
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') { // or $form_id = 'user_login_form'
    $form['#validate'][] = 'check_username_against_ad_hoc_service';
  }
}

function check_username_against_ad_hoc_service($form, &$form_state) {
  $name = $form_state['values']['name'];

  if($name == 'NoGo') {
    form_set_error('name', 'You're an Ad-hoc!');
  }
}
?>

```

You can also use function hook\_form\_FORM\_ID\_alter (https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_FORM\_ID\_alter/7)

# Answer
> 2 votes
As mentioned, you could add a `#validate` in `hook_form_user_login_form_alter()` and just set a form error.

However, if you're validating against an external service and perhaps getting user info from that endpoint, the 'most standard' way is probably to use user\_external\_login\_register().

---
Tags: 7, users
---


# Question
Title: JS error when using AddThis field displayed in a view
I keep getting this error:

ReferenceError: jQuery is not defined }(jQuery));

when using an addthis field displayed in a view.

Anyone has a clue what could be going on here?

# Answer
> 0 votes
AddThis includes it's javascript in the footer. It could be possible that, in your case, you have to add addThis in the header.

You can do this by changing this line of code in the addthis.php:

AddThis.php line 274 comment:

```
'scope' => 'footer’,

```

Hopes this help you out!

---
Tags: views, javascript
---


# Question
Title: I can't remove an manage_file field image
I have the next managed\_file field:

```
$form['portada_field']['imagen_portada'] = array(
            '#title' => t('Imagen'),
            '#type' => 'managed_file',
            '#description' => t('Extensiones permitidas: gif png jpg jpeg'),
            '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
            '#upload_location' => 'public://articulos/portada',
            '#progress_indicator' => 'throbber',
            '#status' => FILE_STATUS_PERMANENT,
            '#progress_message' => 'One moment while we save your file...',
                '#states' => array(
                    'visible' => array(
                      ':input[name="checkbox_imagen"]' => array('checked' => TRUE),
                    ),
                ),
         );

```

After upload an image, If I want to remove the image I can't do it, it appears again

How I can remove it?

Thank you very much.

# Answer
> 0 votes
You can use db query to remove the entry

```
  $mydir =  variable_get('file_public_path', conf_path() . '/files');
  $filename = $mydir .$file_directory. $filename;
  unlink($filename);
  db_delete('file_managed')
      ->condition('filename', $filename)
      ->execute();
  $FileStatus = "The file has been removed - ".$filename;

```

Get the public directory path and delete the file from file\_managed table

This will make your work easy.

---
Tags: forms, files
---


title: How to display plain html

text:
# Question
Title: How to display plain html
I have inherited a drupal site with a few modules. They're not exactly written according to best practices... they return html code instead of renderable arrays. In other words, they do this:

```
function custommodule(){
 $output = '<p> Some output. </p> <p> Some more output. </p>';
 return $output;
}

```

Instead of this:

```
function custommodule(){
   $args = array( arg1, arg2 );
   return theme('sometheme', $args);
}

```

The output is supposed to be displayed in the content region. However, since plain html is returned that is not wrapped in a node or anything like that, the output gets scattered all over my page... for example, the text `Some output.` appears above the navigation, `Some more output.` appears underneath the footer, etc.

By the way, the page-array has the returned markup (the `$output` from above) in this place:

```
page['content']['system_main']['main']['#markup']

```

Whereas for example a typical article would have its #markup in

```
page['content']['system_main']['nodes'][$nid]['body'][0]['#markup']

```

So I guess drupal doesn't realize I would like my output to be in the content region?

Is there any way I can safely render that unpleasant html?

Thanks a lot in advance!!

# Answer
Once again, the problem sat in front of the screen ;)

Like @rooby said, there was a mistake in the html returned. A missing `</table>` tag messed up my layout. Adjusting this solved my problem. Thanks!!

But to be able to influence the layout of custom html a bit more generally, I did this:

When a module returns output without first passing it through a theme function, it ends up in `page['content']['system_main']['main']['#markup']`, whereas in a normal page, there would be no #markup on this level of the page array, only elements like `node`, `pager`, `#block` etc. So finding `page['content']['system_main']['main']['#markup']` means some custom code has been returned by some custom module.

So in my theme's template.php, I implemented

```
function mytheme_preprocess_page(&$variables, $hook) {
    if ( $variables['page']['content']['system_main']['main']['#markup'] ){
        $variables['page']['content']['system_main']['main']['#markup'] = '<div class="customcontent">' . $variables['page']['content']['system_main']['main']['#markup'] . '</div>';
 }
}

```

Thank you guys very much! Always awesome how good the feedback in the drupal community is.
> 0 votes

---
Tags: 7, nodes, theming
---


# Question
Title: How do I access a node object property, if it is an array?
```
$node = \Drupal\node\Entity\Node::load($nid);

```

Having loaded a node object in Drupal 8, I know how to access a property, if it is a single value, and assign it to a variable, `$test` in the example below:

```
$test = $node->field_1->value;

```

However, if `$node->field_1` contains an array, how do I access it so that I can assign it to `$test`? So `$test` would equal something like:

```
array(0 => 'apples', 1 => 'oranges')

```

# Answer
> 9 votes
There's no real need to convert it to an array, as you can already access members of a `FieldItemList` as an array:

```
$first = $node->field_1[0]->value;
$next = $node->field_1[1]->value;

```

This:

```
$node->field_1->value;

```

Is just a shortcut to the first item in the collection anyway (see `FieldItemList::__get()`).

If you need the values in exactly the format you specified, `FieldItemList` is also iterable:

```
foreach ($node->field_1 as $delta => $item) {
  $an_array[$delta] = $item->value;
}

```

---
Tags: 8
---


# Question
Title: Exclude a single module from a Drush update?
Is there a way to exclude a module from a Drush update so it can be ignored when running eg 'drush up' ?

I ask because Rules 2.8 is causing problems with Drupal Commerce but it would be great if everything else could still be updated with Drush.

# Answer
You can use the following command:

```
drush pm-update --lock=modulename

```

There is a post here about it: http://blog.wassill.eu/en/blog/short-excludes-modules-drush-update-09-04-2013
> 11 votes

---
Tags: drush
---


# Question
Title: Does change of .info file need reinstallation of module to take effect?
Does changing a module's `.info` file require reinstallation of the respective module to take effect?

# Answer
> 2 votes
No, it doesn't. It needs a cache clear though.

---
Tags: installation, .info
---


# Question
Title: How to display entire comments in separate page
I know we can display reply form in separate page. But now I having the requirement of displaying entire comments and reply form in separate page. Is there have any way to display those in separate page.

# Answer
> 1 votes
The Talk module shows the comments for a node in a tab added to the node page.

> The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.
>
> When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.

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


# Question
Title: Omega Theme, change content zone when sidebar had no content
I'm using Omega as Base theme. In the content zone I have 2 regions:

* 'Content region' set as 9 columns
* 'Right column region' set as 3 columns

Is it possible to have a "flexible region"? I want to change the column count when the right column region is empty.

# Answer
Yes, it is possible to change the column count for a region if another region is empty.

1. Go to the layout configuration of the Omega 3 Subtheme
2. Go to the zone that's the parent of the specific region
3. Set "Primary Region" to the region you want to give a flexible column count
> 0 votes

---
Tags: theming
---


title: Marketplace fee on each product

text:
# Question
Title: Marketplace fee on each product
I am trying to create marketplace like etsy, where each user can add as many products as they want.

What i want to do is to globaly set a fee of 5% on each product.

So for example: User creates product A with price of 10$. After he clicks save price shown is 11$.

# Answer
Simply add a Rule upon the event Calculating sell price of Product. Multiply price by an amount is probably the Rules event you want to be using.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: how to get XML content over HTTP request?
I'm building a module and I need to get XML content over HTTP request.

The idea is to create nodes programmatically with the retrieved data from the xml file.

Can I do this?

# Answer
Its a little bit of a learning curve , but I would recommend using the feeds module for this

https://www.drupal.org/project/feeds

you can then load xml (or csv) to nodes, and map its contents to nodes. This is preferable to writing your own custom functionality.

but if you do, drupal\_http\_request(), and then node\_save() for constructing the nodes would be the way to do things. If you do code it yourself, Id recommend getting comfortable with running scripts with drush, as that'll be easier than battling timeouts in the browser
> 3 votes

---
Tags: 7
---


# Question
Title: Display Vocabulary (VID) From Selected Field
I'm trying to print out the selected vocabulary from a content type on a page. As the previous user did not use views for this layout, I need to find a way to add it.

Here is my code so far.

foreach ( (array)$node-\>taxonomy as $term ) { echo $term-\>name; }?\>

Right now, it shows all of the terms that are listed in my taxonomy. Is there a way to narrow this down? to only show selected vid?

Regards,

# Answer
> 0 votes
Answering my own question for future purposes:

```
<?php

```

$vocabularies = taxonomy\_get\_vocabularies(); if ($vocabularies) { foreach($vocabularies as $vocabulary) { if ($vocabulary-\>vid == 1) { $terms = taxonomy\_node\_get\_terms\_by\_vocabulary($node, $vocabulary-\>vid); if ($terms) { foreach ($terms as $term) { print $term-\>name; } } } } } ?\>

Did the trick.

---
Tags: taxonomy-terms
---


title: Creating new Invite Type

text:
# Question
Title: Creating new Invite Type
When trying to create new invite type from *admin/structure/invite-types/add* I get this response:

> Sorry no Invitation Type modules available in the system.

I has been researching and there is no info referral to this. And I can not create that invitation type from anywhere, also there is no info to do it programmatically. I get lost into code module but this is the line that returns that message.

# Answer
It is required Invite by e-mail module, it provides an Invite Type.
> 0 votes

---
Tags: 7
---


title: field.tpl.php available variables

text:
# Question
Title: field.tpl.php available variables
According to the documentation, these are the available variables:

```
$items: An array of field values. Use render() to output them.
$label: The item label.
$label_hidden: Whether the label display is set to 'hidden'.
$classes: String of classes that can be used to style contextually through CSS. It can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:
field: The current template type, i.e., "theming hook".
field-name-[field_name]: The current field name. For example, if the field name is "field_description" it would result in "field-name-field-description".
field-type-[field_type]: The current field type. For example, if the field type is "text" it would result in "field-type-text".
field-label-[label_display]: The current label position. For example, if the label position is "above" it would result in "field-label-above".

```

However, I've attempted doing a `print_r($items,1)` (and the others above) and it seems none of these are actually available to me within my `views-view-field--field-download.tpl.php` where `download` is the name of the field I am templating.

> Notice: Undefined variable: items in include() (line 12 of /var/www/sites/path/to/templates/views/views-view-field--field-download.tpl.php).

What am I missing?

---

**EDIT:**

I also found this documentation, but am having a similar problem. It mentions I should have $fields, $view, and $row... but I am having trouble accessing some of these.

I am able to get some information I need using `$row->_field_data["nid"]["entity"]->...`, but how do I output the field as it would normally be output? I have conditionals set up and want to output it as it would normally be on one condition, and output something else on another condition. I am able to get the data for the conditions to work properly... but can't figure out how to output the field as it would normally be.

# Answer
A views field template only has these variables:

```
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

```

This is the default views field template:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

```

You can see what templates you can use by going to your view, then click "advanced" and then next to "Theme", click on "information". This will show you all available templates you can use and override.

Hope this helps you out.
> 1 votes

---
Tags: views, entities, theming
---


# Question
Title: Don't allow "Delete this field" if a module is activated
Inside "Article" type, I have a field called 'field\_xenforo\_thread\_id' (machine name), It's possible to disable the "Delete" option only for this field and only if my module is activated please ?

If the module is activated and if the administrator remove this field, the module is broken and I want prevent this problem.

# Answer
> 1 votes
The module field lock allows you to lock fields for certain roles. You can use that module out of the box or you can copy it and adjust it so that the fields only lock if your module is activated.

---
Tags: 8
---


title: Allow user to translate specific field?

text:
# Question
Title: Allow user to translate specific field?
I have a content type called profile where a user can enter data and thereby create an own profile. Now, most of the profile fields are numeric but two of them are text areas. As my site is in German and English the user should be able to translate these two text area fields (the Input not the Label) but no other fields.

Does somebody know if there's a way to grant translation access to users for specific fields?

# Answer
Entity translation will do the trick :). That module allows you to point out certain fields to be translated without translation the entire node.

https://www.drupal.org/node/1280632 shows you some use cases and examples on how to configure the module.
> 1 votes

---
Tags: entities, i18n-l10n
---


# Question
Title: Display field from referenced entity using Display Suite and Views
I have a view which displays some products (node) teasers.

In the products, I can select a producer (taxonomy term).

Now... In the products teasers I want to display the country, which is a field from the producer taxonomy term. How can I add this field to the teaser using Display Suite?

# Answer
You have to configure a new view mode for vocabularies (admin/structure/ds/view\_modes). Let's call it "country"

Then on your newly created view mode (admin/structure/taxonomy/{tax\_name}/display/county) configure the fields you want to show. In your case this will be the term name and the country.

After you done that you have to go to the manage display of your product content type and select the "teaser" view mode. There, on your taxonomy field, choose "Rendered taxonomy term" as format. Then click the button on the right and choose "country" as view mode.
> 0 votes

---
Tags: views, entities, display-suite, nodes
---