# Question
Title: db_query() is not returning results from a valid query
In short: db\_query of a SELECT statement is returning no results. However, running the SELECT statement in phpMyAdmin vs the database returns thousands of results. I'm using Drupal 6.

What I'm trying to do: The site I'm working on gets thousands of spammers hitting it each day and creating accounts. The accounts are worthless to them, because if they do not pay, they don't get to do anything but log in. I want to safely remove these accounts. Therefore, I'm selecting the accounts based on certain criteria and then want to iterate through each and use the Drupal delete user function to remove the user from Drupal. Right now, I'm just trying to print the info that returns so I can see if I get the correct results before moving on to the delete, which is a simple 1 line addition.

Here's the code:

```
include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";

$results = db_query($query);

print $query;
print "<br/>";
print db_num_rows($results);

foreach ($results as $row) {
        print "<br />";
        print "ID: " & $row['id'];
        print "Name: " & $row['name'];
        print "E-Mail: " & $row['email'];
        print "Role: " & $row['role'];
        print "Created: " & $row['created'];
        print "Deadline: " & $row['deadline'];
}

```

---

For Posterity's (and other people finding this question) sake, here's the final code:

```
include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";

$results = db_query($query);

print "Users To Delete:  " . db_affected_rows($results);

while ($row = db_fetch_array($results)) {
    print "<br />";
    print "Deleting: ";
    print " ID: " . $row['id'];
    print " Name: " . $row['name'];
    print " E-Mail: " . $row['email'];
    print " Role: " . $row['role'];
    print " Created: " . $row['created'];
    print " Deadline: " . $row['deadline'];

//delete the spam user cleanly
user_delete(array(), $row['id']);

    print " Completed.";
}

```

I setup a CRON job to run this weekly to do the clean-up. There's no reason it can't be run more or less often, though.

# Answer
The SQL looks fine, but you're using the wrong versions of the DB API at the moment.

For Drupal 6 you want to use syntax similar to the following:

```
$results = db_query($query);
while ($row = db_fetch_array($results)) {
  print "ID: " . $row['id'];
}

```

There's some good documentation for the D6 API on this post, it's worth a read.

Forgot to mention...`db_num_rows()` is a Drupal 5 function which is why the script is failing. There's a discussion on the alternative methods for D6 here (most involving `COUNT` queries)
> 1 votes

---
Tags: users, database
---


title: Add class to new posts with Views

text:
# Question
Title: Add class to new posts with Views
I have a view (using Views module), which displays a list of all Titles of a custom content type. What I want to do is add a CSS class to the posts that are new (posted within 24 hours for example). I am guessing I need to create a custom module to do this, but am confused where to start. Any help is appreciated.

# Answer
> 0 votes
A custom module is almost certainly overkill here. A simpler strategy is a View with an attachment.

Start with your existing view. You need to add a filter to that view so it only shows OLDER content. So add a filter that looks at the relevant date field, e.g. posted, and apply a test such as less than or equal to NOW - 1 day. This will now show all your titles EXCEPT those that are new.

Next add an attachment. Tweak the filter (make sure you apply an `This attachment (override)` so that your change doesn't affect all displays). This time you want the test to be greater than NOW - 1 day (or whatever period of time is relevant - but it needs to be the inverse, as it were, of the test applied on the first display of the view). Attach the attachment to the first display of your view (page or block as appropriate) and set it to appear BEFORE. This attachment will now show only the NEWER content.

If all that works, you will have the list of titles, both new and old.

The final step is to tweak the CSS. Working on the attachment that has the NEWER entries, go into the field configuration for your title. Again, make sure you select `This attachment (override)` and not `All displays`, i.e. that your change will apply only to the attachment and not the initial display as well. You can then adding the name of a custom class in the field configuration (Style Settings, then one or more of the Customize options, then Create a CSS class) and create a class with corresponding name in your style sheet. Or you may be able to apply sufficient tweaks just by using a rewrite.

# Answer
> 0 votes
You may want to simply make use of the existing field available in views called:

> Content: Has new content values Add that as a field or use it to customize another field, it is pretty handy.

Some more information on what constitutes as NEW or UPDATED: for how long is Content considered "new" by the filter criteria "Content: has new content"?

---
Tags: 7, views, theming
---


# Question
Title: In views, what is the difference between Normal menu entry, Menu tab and Default menu tab
When adding a menu item in views I see three selections that are ambiguius

Normal menu entry

Menu tab

Default menu tab

What is the difference and when would I use each?

# Answer
> 14 votes
They correspond to the `type` parameter of items returned from `hook_menu()`

* Normal menu entry = MENU\_NORMAL\_ITEM

> Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.
>
> Normal menu items show up in the menu tree and can be moved/hidden by the administrator. Use this for most menu items. It is the default value if no menu item type is specified.
* Menu tab = MENU\_LOCAL\_TASK
> Menu type -- A task specific to the parent item, usually rendered as a tab. Local tasks are menu items that describe actions to be performed on their parent item. An example is the path "node/52/edit", which performs the "edit" task on "node/52".
* Default menu tab = MENU\_DEFAULT\_LOCAL\_TASK

> Menu type -- The "default" local task, which is initially active.
>
> Every set of local tasks should provide one "default" task, that links to the same path as its parent when clicked.

The best example I can think of are node pages. When you visit a node page, the 'View' tab is provided by a menu item of type `MENU_DEFAULT_LOCAL_TASK` (see `$items['node/%node/view']` in `node_menu()`).

It doesn't have a path as such (it inherits from the parent menu item), it's only purpose it to allow the node page to have a tab amongst the groups of 'real' tabs, which are defined with `MENU_LOCAL_TASK`.

---
Tags: views, routes
---


# Question
Title: How to tell if a function is being called by javascript?
I have a validation function that is being called either from another php function or a JavaScript call. I was wondering if there is a way to determine if the function is being called by JavaScript so that I can implement different functionality. I am using Drupal 7 for this but if you could post an answer for Drupal 6 too, I am sure that would help out other people as well.

# Answer
JavaScript cannot directly call a PHP function. If you think that JS may be 'triggering' the call of that validation handler, then there must be an AJAX event going out to the backend, which then calls the validation handler. If that is the case, the request will go out to the `system/ajax` URI on your site (unless it has been intentionally changed to a different URI - you can double check this by viewing the 'Network' tab in Google Chrome's developer tools), which will then handle the request and dispatch it to the validation handler.

So...

You can check the `$_GET['q']` value in your validation handler:

```
if ($_GET['q'] == 'system/ajax') {
    // AJAX request
}
else {
    // other request
}

```
> 2 votes

---
Tags: 7, javascript, forms
---


# Question
Title: View does not pick up webform submission is from url
I have created a block that is to print out the currently displayed webform submission. The problem is that it does not pickup the submission id from the url. It is always displays submission id 11 regardless of what submission you are looking at. Can anyone tell what the problem is how to fix it?

The Details: this is for Drupal 7.19 and using views. My block is set up the following way:

```
Contextual Filter: Content Nid
Filter: Content NID = 33
Fields: Content NID
        Web submissions: Sid
        Global Custom Text

```

In global custom text I try and read the nid and sid fields using tokens. The block is only displayed when you view a submission of a specific webform (in this case: webform with node id 33).

Please help as I am desperate here.

Thanks

# Answer
OK. I see the problem. The submission will be for only one node, so all you need to get the information is the sid. The nid you are looking at is not the nid in the webform submission record. (You will understand in a moment.)

First, delete both the contextual filter on Content:nid and the filter on Content:nid.

Then create a contextual filter using Webform Submission:sid. Under 'When the filter value is NOT available', select Provide Default Value \> Raw value from URL, and set the Path Component to 4.

Now to get the correct nid value, you need to create a Relationship on Webform submissions: Node, and check 'Require this relationship'. Now go back to your fields, and edit the Content:nid field changing 'Relationship' to 'Webform Node', and save. Your field should now display as '(Webform Node) Content: Nid (Nid)'. This is the nid found in the Webform Submission record.

Save your view, and you will get the correct values in the block display. I don't know about the token replacements, but it looks like it should work. If not, the Views PHP module will be able to do it without the tokens, using the $row values directly from your view.

Good Luck.
> 1 votes

---
Tags: 7, views
---


# Question
Title: drush perm-grant gives "The drush command 'perm-grant' could not be found"
I am using `drush -u 15 perm-grant --roles="site administrator"` but the command returns:

> The drush command 'perm-grant' could not be found.

any ideas about that? according this documentation the `drush perm-grant` is an available command. or maybe is some limitation of the user used to run drush?

the drush version is 5.4

thanks.

# Answer
according @MDP, Permissions API module is required for this, and according its module page is only for Drupal 6, so this command is not available in drupal 7. @greg\_1\_anderson user recommends to use Drush 8.x-6.x to get this feature working built-in
> 0 votes

---
Tags: 7, users, drush
---


# Question
Title: Using Rules to publish nodes depeding value in Field
I have been trying to figure out how to publish multiple nodes using Rules.

I have content type Parent and content type Child. When Parent is published then Child will be created/published too. This is what I have managed to do with Rules right now.

But now I have created field (list integer) to Parent. Choosing from list (value from 1-9) example value 4. Then Rules should create 4 Child nodes.

This does not work. It creates Child nodes randomly. Example choosing 9 from list it creates just one Child. And sometimes when choosing 4 from list it creates 2 Child nodes.

Apparently there is something that I dont figure out. What would it be? Any help would be appreciated.

Here is what I have in Rules right now:

> **Rule to publish Child nodes when Parent is published**
>
> **Event:**
>
> * After saving new content
>
> **Conditions:**
>
> * Content is type of. Parameter: Content: \[node\], Content types: Parent
>
> **Actions:**
>
> * Fetch entity by property. Parameter: Entity type: Node, Property: Choose how many Childs, Value: \[node:field-number-of-childs\] Provides variables: Number of Childs (number\_of\_childs)
> * Loop. Parameter: List: \[number\_of\_childs\] List item: Current list item (list\_item)
>
> + Create a new entity. Parameter: Entity type: Node, Content type: Child, Title: \[node:nid\], Author: \[node:author\] Provides variables: Created entity (entity\_created)
>     + Save entity Parameter: Entity: \[entity-created\], Force saving immediately: true

Any help with this? Thanks!

# Answer
> 0 votes
Rules actually can loop based on array, and you have a integer only. Try Rules Array Create. Here is a issue about that.

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


title: how to use pdf reader module in drupal?

text:
# Question
Title: how to use pdf reader module in drupal?
im trying to make a simple pdf viewer or reader website running locally on my computer. Ive used the pdf reader, follow the instruction in README.TXT but still i can't use this. I can't seem to find the pdf reader. Any suggestion on how to achieve what i want?

# Answer
> 2 votes
You need to enable pdf module and create a file field in the content type where you want pdf to be visible and there are two option to display PDF file in the field display setting, select which ever you require. (You need to use the latest pdf.js to use first page display).

Note: you need to download pdf.js manually and add in project directory

Hope you are following this, http://drupalcode.org/project/pdf.git/blob\_plain/refs/heads/7.x-1.x:/README.txt

---
Tags: files
---


# Question
Title: When webform block submitted send email to node author and site admin -how?
This is scenario which I try to reach on my website for free blogging:

1. There is created universal webform **Contact author** with fields *name*, *email* and *text* which is as block *(display webform as block checked)* displayed under every blog node type.
2. When reader submit this block, submitted values are send as email to author of blog post *(node author)*, site admin *(me)* and possibly to submitter *(reader)* email.

Is there any possible solution involving webform? What's best combination of modules to do it so, if not webform *(I prefer some webform solution)*?

**Update:** For Webform 4.x I use token `[current-page:node:author:mail]` for "*E-mail to address*" in "*E-mails*" tab. You can find more details in this tutorial I wrote.

# Answer
> 2 votes
The best solution (IMHO) doesn't actually work: you should be able to use the Tokens module and use a proper token to fill a recipient field. For example: `[node:author:mail]`

However, Webforms only appears to support its own *%something* tokens, and those only relate to the current user and the webform id (not the id of the node being read).

So instead, write the site's inevitable custom module and use `hook_mail_alter()` to change the To address.

Another resource I read (and have now lost) suggested setting the Webforms recipient to something easily recognizable, like "replace-me@mysite.com".

Then in your `hook_mail_alter()` function,

1. confirm the form's identity,
2. get the current post's author,
3. get that user's email address, and
4. use it in the Recipients. (Along with the admin & the poster, as you like.)

---
Tags: webforms, emails, nodes, notifications
---


title: Inherit page id for drupal node

text:
# Question
Title: Inherit page id for drupal node
I am trying to make a node inherit the url of where it is clicked form.

eg : .com/blue-work/node-1

not .com/node-1

This is so when a link is clicked from a certain destination the node inherits its parents block settings. Is this possible with Drupal?

# Answer
> 0 votes
That sounds like fun.

First, a question: In your example, do you mean that the source page is `/blue-work`, and you're clicking a link on `/blue-work` to go to node-1? And you want the destination URL to become `/blue-work/node-1` ?

If so, that sounds difficult b/c you'd have an open-ended number of different paths and you'd be telling Drupal to behave differently, paying attention to the tail only (and how is Drupal to know what, exactly, is the tail?). I think it would still be possible, though.

Instead, you could go with what currently works: if you click a link on `/source-page` to go to `/destination-page`, then this URL works: `/source-page/destination-page`. However, I'd sooner use: `/source-page?context=destination-page`.

Regardless, you might start with `hook_page_alter` so you can edit all the links on the source page before it's rendered, adding the source page's url to (the end of) the links.

Then, of course, you're going to have to check the requested URL to get the 'source-page' context and apply it. Perhaps with `hook_page_alter` again.

---
Tags: views, uri
---


title: theme node add use custom theme

text:
# Question
Title: theme node add use custom theme
I followed this answer to try and theme node add

https://stackoverflow.com/questions/1538600/how-can-i-theme-the-template-for-edit-or-add-a-node-for-a-specific-content-type

the only problem is my theme is using Garland in node/add so I can not theme it with mythemename\_, how do I use my custom theme for this instead of garland

# Answer
It sounds like you have enabled your Administration Theme for content creation.

Check `www.yoursite.com/admin/settings/admin`:

and see if that check box is checked. If it is, uncheck it and then your custom theme should be used from then on, assuming, of course, it's enabled for the user.
> 0 votes

---
Tags: 6, theming
---


title: Modify a Module's output from a theme

text:
# Question
Title: Modify a Module's output from a theme
I'm really pulling my hair out about this one and wonder if someone can help?

Is it possible to override a module's output from the theme's template.php file? Basically, I wan't to modify the output of the Geolocation Module without updating the module output itself.

if so, how would I go about it?

thanks a lot

Dave

# Answer
> 0 votes
Your question is somewhat vague, what specifically is the "output" you want to override?! Is it drupal `Field` output, a theme variable such as `$vars['geolocation-something-foo']` ... or something else?

There is likely a preprocess or process Hook you can implement to slide in your changes. Or using Devel Themer you can probably override their template file with one of your own easily.

Something I did yesterday was override the implementing function of another module with a (local copy) of my own version of that function in a custom module -- tweaked to add HTML attributes and tags that I needed and were'nt provided by the raw HTML (non render array) output of the other module.

I followed the good example from this Snugug: Overriding Drupal Theme Functions from your Module and used HOOK\_theme\_registry\_alter() using the following logic:

```
/**
 * Implements hook_theme_registry_alter
 */
function mymodule__theme_registry_alter(&$theme_registry) {
  $theme_registry['ORIGINALMODULE_function_name']['function'] = 'MYMODULE_function_name';
}

```

I think took the body from the original function, copied, tweaked and pasted it into `mymodule_function_name`. I believe this hook is callable from a theme as well ...

---
Tags: theming
---


title: Filling fields with data on fly

text:
# Question
Title: Filling fields with data on fly
I have some records imported to my module tables. Some of this data is synchronized to drupal nodes by creating and updating existing nodes of specified type. This operation is made each time new import is done. The problem is, it produces around 60 000 nodes for every new import and it is quite a lot. Synchronization takes hours and operations through Views takes ages or crashes.

Is there any way to store my data only in my tables and serve them from this tables as nodes? Some way to only creates nodes with some properties set as language and title, and then provide data for fields directly from my tables?

# Answer
> 0 votes
If revisions aren't important you might want to fork your website codebase and try installing Field SQL NoRevisions module, by removing the "revisions" of Nodes node creation and fetching takes half the number of normal drupal queries.

Depending on you Read vs Write ratio you also might want to consider moving some of your Fields into a NoSQL database such as MongoDB.

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


# Question
Title: Has anybody figured out how to add videos to a node gallery?
I've just finished building a node gallery image gallery system in drupal that lets my users add lots of photos easily to the site, and create their own galleries. However, I'd like them also be able to add video files. Node gallery says this is not available "out of the box" but possible, but I cant find any instructions on how to do this. I'm hoping someone out there has figured this out.. thanks in advance.

# Answer
> 0 votes
http://drupal.org/project/video This maybe is the module you need to try?

or users add simple link to youtube http://www.youtube.com/watch?v=-LF30SUwr5Q

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


# Question
Title: How can I run Drush as user 1 in version 5?
Drush v3 had a --user flag (--user=1), however, this seems to be removed since v4, according to the website. How can I run Drush 5 as logged in as user 1?

# Answer
> 7 votes
See `drush topic core-global-options`; you will see that the --user flag is still supported.

Of course, you do not really 'log in' to your Drupal site with Drush. The usual convention is that Drush commands should call API-level functions, which are expected to operate independently of the current user. (Drupal does access checks before calling the API functions.) There are only a few instances, mostly in contrib, where setting the user is necessary.

---
Tags: drush
---


# Question
Title: Preventing FlexiSlider (Adaptive) to resize beyond a certain minimum height
I am using Flexi-Slider and AIS to create a responsive (full-width in this case) Images Slider for a front page on a Drupal 7 install.

I got it working perfectly but I would like to restrict the resizing function when the images reach a certain size. Meaning for example, if the height = 500px, even if the device screen size or resolution is smaller than that, or the user resizes the browser window, I don't want the image to get smaller than that.

Is that at all possible? Anyone has done it or could guide me into it? Thank you everyone for your time.

# Answer
I hope my auto-reponses to the last 3 or 4 questions I posted, serve to the rest :)

Just wrap the block where your flexislider slide views is contained in a div and give it a min-width with !important and set the height to "auto".

Have not tested this in IE yet tho. Let's see.
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: Content access based on on the field reference
I want to make a content access ( node ) based on it's user reference field .
ie: While i'm creating a node that have a user reference field, i want that it will be accessible just for the users that i mentionned before .
Is there any module or a way to do that ?
Thank you very much

# Answer
For Drupal 7 there's the Node Access User Reference module which does exactly what you are asking for.
> 1 votes

# Answer
There are plenty of node access modules available for Drupal but I honestly am not sure if there is one that would do exactly what you are looking for.

Either way, I would probably avoid a specific node access module for this and use Panels - read the Panels module - to do this since its makes this scenario easy to accomplish.

You can easily override Drupal's standard Node template and create an invariant that matches both the content/node type you want to apply this rule on and add a condition that the logged in user's ID matches the user id in the reference field defined by the node.
> 1 votes

---
Tags: entities, users
---


title: updating drupal core only without drush

text:
# Question
Title: updating drupal core only without drush
I'm trying to update drupal core on a large multisite version of drupal. He only wants core updating for a security update. However, I can't see any instructions out there on just updating core without updating all the modules, unless you have drush installed. (I tried updating all of them anyway on my dev box and the update failed because of duplicate entries in the nodewords table).

He doesn't have drush and I don't have the ability to add it. Is it possible without drush?

Thanks Alex

# Answer
This is in the docs with every download of Drupal...

http://api.drupal.org/api/drupal/UPGRADE.txt/7
> 2 votes

---
Tags: updating
---


title: How to remove required field from nodes

text:
# Question
Title: How to remove required field from nodes
I'm displaying jobs in my site but after expiry of last date of application of job, I want to archive it for a month or so and then delete it.

So after last date of application I don't want to be listed in me Menu block and Taxonomy blocks: http://bit.ly/WB59KX . As if the (optional/required) term reference field value has been removed.

In short if Accountant term has been selected in a field( named profession) then after last date of application, clicking Accountant term should not display this node.

I don't want to unpublish expired jobs though.

How can I achieve this?

# Answer
The way I'd do this would be to use Views to override the default taxonomy listing, then add a filter to the view so that the application date must not be in the past.

Life gets a little more complicated if you have multiple vocabularies and this rule won't work with all of them. Ctools page manager will let you load a different view per taxonomy.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How can I modify body class based on non-taxonomy node data?
I need to add a custom class to my html `<body>` tag when certain elements are present in content (namely, either a featured image or image gallery, both of which are added to content using Entity Reference fields in the site's main content types).

Currently I'm accomplishing this using the Context module and a taxonomy vocabulary. (Condition: Taxonomy; Reaction: Theme HTML). The workflow for content managers looks like this:

1. Add an image or gallery to a content item
2. Don't forget to attach the appropriate taxonomy term so the page lays out correctly.

Oddly enough, forgetting step 2 is a rampant problem.

Any suggestions on methods for eliminating step 2? It seems like it ought to be possible to just test for the presence of a value in the appropriate fields and either automatically attach the taxonomy term, or skip the taxonomy term and trigger the theme HTML based on the data values themselves.

I should mention that the taxonomy vocabulary in question has NO purpose in my application other than applying the appropriate body class.

I'm open to using some other module to accomplish this. (Rules? Couldn't figure out how to make this work either).

(Drupal 7).

# Answer
You could do this in your theme's template.php. Something like this:

```
function mytheme_preprocess_html(&$vars) {

  // Load node
  $node = menu_get_object();
  if ($node) {

    // Wrap to fetch field values easily
    $wrapper = entity_metadata_wrapper('node', $node);

    // Check image reference fields and add body class
    if (
      $wrapper->field_featured_image->raw() ||
      $wrapper->field_image_gallery->raw()
    ) {
      $vars['classes_array'][] = 'my-class';
    }
  }
}

```
> 2 votes

# Answer
You don't say whether you have any PHP coding ability or not. If you do, the simplest answer might be to add a hook\_preprocess\_html() implementation to your theme.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to override core taxonomy/term/% with a view?
I have enabled the taxonomy/term/% view provided by the Views module but taxonomy term views are still handled by the core. Modifications has no effects and hooks such as `hook_views_pre_render()` are not invoked.

However, views explicitly specifying a term such as taxonomy/term/5 work.

Do you have any idea on how I can override the core default taxonomy?

# Answer
> 0 votes
The problem was that I had the Taxonomy View Integrator (TVI) module enabled. By default, if no override is set it invokes the core term page, which makes sense.

# Answer
> 0 votes
The Taxonomy views integrator module can help you; it allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.

# Answer
> 0 votes
You have to change the default view before it will take over. Add your customizations (for example, a field) to the taxonomy display, and save.

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


title: Views Dropdown List of valid items

text:
# Question
Title: Views Dropdown List of valid items
I'm looking to add an exposed filter that only contains existing user inputed value.

For example. I've create a content type called 'Items'. Inside that content type there is a field called 'Team name'. The user can freely enter the Team name and add multiple items associated with that Team.

When the user is viewing items, I'd like for them to be able to filter based on that Team Name, but rather than force them to type in the name, I'd like for the exposed filter to contain a list of Team Names that have been added into the nodes.

How to make an exposed filter that only contains existing database values?

# Answer
It really sounds like the team name is a `tag` based on a Taxonomy Term. You could make a taxonomy called `Teams` and add a `term_reference` to your node type. Views can then make an exposed filter based on the term reference.

Using the autocomplete widget for the field will auto create non-existing team names. For more UI flexibility see Autocoplete Deluxe.
> 0 votes

# Answer
I think what you are looking for is the Views Selective Exposed Filters module, which limits the list of options to those returned as part of the data set.
> 0 votes

---
Tags: views
---


title: Serial number for each item

text:
# Question
Title: Serial number for each item
I am making a book rental cum selling site. I have planned to use Drupal Commerce for it. But tracking the item is simply not possible & so that I am trying to find the solution for assigning serial number for each number of items(attributes) for drupal commerce product.

Like I am having a BOOK & it has 10 copy, so I want to keep one unique serial number for each copy.

If somebody have any idea about this then please help.

# Answer
I would implement this by first creating a Book Product (Non-Fiction) and issuing a specific sku number for each separate Book Title that I would introduce as a specific product. Combining this with the http://drupal.org/project/commerce\_stock module might be useful in allowing unique skus per book but than also having quantity of books in stock for multiple copies.

1. Ender's Game (10 copies according to commerce\_stock) SKU #00000001
2. Dune(30 copies according to commerce\_stock) SKU #00000002
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I get views_save_view($view) to return TRUE when using Drush?
I have a script that calls various views API functions, namely views\_save\_view() or $view-\>save().

When using Drush 5 to run the script, these functions return false. However, when I run these with cron while logged into Drupal through the config, it works fine and everything executes as normal.

How can I get these to return true while using Drush?

I have feeling this is a permissions issue, but can't figure out how to get Drush to execute with the permissions it needs. This is a follow up question to here:

How can I run Drush as user 1 in version 5?

Also there is a somewhat related issue here:

http://drupal.org/node/1515616#comment-6312604

# Answer
> 0 votes
You can run a script as a user with the right command line option. Basically:

`drush php-script YOURSCRIPTNAME.php --user=1`

or `--user=UID` where UID is a valid drupal user ...

---
Tags: views, drush
---


# Question
Title: How to merge two different pages on one page
I am using profile 2 module to manage users profile related information. so far I am having two tabs

1. My Accounts
2. Customize the tabs takes me to two different URLs
i.e (mydomain.com/users/user-name/edit/Customize)
(mydomain.com/users/user-name/edit/MyAccounts)

My question is, can I make this into one tab and make these two different pages to display in one single page?

Thanks alot

# Answer
> 1 votes
Hide the tab on the user account page.

```
function MY_MODULE_menu_alter(&$items) {
  $items['user/%user_category/edit/profile']['access callback'] = FALSE;
}

```

Then, merge the profile2 form with the user account form itself :

```
/**
 * Implements hook_form_FORM_ID_alter() for the user edit form.
 */
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (($type = profile2_get_types('profile')) && $type->userCategory) {
    if (empty($form_state['profiles'])) {
      $profile = profile2_load_by_user($form['#user'], 'profile');
      if (empty($profile)) {
        $profile = profile_create(array('type' => 'profile', 'uid' => $form['#user']->uid));
      }
      $form_state['profiles'][$profile->type] = $profile;
    }
    profile2_attach_form($form, $form_state);
  }
}

```

From http://www.jide.fr/english/add-profile2-form-directly-on-the-user-edit-form

---
Tags: views, 7, users, routes
---


# Question
Title: Adding Values to Header Drupal 7 + .htaccess
Well, I'm new to Drupal, I was wondering if I can add values to header?

**Note: this is the code for my mysite.com**

I got this piece of code in mysite.com

```
<?php

    if (isset($_GET['code'])) {
    echo $_GET['code'];
    }

?>

```

So for example,

**Drupal URL:**

*mysite.com/U2pVnWK*

If I run that URL, it redirects me to **PAGE 404**

So I tried this, **URL:**

*mysite.com/?code=U2pVnWK*

Which it eventually works.

So I tried using RewriteRule thing in .htaccess and added this code

```
RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1

```

Even change it into

```
RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ ?code=$1

```

Also

```
RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ http://www.mysite.com/?code=$1

```

**None** of it works.

Plus **I don't know where to put that piece of code in existing .htaccess that Drupal made it.**

So to simplify, what I want is:

If I access ***mysite.com/U2pVnWK*** I would be able to **retrieve and echo** *U2pVnWK* instead of redirecting to PAGE 404 PAGE

Any help would be appreciated. :)

# Answer
There is something you can try with Drupal itself.

hook\_url\_inbound\_alter

> Alters inbound URL requests.

The idea is to drupal\_lookup\_path and if nothing found you can do whatever with `$path` variable in hook\_url\_inbound\_alter
> 1 votes

---
Tags: 7
---


# Question
Title: Image styles to make all user inserted images appear as circles
Users can insert images on my site...i want that all of them are displayed in a similar fashion. So i created a new style under Image Styles. However, how can i make sure that all images appear as circled. Even if a user inserts a square image, the final display should appear in a circle. I do not find any option to do so. Any help or advice.

Thanks

# Answer
To create the image style you want, you'll need to install the ImageCache Actions module to get the "Rounded Corners" effect. Note that when you install this module, you need to turn on several different modules in drupal (and I'm not sure which one provides "Rounded Corners"): image\_styles\_admin, imagecache\_canvasactions, image\_effects\_text, imagecache\_customactions, imagecache\_coloractions, imagecache\_autorotate, imagecache\_actions.

Once you have the Rounded Corners effect, you should be able to create the behavior you are looking for. Here's an example:

The only thing that you can't see on the screenshot is the "radius" setting for the rounded corners effect. To get a truly round image, it should be set to half of the height/width used in the scale & crop step. In the example, scale & crop is set to 100x100 and radius is set to 50. If you set scale & crop to 500x500, you'd set radius to 250.

Once you've got the image style you want, go to Administration \> Structure \> Content Types, and choose the content type that has the image field. Go to the "Manage Display" tab, and click on the settings icon for the image field. This will allow you to select the image style to be used for this image field.

You may need to do this for multiple display modes for your content type, for example "Default" and "Teaser."
> 5 votes

# Answer
You can create png masks for your user pictures above them and clip visually actual user pictures. Masks should be in the color of background and added with css above the bare image tag in some of existing field wrappers.

But, there may be different sizes showing up in your site. So you need a mask and css style for every appearance. User should be forced to enter x=y image, or their images should be cropped or they would not fit circle.

It needs more investigation, planning and some precise design photoshop effort, but on the bright side you won't use any extra module.

From the other side, if you can spend some more computing power/installing few modules, proposed way to do it drupal way is more "secure".
> 0 votes

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


# Question
Title: Creating a menu while categorizing my products
Hello I am developing an e-commerce website with drupal commerce(commerce kickstart) everything seems great.I have imported my products and I have tested it and I made my catalog like the video on vimeo that it is posted http://vimeo.com/22748684.

But I would like to make this catalog as a drop down menu.I mean I want to a menu with jquery that it will replace this catalog and the user for example can see a subcategory cars and can choose Toyota, BMW, some other with tyres like my products on the catalog.

How can I do this?

# Answer
> 1 votes
You can use Superfish to replace the default main menu that comes with commerce kickstart, however you use it at a cost since this jquery drop down menus are usually not optimized for mobile, although superfish provides some optimizations (most in a beta state right now).

Anyway if you need a *big* dropdown menu your alternatives are short, and Superfish provides minimal mobile browser support if used with a responsive theme (auto-resize and support for touch devices).

---
Tags: routes, commerce
---


# Question
Title: To add a value entered in a field to select list
I have a field and select list. When a value is entered in the field ,if that value is not present in the select list then i want to append that value in the select list. how can i acheive this?

# Answer
> 0 votes
Not exactly the workflow you're looking for but one of these two modules can help you:

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

> Rather than having a multi-select field, this modules allows you to have multiple select fields with the traditional FieldAPI 'Add another item' button.

---
Tags: 7
---


# Question
Title: Moving a Drupal website from one server to another, an error needs to be fixed
I set my test Drupal 7 website on my Macbook in a XAMPP environment, and I've now moved the site to another computer with Windows xp, using the following steps:

1. Export the database use the phpmyadmin to a .sql file.
2. Import the database in the XP computer using the sql file.
3. Copy all the website's files in the htdoc directory to the new server's same directory
4. Alter some parameters in settings.php associated with database.

OK, I did it. Everything goes well, except one thing. The Configuration Menu for the Administrator doesn't work. When I click the Configuration menu, nothing happens after waiting for a long time, only a blank page appears.

And I don't know what had happened, or how to solve it.

# Answer
> 0 votes
Try disabling the update module, the quickest/easiest way would be via Drush using drush dis update.

If you cannot use drush follow this: http://drupal.org/node/157632 "phpMyAdmin

To disable a module via phpMyAdmin you must login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save."

---
Tags: toolbar
---


# Question
Title: _preprocess_views_view not getting called
Drupal 7, Views, Bootstrap theme sub theme in use

I have a views-view-table.tpl.php file in my sub theme and I am trying to preprocess some of the variables sent to this tpl. I created a function bootstrap\_preprocess\_views\_view(&$vars) in my template.php and it is not getting called when I visit one of my views pages. Why would this be? Other preprocess functions are getting called from the same template file. I have tried flushing the cache.

```
function bootstrap_preprocess_views_view(&$vars) {
  dsm($vars);
  dsm("aaaa");
  die;
}

```

# Answer
Ok. Then, we have to consider the following possibilities:

* The name of the function is bad typed. The structure for this case should be `template_preprocess_HOOK(&$variables)`. The second part (**\_preprocces**) and third part (**\_views\_view**) is well typed, but are you sure the first part is well typed? I assume that "bootstrap" is the name of your theme.
* This template hasn't been called when you visit the page, for example, if the pages have been stored in cache\_page table for anonymous users. Another possibility could be that a different template has been called.
> 1 votes

---
Tags: views, theming
---


title: creating lists of nodes in a list

text:
# Question
Title: creating lists of nodes in a list
is there currently a module that allows a user to bookmark a bunch of nodes and name them? E.g. create a bookmark of each movie and name the list, "comedy".

I'm guessing using the flag module would be the best bet but i'm not sure how to store attributes to flags and how to create separate flags.

# Answer
> 3 votes
You might want to look at the Flag Page module which expands on the Flag API, or the Bookmark module.

For the Flag API, look at the Flag Lists module which will allow your user to create multiple private lists of nodes.

# Answer
> 1 votes
I think you can use or perhaps find inspiration in the Bookmark Organizer module. It has the functionality you are describing in your question.

# Answer
> 1 votes
Yes you can bookmark the nodes in Drupal 7 using the Flag module:

1. Download the flag module and enable it.
2. Create a new flag by visiting admin/structure/flags and then clicking on "Add a new flag" link.

You can create separate the flags by clicking "Add a new flag" link again and giving some other name to the flag.

---
Tags: 7, users
---


# Question
Title: Allows authenticated users to tag content
Administrator can add tags/Term reference to any content types. How can I give permission to authenticated users so that they can tag on any content type where they have access for editing/adding?

# Answer
> 1 votes
Check for field permission. If authenticated user has permission to add/edit the node then user should be able to tag it. You Just need to verify your permission settings.

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


# Question
Title: how to assign first img linked on a node to image field
What I have: a D7 site with around 2k nodes on it, many of these nodes have images `<img>` in the html of the body but those images are not assigned to the image field. (It is an old drupal site that was upgraded to D7).

I would like to parse all the nodes so that the first image in the body content is assigned programatically to the image field of the node. Manually editing is not an option, as there are over 2.000 nodes on that site.

Is there a way to do that programatically? I guess field api may help (and so my tag) but I dont really know.

Thanks.

# Answer
> 0 votes
I would write a module that read the field\_data\_body table in database. This table contains a field called body\_value where the values are stored. If the module find a mark, you can get the "src" attributte.

You don't forget to make a comparison in field\_revision\_body table to avoid problems.

Once you have the path of the file, you must save it as managed file in database. For this, take a look to "file.inc".

Here a little summary for last changes in D7.

I think it's important that you understand the difference between managed files and unmanaged files. Once you have saved the file, you could load the node, and assign to the field\_image field, then node\_save().

---
Tags: media, entities
---


# Question
Title: Problem using entity reference to show links to content types associated with a content type
I have a content type called module and a content type called lesson. Module can contain unlimited lessons.

* I installed entity and entity reference module.
* In module, I created a field type of entity reference and set target to node, entity selection to simple and lesson.
* I saved these settings and found I now have select box which allows me to add select lessons when I edit a module type.

However, when I go to the module page I don't see any lessons or even a label for lessons.

Does anyone have any idea how I can troubleshoot this, or what might be wrong? Also, would i be better trying to create a view rather than using entity selection simple mode?

Thanks in advance,

# Answer
> 0 votes
First thing I'd do would be to check the display settings for your module content type. The field may be hidden or otherwise not configured as you want.

---
Tags: nodes, entities
---


title: List all terms from a vocabulary

text:
# Question
Title: List all terms from a vocabulary
I have a taxonomy called services and want to list out all the terms. I can load the vocab with

```
 $vocabulary = taxonomy_vocabulary_machine_name_load('Services')

```

but cannot seen to get all the terms out.

# Answer
> 49 votes
There are a few ways but I prefer `entity_load()`:

```
$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

```

You could also use:

# Answer
> 21 votes
I would like to use this code.

```
$name = 'YOUR_VOCAB_NAME';
$myvoc = taxonomy_vocabulary_machine_name_load($name);
$tree = taxonomy_get_tree($myvoc->vid);
foreach ($tree as $term) {
 echo $term->tid;
}

```

taxonomy\_vocabulary\_machine\_name\_load

taxonomy\_get\_tree

---
Tags: 7, taxonomy-terms
---


title: Alter Reset Password Link

text:
# Question
Title: Alter Reset Password Link
When a user resets his password he/she gets an email with a link which adds a message to the website and a hyperlink which it redirects him to the /user/\[uid\]/edit?token=... page.

How can i alter this link ?

# Answer
I would prefer mail a new link to user rather than altering the current link.

Use Tokens API to create user wise links.

```
function MYMODULE_token_info() {
  $info['tokens']['user']['passresetlink'] = array(
    'name' => t('Password Reset link 2'),
    'description' => t("Password Reset link 2"),
  );
  return $info;
}

```

and

```
function services_chat_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'user' && !empty($data['user'])) {
    $user = $data['user'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'passresetlink':
          //$user = user_load($node->uid);
          //$newlink = make your link here.
          $replacements[$original] = $newlink;
        break;
      }
    }
  }

  return $replacements;
}

```
> 1 votes

---
Tags: 7, users
---


title: Restrict permission to custom modules

text:
# Question
Title: Restrict permission to custom modules
I am using drupal 7, and I have created a custom module. This module consists of a form that can be used for adding records to the database. But I saw that the link to accessible to all the users, even anonymous users.

I want to restrict the access to this module and form from all the normal users; only the administrator users should access it.

I have created a role called Administrator and permitted my module only for the administrator. It still doesn't work.

How can I restrict the access to my custom module?

# Answer
> 0 votes
When you define the page the form is on via hook\_menu(), you need to set the access rights via the "access callback" and "access arguments" settings.

The simplest way to do this is to provide an array containing a single permission value as the "access arguments" setting.

---
Tags: theming
---


title: Features to import content types

text:
# Question
Title: Features to import content types
Features seem to be the right way to import custom centent type in a fresh D7 install from a D6. But when I create my feature on the D6 one, it added dependencies like modules,and once I import the module on D7, these aren't satisfied because D7 module version doesn't yet exist or it's not recognized..

How can I figure out this ? it's about CCK submodules (filefield,imagefield..)

thanks

# Answer
If you are simply trying to migrate the content type (not the content) then it'll probably be easier to recreate it from scratch than trying to use Features as a migration tool, which is not what it's meant for.

If you want to go down the migration route the natural approach would be to upgrade a copy of your D6 site to D7, but in my experience that'll take longer and be more problematic.
> 1 votes

# Answer
These modules are now in core in D7.

EDIT:

I think I now understand what you are trying to do, and it is going to be a little more difficult than simply upgrading your site to D7. If I understand correctly, you are taking a D6 module generated by Features, and trying to plug it into a D7 site. Before you can do that you MUST first upgrade the D6 module to a D7 module. You will find more information here. The Drupal API has changed for D7.

If this is only a small site, do a clean install in D7, create your content types manually, and use cut and paste to migrate your content. For larger sites, create a complete working copy on a test bed and do a site upgrade following the instructions found here.

I have done several d6 -\> d7 upgrades, and it usually takes two or three tries to get it right. If you do multiple backups during the process, you can restore to a working stage and continue without having to start from scratch if the upgrade fails for whatever reason.

Good luck.
> 0 votes

---
Tags: migrations, features
---


# Question
Title: How do I get fields attached to a user to display to anonymous viewers?
*I've searched around and either I don't find any questions that address my issue per se, or the solutions offered don't pertain/affect my problem. So here goes:*

A D7 site, current core, etc.

I have fields attached to user entities. I don't have any permissions applied to limit access to the fields. All users (including anon) have access to user pages (user/username).

However, attached fields do not appear through views for anonymous users. They do appear for logged in users, and anonymous users **can** see the Groups Audience (I use organic groups on the site), but no other affiliated data shows (full name, website, twitter, etc).

If my view is a list of fields, the fields **do** appear, but without content (the labels print if I turn them on, text I have set to display as no results behavior shows, etc). If my view returns a rendered entity all that prints for anonymous users is the user picture and Groups Audience.

I'm at a loss here. Initially I thought it was a views issues; now I'm not so sure. I've checked my permissions multiple times and I can't see what's blocking it. Anonymous users can access user pages. I don't have any field-level restrictions (and enabled the Field Permissions module just to make sure). I don't know what else it could be.

Any help is super appreciated.

# Answer
> 1 votes
After poking around on this for a while I discovered that it is definitely an organic groups permission issue. For the record, I have the 7.x-1.5 version of OG installed.

In OG global permissions (admin/config/group/permissions) the fields attached to the user (and nothing else) are all listed under Organic Groups Field Access along with fields attached to groups and fields attached to group content types. When I give access to non-members the fields appear for anonymous.

I suppose this functionality is designed so you can limit user access to people who are connected through a group. This isn't entirely senseless, but can be frustrating if you don't anticipate that control over some objects will be trumped by OG permissions.

---
Tags: entities, users
---


# Question
Title: Drupal form won't save with TinyMCE (Firefox only)
I have a Drupal form with a TinyMCE (3.5.6) instance on it, this is instantiated via the Wysiwyg module. If I save the form in Firefox, it visually displays an AJAX spinner but nothing happens, the form does not save and leaves me on the form. All other browsers work. I can get it to work 2 different ways but not sure why it works and how to translate that to a permanent fix. I have been going through all the suggestions in http://www.tinymce.com/forum/viewtopic.php?id=18821 but have not been successful yet.

1.) If I unminify the code with http://jsbeautifier.org it works without throwing console errors but JSLint throws tons of lint errors in the code.

2.) If I delete the code below it works,

```
<textarea rows="3" cols="60" name="field_caption[und][0][value]" id="edit-field-caption-und-0-value" class="text-full form-textarea" style="display: none;" aria-hidden="true"></textarea>it works but with the below error:

```

but throws this error.

```
NS_ERROR_UNEXPECTED: Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMHTMLDocument.implementation]
http://loc.dbtv.nbcuni.com/sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js?mhcuev
Line 1

```

Here is a video of the issue at hand =\> https://docs.google.com/file/d/0B47tip0c\_KEtY2w1akUtcFZHYUU/edit

# Answer
> 0 votes
The main fix is linked to in comment #6 of the TinyMCE bugtracker here =\> http://www.tinymce.com/develop/bugtracker\_view.php?id=3152

The source fix is in comment #4 but that won't help many since you need to have an environment to actually compile TinyMCE.

---
Tags: wysiwyg
---


title: Code showing on every content page

text:
# Question
Title: Code showing on every content page
I'm pretty new to Drupal but have take my company's half-baked site from the server and gotten a working instance of it in my local wamp stack working. The only problem is that it seems on every page there is a section of code being inserted:

```
<?php
if ( isset($entity->field_job_id['und'][0]['safe_value'] )) {
   $job_id = $entity->field_job_id['und'][0]['safe_value'] ;
   $application_link_form = '
<form action="/careers/application" method="POST">
    <input type="hidden" name="job_id" value="' . $job_id . '" />
    <input type="submit" value="Apply online" class="job-application-link" />
</form>';
   print $application_link_form;
}
 ?>

```

This is showing a section of this code plus an "Apply Online" button at the top of each section of content. It doesn't seem to matter what the content type of the content and the site which I imported all the files and db from has no such code - not even when I view source is there anything even commented out. Hopefully this code gives you some context as to where this is ocurring - it comes immediately following this series of divs:

```
<div class="region region-content">
  <div id="block-system-main" class="block block-system">
    <div class="content">
      <div class="contextual-links-region"><div class="panel-display panel-1col clearfix" id="job">
        <div class="panel-panel panel-col">
           <div>
              <div class="panel-pane pane-dsc" >
                 <div class="pane-content">

```

In any case, I cannot figure out where to find this code in order to get rid of it. I'm not seeing any modules relating to this, etc. And I just am baffled as to why it would start showing up after importing from a site that doesn't display this. If anyone can think of any possibilities, please let me know!

# Answer
> 1 votes
If it's not in the source, it's in the DB. At a guess, this is code that someone entered using the PHP filter, but the PHP filter is not active so it's showing up as text.

As to where it is in the DB, there's many possibilities. I'd use brute force to search the DB in its entirety. (That's easy for me to say as I have a copy of SQLyog to hand. I'm sure there are other tools that provide this functionality, though: I think PhpMyAdmin has it.)

Addendum: looks like it's in a custom pane, so the table panels\_pane is the most likely culprit. Ideally you want to find how it's getting inserted onto the page. Do you have the module Panels Everywhere enabled?

# Answer
> 0 votes
I consulted a Drupal expert in our company who looked through the instance. He diagnosed a couple of causes. For one, the PHP Filters module was not enabled. Additionally, I needed to set the PHP Evaluator option for "Display Suite Code" (in Configuration \> Content Authoring \> Text Formats \> Display Suite Code). These two items fixed the issue.

According to him, the code was in the panels in order to display an Apply Online button conditionally above some content. He thought it was unnecessarily complex to do it in the way the previous Drupal Dev did it. Being a newb, I wouldn't presume to offer my own opinion. ;-)

# Answer
> -1 votes
As Alfred says, it's going to either be in the code or the database.

If you have the sql data dump, you can open that in a text editor and search for the code.

The fact that it's found here in your html

```
<div id="block-system-main" class="block block-system">
  <div class="content">

```

... leads me to think that it's a block within your content region that's injecting this code.

Go to Admin \> Structure \> Blocks and see what blocks are enabled in the content region, try disabling them.

---
Tags: forms
---


# Question
Title: Insert value to field programmatically and remove cache from field
I have content type `feature` and i have field `hit_count` in this c.type, also i have `db table - hit_count` \- example:

```
nid   hit_count

1     434
2     233
3     512

```

I want to output `hit_count` inside my field - `hit_count` on current node(also should appear on node edit). So for example if node id is `1`, field `hit_count = 434`, and if admin want to edit this field i want to update field value to my table `hit_count` with current `nid` and field value `hit_count`.

To save value into my database table i will use `hook_node_update` and just get fields `nid` and `hit_count` values and update my table.

But i don't know what `hook` should i use or how to insert this value from database to my field. There are lots of nodes with content type `feature`.

**UPDATE**

> **My first thought is - why do you use a separate db table for this rather than simply using an integer field in the content type?**

`Hit count` module was created long time ago, client wanted to disable/enable statistics for every content type, so default `statistics` module does not fit our needs. And now client want to manage this `hit counts` for certain nodes etc...

Also i managed to insert value to edit form on `hook_exit` updated custom hit count module.

```
function hit_count_exit($destination = NULL) {
    if ($node = menu_get_object()) {
        $selected_types = array_filter(variable_get('hit_count_content_types', array()));
        if (!empty($selected_types)) {
            if (in_array($node->type, $selected_types)) {
                db_update('node_hit_counter')
                        ->expression('totalcount', 'totalcount + 1')
                        ->condition('nid', $node->nid)
                        ->execute();
                if($node->type == 'feature') {
                    $val = db_query("SELECT * FROM {node_hit_counter} WHERE nid='$node->nid'")->fetchAll();
                      db_merge('field_data_field_hit_count_node')
                        ->key(array('entity_id' => $node->nid))
                        ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'feature',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->nid,
                                'language' => 'und',
                                'delta' => 0,
                                'field_hit_count_node_value' => $val[0]->totalcount,
                        ))
                        ->execute();
                }

            }
        }
    }
}

```

But right now i see next problem. I need to get rid of Drupal field cache, cuz i see cached value every time i reload page, and if i clear all caches i get current value of `hit_count`.

# Answer
I also think you could use an integer field on the node for this - but keeping that aside, the problem you are facing (the inserted value not being refreshed by the cache) is caused by the fact that you are trying to write in the database table `field_data_field_hit_count_node` directly. This is definitely discouraged, and you should be using the proper API instead.

Instead of `db_merge('field_data_field_hit_count_node')->...->execute()` you would want to do something like:

```
$node->field_hit_count_node[LANGUAGE_NONE][0]['value'] = $val[0]->totalcount;
$node->save();

```

Doing it this way ensures that the saving is done by Drupal, the caches are cleared as required, hooks as called as necessary, etc.

In addition if you don't mind using the entity module, then you can do this with Entity Metadata Wrappers in a simpler way:

```
$nw = entity_metadata_wrapper('node', $node);
$nw->field_hit_count_node = $val[0]->totalcount;
$nw->save();

```
> 2 votes

---
Tags: 7, entities
---


title: CSS, adaptive theme

text:
# Question
Title: CSS, adaptive theme
In migrating a site from a in-house CMS to Drupal 7, I'm trying to match font sizes between the older site and the newer one. In D7 we're using a Adaptive theme.

Using Firefox's inspector, the font size has a computed size of 10.88.

My question: in using only `font-size: x em` specifications, how should I most properly match that? Do increase / decrease the initial em size setting in the Adaptive style sheets?

# Answer
> 2 votes
It depends on the base size of the font, as em is effectively a ratio. If in the CSS for the body of your webpage is

```
font-size:16px;

```

Then

```
font-size:1em;

```

is equavelent to 16px (100%).

To get from base size (B) to desired size (D) use formula:

> D/B

So if your base size was 10px, to get a desired size of 10.8833px:

> 10.8833/10 = 1.08833

so

```
font-size:1.08833em;

```

If the base size was 16px

> 10.8833/16 = 0.68

```
font-size:0.68em;

```

So you need to know the base font size, and then work at an em value based on this. The default size for medium text in a browser is 16px, so if body font-size is set to 100%, then the base size is 16px.

---
Tags: theming
---


# Question
Title: Quicktabs and views to create tabbed views
I see that quicktabs uses blocks as tabs. This is fine if i create 4 views blocks for 4 single items of a content type and then add them to quick tabs manually.

Is there a workaround to show the latest 4 items of a certain content type using quick tabs and views?

Thanks,

# Answer
> 3 votes
Is this not just a matter of editing the view block to show four items rather than one? Under "Pager" in the view, select "Display a specified number of items" and then the quantity you prefer.

# Answer
> 0 votes
for the specific content type, add a filter : specific content type nd sort by date decreased nd limite the number of resulets by pager, nd use offser if you want too.

---
Tags: views, blocks
---


# Question
Title: Content Template admin interface for custom content type not displaying
I'm trying to work with a content template for a custom content type. The admin interface isn't loading... well, it's not fully loading. Here's what I get:

It should, of course, look something like this... which is another custom content type that I created whose content template loads just fine:

This content type is fairly straightforward. I don't think I've done anything unusual with it... so I'm stumped. Any ideas?

# Answer
> 0 votes
It was PHP file size limit. Weird. It was increased and everything went back to normal.

---
Tags: nodes
---


title: Hook active trail path

text:
# Question
Title: Hook active trail path
I' am trying to make a custom module to set an active trail path to a menu. I created a views page. The active trail must be to a node or taxonmy term. When I open the pages created by the view the active trail is not active.

I wrote the script here below but it doesn't work, can somebody please help???

```
function mymodule_views_default_views(&$view, &$display_id, &$args){
  if( $view->name = 'productdetail';)
    {menu_tree_set_path('menu-categorie', 'node/39');
 }
}

```

# Answer
I found the answer to my own question.

In the view I added a field with the taxonomy term ID / node ID which is although used for my menu and hide the output and do a rewrite of the output. I pasted the following code in the text field for rewrite; field\_categorie-tid is my reference term from the menu.

```
menu_tree_set_path('menu-categorie', 'taxonomy/term/[field_categorie-tid]');

```

Instead of taxonomy/term/\[field\_categorie-tid\] you can also use node/\[nid\].

I added in the head section a global field with PHP and token, and put `<?php [field_categorie]?>`.

That's all; no hooks nor custom scripting in the template.
> 0 votes

---
Tags: 7, views, hooks
---


# Question
Title: How do you modify the form after it validates and show's errors
I have built a form using CCK in Drupal 6. I have two fields, one which is called health plans and the other is called terms. If I select a health plan I update the terms via AJAX (both are select lists).

So for example: (health\_plan\_field)Plan A -\> (terms\_field)(1, 3, 6, 12)

I submit the form and serialize the terms inside a session so that I can keep them.

My problem is that if the form has errors, the terms field is blank because it starts empty until a health plan is selected. So if I have already selected a plan and terms, when the form returns after errors I have nothing.

I have tried to use form\_alter (have used this before) by recursively walking down the cck fields on $form to modify the term\_field options based on what I have in the session. This does nothing on return.

My code is as follows (called from hook form alter):

```
function acg_pportal_new_service_order_form_cck_walkerTerms(&$array, &$cck_fields) {

$terms = unserialize($_SESSION['termDataFromForm']);
if (!empty($terms)){
    foreach($array as $key => &$value) {
        if (in_array($key, $cck_fields)) {
        unset($value['value']['#options']);
        $first = "";
        foreach($terms as $key2 => $value2){
            if (empty($first)){
                $first = $key2;
            }
            $value['value']['#options'][$key2] = $value2;
        }
            $value['value']['#default_value'] = $first;
            $value['value']['#value'] = $first;
        }

    }
    }
}

```

Is there anything that you know that will help me in this case.

# Answer
> 2 votes
You need to set the form to rebuild on validation fail.

```
$form['#rebuild'] = TRUE;   // cause form rebuild after validation failed

```

Then you can use your `$form_state['values']` inside your `hook_form_alter()`.

OR

You can create a custom function and use the #after\_build property.

# Answer
> -1 votes
`hook_form_alter()` gets called whenever a form is build or *rebuilt*, meaning it'll get called again when the form fails validation. At this point you can look at the `$form_state` variable to see the current state of the form and do whatever you need to do.

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


title: problem when adding jquery.js file

text:
# Question
Title: problem when adding jquery.js file
I need to run jquery code in my content type form so i added jquery-1.8.0.min.js file in info file of my theme.

after clear all caches something wrong happened, the "add more" button on date field stop working, i'm sure it's from adding the js file.

Any suggestion?

# Answer
Drupal already includes jQuery. You should not add another jQuery library because this can cause conflicts with the existing one.

I suggest you to use jQuery Update if you want to use another version of jQuery.

If what you want is to run your own javascript code, you could add it using drupal\_add\_js().

Hint: Try first with `alert('hello world')`. See Working with JavaScript and jQuery.
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: Drupal form creating method without using a module
I am working on a Drupal site and it has a custom form in the frontend. I want to remove that form, but the problem is it is not generated by a custom module.

There is only one custom module. so I disabled it to check if that's the module generating the form. I cleared the cache also.

But the form is still there. So is there any other method of adding a form to a Drupal site without using a custom module?

# Answer
As the comments and the other answer says, there are several possibilities:

* A contributed module such as Webform.
* Someone with very bad habits hard-coded that form inside templates, other modules or even Drupal core.
* A block/node could contain that form, specially if the PHP-filter is enabled. Even with the HTML filter enabled (and submitting the form to another page).

If you see some custom text, or the name of the fields are unique or rare, you could try to search inside Drupal root directory for them:

```
grep -r 'Custom text' /var/www/drupal

```

phpMyAdmin includes a functionality to search across an entire database. If you feel desperate, try to search inside the Drupal database for the text you see in the form.

Examining the outputted HTML code could help. You will see if the form has an ID, for example.
> 2 votes

# Answer
Check if the webform module is installed.

Chances are that the form is in a block. You might want to check your block list if it is there.
> 1 votes

---
Tags: forms
---


# Question
Title: Entity Reference: User field not displaying unless user is referenced
I have a field that references users: field\_cc. When userA creates a node with this field populated with userB, userA cannot see the field when the node is displayed. If userA references himself, then userA will be able to see the field when the node is displayed.

This was on a clean install, no other permission-type module installed. Also tried fixing this with the Field Permissions module but this is did not help. I went through all possible permissions and settings but nothing seemed to work.

Am I misunderstanding how this module works out of the box?

Thanks in advance!

# Answer
Does that field display a link to the user profile? I think it does, and your users do not have the 'View user profiles' permission, so they cannot see the link to a page they don't have access to.
> 0 votes

---
Tags: entities
---


# Question
Title: Using Entity API, if given an entity in a function scope, how do you get the entity type?
This is very similar to this question: How do I get entity\_type and entity\_id from any entity page?
But I don't know what that asker means by "Entity Page," and in my case, using `debug_backtrace` (seriously?) doesn't cut it as I'd like this function to actually work from more than 1 scope.

Anyway... I am writing a module that uses numerous Entity Reference fields, and works the same code over several types of entities. The trouble is that in my function scope I don't know the type of entity.

If I pass an Entity object into a function, I can access its type parameter:

```
function foo ($entity) {
  // bundle is:
  $entity->type;
}

```

But how do I get the "Entity Type" from this object?

For example, I have a `dateset` entity type with several bundles: `class` and `retreat`. When I pass an instance of the `class` bundle into my function, I can identify that it's a `class`, and use `identifier()` to get its ID. But I want my function `foo()` to also handle `node` entity types with bundles `content_type_a` and `content_type_b`

Given any instance of one of those bundles, `foo()` can identify the bundle:

```
function foo ($entity) {
  $entity->type; // class, retreat, content_type_a or content_type_b
  $entity->indentifier(); // numeric ID
}

```

But what about getting `node` vs. `dateset`? Doesn't `$entity` know what type of entity it is?

**UPDATE:** Even though I accepted Yury's answer because it provided a realistic workaround, I think the true answer is that you cannot do this in Drupal. You have to pass around $entity\_type anywhere you pass $entity (which really kind of makes the idea of having Entities as objects pretty much worthless... but I think any Drupal developer knows that object oriented concepts in Drupal are just hacked in and not ever truly related to real world object oriented design). See this Drupal issue: http://drupal.org/node/1042822

# Answer
There are various (convoluted) methods for getting the entity type and bundle, but none that I'd consider "acceptable" on a large-scale. What I've done is implemented `hook_entity_load()` and added the `entity_id` and `entity_type` properties on all entities at load-time.

The following code does this, and is part of the Devtools module I maintain:

```
function hook_entity_load($entities, $type) {
  // add the entity type & id to all entity objects for easy data access
  // from other hooks & modules
  foreach ($entities as $entity) {
    // we don't want to add these entity fields when the entity is being exported into
    // a feature, otherwise the feature will always show as overridden and will not
    // revert
    if (  preg_match('#admin/structure/features#', $_GET['q'])  // features page
            ||
          (                                                     // drush fu command
            isset($_SERVER['SCRIPT_FILENAME']) &&
            preg_match('/drush\.php$/', $_SERVER['SCRIPT_FILENAME']) &&
            isset($_SERVER['argv'][2]) &&
            $_SERVER['argv'][2] == 'fu'
          )
       ) {
      continue;
    }

    // set entity_type
      $entity_type_field = (!isset($entity->entity_type)) ? 'entity_type' : 'devtools_entity_type';
      $entity->{$entity_type_field} = $type;

    // set entity_id
      $entity_id_field = (!isset($entity->entity_id)) ? 'entity_id' : 'devtools_entity_id';
      list($entity->{$entity_id_field}, $vid, $bundle) = entity_extract_ids($type, $entity);
  }
}

```
> 3 votes

---
Tags: 7, entities
---


# Question
Title: drush core-config causes 'Permission denied'
When I use command as follow:

```
drush core-config

```

and then enter

```
1

```

a error displayed:

```
sh:/etc/php.ini: Permission denied

```

how to solve this problem?

# Answer
You are trying to edit a system level file (ex. /etc/php5/cli/php.ini) using Drush and you don't have access to it at your current permission level. You need to login using an account with higher permissions or use sudo.
> 0 votes

---
Tags: drush
---


# Question
Title: What module lets you delete a node after a specific time if its unpublished?
is there a module that can delete or prune nodes that does not get published after a certain amount of time has passed? Currently the node prune module doesnt work with the latest core release. Looking for alternatives if possible.

thanks

# Answer
> 3 votes
You could do this using the Rules module. If you enable the built-in scheduler submodule, you could create a set of rules/components like this (rough code to give you an idea, not a step-by-step walkthrough):

Component to delete content (Action set)

* Action: Delete content

Rule to schedule content deletion (Rule)

* Event: Content is created
* Action: Schedule the "Component to delete content" after the specified amount of time

Rule to clear deletion on publishing (Rule)

* Event: Content is published
* Action: Delete the scheduled event for that piece of content ("Component to delete content")

---
Tags: nodes
---


title: Drupal behaviors attach to form load

text:
# Question
Title: Drupal behaviors attach to form load
I am using the simpledialog module with the 'edit' tab still in it. The edit overlay for the node is displayed in the background with the simpledialog still in the way.

I have tried a bunch of ways of attaching the close call to the edit button and triggering a click on the dialog close button. None of it very successfully - all iframes. e.g.

```
$htj2('.tabs.primary').delegate('click', 'a', function() {
    $hjt2('#simple-dialog-container').dialog("close");

```

I think the 'correct drupal pattern' is to attach a behavior to the form load using drupal behaviors.

```
(function ($) {
    Drupal.bahaviors.hotTopicsResearch = {
        attach: function(context, settings) {
            // ?? What next?
            $('#hot-topic-research-node-form',context).once('load', function() {

            });
        }
    }
})(jQuery);

```

How do I find out what the behaviours are? How do I attach to the load event or is there an event related to clicking on the 'edit' tab? How do I get close the simpledialog?

# Answer
> 1 votes
Got it after a number of days searching:

```
(function ($) {
    Drupal.behaviors.hotTopicsResearch = {
        attach: function(context, settings) {

            $(document).bind('drupalOverlayBeforeLoad', function(event) {
                $('#simple-dialog-container', context).dialog('close');
            });
        },
        weight: 11
    }

})(jQuery);

```

The other events seem to have the wrong order. 'drupalOverlayOpen' almost works except that the editing overlay never 'becomes active'. This is why I was trying to work on the target editing screen events rather than the open dialog.

overlay\_paths without there being'use case documentation' it looks like it only applies to menu items. How to manually use Drupal 7's admin Overlay? shows you how to add content nodes to the admin paths. This displayed my node in the admin overlay, but without the background context being visible - defeating the point - and with some further quirks.

---
Tags: javascript, modal-dialogs
---


title: drupal 7 entity and simple test

text:
# Question
Title: drupal 7 entity and simple test
What I can't workout is what steps I need to see if the entity is loaded using simple test. Any direction will be greatly appreciated thanks.

```
/**
 * @file
 * Definition of creation of a entity.
 */

/**
 * Coded entity display test.
 */
class CreateCoded extends DrupalWebTestCase {

  /**
   * Implements getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Coded',
      'description' => 'Adding table to entities to create entity',
      'group' => 'Coded',
    );
  }

  /**
   * Enables modules that are need for test.
   */
  public function setUp() {
    // Enable any module that you will need in your tests.
    parent::setUp('coded');
  }

  /**
   * Tests for table coded.
   *
   * @Description
   *   Method needs to start with test if you wnat to test.
   */
  public function testCreateCodedEntity() {
    // how to I test the entity

  }
}

```

# Answer
Try the examples module:

> This project aims to provide high-quality, well-documented API examples for a broad range of Drupal core functionality.
>
> The Examples project contains many modules which hopefully illustrate best practices for implementing various Drupal APIs. These modules can be enabled individually, and will typically add menu items to your site, which should guide you through their features. You can then look through the code to see what they are doing.

It has a drupal 7 & 8 entity example in which has a test as well.
> 2 votes

---
Tags: entities, testing
---


title: Unable to create content

text:
# Question
Title: Unable to create content
I created a test account and added it to a numer of roles. Some of those roles (not all) have permissions to create content. I am unable to create or edit any content, but am able to view all published content.

When I log in as user/1 I am able to create new content.

What permissions am I missing in order to be able to create new content when logged in as a newly created user?

# Answer
> 0 votes
In some scenarios, re-ordering the roles on the Roles page might help solve access issues.

To reorder the roles, go to `Administration > People > Permissions > Roles` (`/admin/people/permissions/roles`).

Click and drag the far left handle for each role to re-order the roles by least permissive to most permissive, i.e. your admin role at the bottom.

Example:

* anonymous user (locked)
* authenticated user (locked)
* moderator
* administrator

For reference, here is the help text for the Roles page:

> Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined on the permissions page. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the names and order of the roles on your site. It is recommended to order your roles from least permissive (anonymous user) to most permissive (administrator). To delete a role choose "edit role".
>
> By default, Drupal comes with two user roles:
>
> Anonymous user: this role is used for users that don't have a user account or that are not authenticated. Authenticated user: this role is automatically granted to all logged in users.

Drupal handbook on Managing access control with permissions and user roles.

# Answer
> 0 votes
The only permission a role needs in order to create new content for a content type is *Create new content*. This permission must be set for each content type you want the role to be able to create content for.

If your user belongs to a number of roles, then it is - in a default Drupal 7 configuration - neccessary that at least one of the roles have this permission granted. Unless you have some node access module installed that breaks with the Drupal paradigm of grants being accumulative (e.g. **Deny Access**), then it should not matter if some of the roles the user belong does not have this granted.

---
Tags: users
---


# Question
Title: how to delete the files uploaded in the file field?
if i remove the files that were uploaded in a File field,and then upload a same name file, the file removed just now is still present in the server and the new uploaded file gets renamed to a name with index ,say, xxx\_0 ,xxx\_1.

What I want to do is when I remove a file, it should be deleted from the server, to save space in the server, How can I do this?

# Answer
> 2 votes
I also crossed this issue. I just did these following steps.

1. edit the node, and delete the file from the field (dont upload now) and save it.
2. then edit the node, now upload the file (with same name) and save it.

Its worked for me. without xxx\_0 like that.

Thanks

---
Tags: files
---


# Question
Title: Show WebForm Block through a link on a Page
I have a WebForm Survey which I want to show in a page through LightBox.

The LighBox part is all sorted but I am stuck in getting a link to the WebForm Survey.

Here is what I did:-

* Created a WebForm Survey
* Made it available as block (It can be seen in Structure\>Block as Webform: Self - Assessment Survey)

Now on a Page (About Us), I have a link "Open Survey". What I want to do is, that when this link is clicked, my Survey should open in a LightBox.

I tried doing this Open Survey, but this never opens my WebForm, and instead shows a 404.

What should I Do?

Many Thanks.

# Answer
This isn't possible at present, not automatically any way.

You could write some javascript to find all "/contact" links and append "/lightbox2" to it so it's "/contact/lightbox2". You would also need to add a rel="lightframe" to the anchor link. This would open the contact form in a lightbox when the contact link is clicked, and you could style the form with a page-contact-lightbox2.tpl.php template file in your theme's directory.

However, this will open the form in a iframe, rather than treating it like modal content which is what is done to the login form. The disadvantage to using an iframe is that the form isn't closed upon form submission, like with the login form. The advantage is that the iframe will add a scrollbar to accommodate the size of the content. If you want, you can treat it as modal content (just use rel="lightmodal"), but you'll need to specify the height and width of the lightbox container (see lightbox2 docs).

I'm not adding it to lightbox2 module at this time because there are too many modules that modify the contact form content, e.g. advcontact, contact\_forms, content\_attach, captcha, mollom, etc. These potentially could modify the size of the content, making it difficult for lightbox2 to estimate the outputted form size.

If enough other people request it, then I'll add the ability for lightbox2 to open the default contact form in a lightbox, but for now, this feature won't be implemented for the reasons outlined above.
> 0 votes

---
Tags: blocks, webforms
---


# Question
Title: How do I download/open a pdf file directly by clicking on lable/link
I have created a view that displays in a bulletin format, which works fine. My challenge is when I click on the bulletin which has a pdf attachment, I want it to immediately download/open the attached pdf file. Currently it takes me to second screen(see attached) which has a pdf attachment. I would like to get pdf attachment downloaded immediately when I click on the bulletin, **National Arts Festival Grahamstown 27 June to 7 July 2013** from the first screen(see attached).

I have tried to use file force drupal module but seems not to be doing the trick.

Herewith an attachments.

# Answer
> 6 votes
If want to Download File, then use DownloadFile module.

> a module to direct download files or images.

If want to open PDF, then use PDF Reader module

> will render your entity file fields with the selected PDF renderer.

and PDF module.

> Use HTML5 to display PDF files if users don't have pdf plugin for their browsers.

---
Tags: 7, views, files
---


# Question
Title: How can I install CKEditor on a server without downloading the files locally?
A bit of background info before I get down to my question - I'm using the URL method of loading modules to Drupal as I do not wish to save them to my dinosaur age PC. I have also not uploaded Drupal to my PC, but am operating it via Pantheon. This is not only because of my old PC, but as I am only in the very early stages of developing my website, one advisor has said I don't need to worry about that and other programs such as MySQL.

I'm keen to get CKEditor onto my Drupal platform, so have added the CKEditor - WYSIWYG HTML editor module and this appears so far to be successful.

The tutorial I am following assumes that I am able to save the CKEditor program to my PC... which I guess in essence I can, but I am hoping there is a way to avoid doing this and load it the same way I do a module via URL perhaps?

# Answer
> 0 votes
Pantheon assumes that you are using git; although there is an on-server development feature, the primary workflow is designed to use git as a conduit between your local machine and Pantheon's servers.

Nearly all tutorials you encounter will also assume you are able to download files to your server/local machine.

Even if you don't install Drupal to your local machine, you can clone your Pantheon repository and download/edit/commit the files locally without running Apache, MySQL, etc. (Documentation here)

I would not try loading modules via URL using Pantheon; you need to learn how to use Git or you will constantly be running into problems later when you try to sync your sites.

Alternately, if you just want a WSYIWYG editor and some other nice features, you could try spinning up the Panoply distribution of Drupal 7, which includes a bunch of modules pre-configured out of the box (though it still has a fair number of bugs).

---
Tags: wysiwyg
---


title: switching between 2 views

text:
# Question
Title: switching between 2 views
I have created two Views, I then placed the second view on the footer of the first view. Main view has date, an image, attachment and size of the attachment, the second one has an images that are linked to a files. Output, latest one should always display on the top with an image, attachment and size of the attachment which I got it right when I click on the image from the footer I want an image to display above with the attached file and the size. May anyone help on how I can do the switching part in. See an the attached, am using Drupal 7

# Answer
> 0 votes
I have actually resolved my problem by adding a piece of php code within filter criteria. see attached.

---
Tags: views
---


# Question
Title: how to block a user from publishing a node in drupal 7
Please tell me that the user creates a node and he or she cannot publish that node on website and administrator can review that node and then the administer publish that node....

# Answer
There is workflow module which suits your requirement.

> The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.
> 1 votes

# Answer
consider using the workbench module suite it gives you full control who can do what, and introduces states, like needs review.

with the publish content module you have a simpler approach. only permissions.
> 1 votes

---
Tags: users, nodes, blocks
---


title: Drupal7: Linked template node file

text:
# Question
Title: Drupal7: Linked template node file
How I can define my node-title.tpl.php via dashboard?

Here what I did:

1. I created new content type page (our locations)
2. I uploaded a file to the templates: node-our-locations.tpl.php
3. I added new (our locations) content, and I set (our locations) in the title field

# Answer
You should read the page about Drupal 7 Template suggestions \- you would see that the proper template suggestions for Drupal 7 nodes are :

* `node--NODEID.tpl.php`
* `node--NODETYPE.tpl.php`

I'm unsure from your question whether you want a template for a particular node (in which case you should use the node id, not the node title - `node--NODEID.tpl.php`) or for all nodes of your content type "our locations" (in which case you want to use the second form, which depends on the node type, not the node title, `node--NODETYPE.tpl.php`)

Note that NODETYPE is your content type's machine name - on your site you will see this next to the content type name when you go to "admin/structure/types", and that hyphens should be replaced by underscores. So if your content type machine name was `our-locations`, the template file you want is `node--our_locations.tpl.php`)

Finally remember that once you've added the new template file, you must clear your cache before it gets noticed. You can do this on the performance page on your site at "admin/config/development/performance".
> 1 votes

---
Tags: theming
---


# Question
Title: How to get the list of all entity reference fields and their params?
I'm trying to build a new widget for the entity reference module. (nested checkboxes = tree according to entity references between nodes)

The only answer I'm looking for is : "How to get the list of all entity reference fields and their params? (child and parent node)

Thank you for your help!

Ludovic

Edit : working on D7

# Answer
> 1 votes
Here is my custom function that gets id's of all files referenced entities and their parents. Also get's all field names, entity types and bundles of entityreference fields.

```
function _my_module_get_entityreferences_settings() {
  $child_ids = $field_names = $settings = array();

  // Get all entityreference field names
  $query = db_select('field_config', 'f');
  $query->fields('f', array('field_name'));
  $query->condition('f.type', 'entityreference');
  $query->distinct();
  $rows = $query->execute();

  foreach ($rows as $row) {
    $field_name = $row->field_name;
    $field_names[] = $field_name;
  }

  // Loop all entityreference fields. Get all child and parent Ids
  foreach ($field_names as $field_name) {
    $table = 'field_data_' . $field_name;
    $target_id = $field_name . '_target_id';

    $query = db_select($table, 'f');
    $query->fields('f', array('entity_id', $target_id, 'entity_type', 'bundle'));
    $query->distinct();
    $rows = $query->execute();

    foreach ($rows as $row) {
      $settings[$row->entity_type][$row->bundle][$field_name] = $field_name;
      $child_ids[$row->{$target_id}] = array(
        'id' => $row->{$target_id},
        'parent' => $row->entity_id,
      );
    }
  }

  return array(
    'childs' => $child_ids,
    'settings' => $settings,
  );
}

```

Maybe you don't need all this stuff. When you get $field\_names array you can use

```
$field = field_info_field($field_name);

```

to get settings of current field. You can find here referenced bundles, field type, handler\_settings etc.

---
Tags: 7, entities
---


# Question
Title: Disable jquery.ui.theme.css only for front end?
I'm using jquery tabs on my page but they loaded some default styles that I didn't want. Thus I removed them with the following code:

```
drupal_add_library('system', 'ui.tabs');

function mytheme_css_alter(&$css) {
   // List of disabled drupal default css files.
   $disabled_drupal_css = array(
      // Remove jquery.ui css files.
      'misc/ui/jquery.ui.core.css',
      'misc/ui/jquery.ui.theme.css',
      //  'misc/ui/jquery.ui.tabs.css',
   );

  // Remove drupal default css files.
     foreach ($css as $key => $item) {
         if (in_array($key, $disabled_drupal_css)) {
            // Remove css and its altered version that can be added by jquery_update.
            unset($css[$css[$key]['data']]);
            unset($css[$key]);
         }
     }
}

```

This seems to do the trick, but I also noticed that my backend is not loading it's styles properly. I guess some of it uses the jquery.ui styles.

How can I load these only for the logged in user but not for

# Answer
> 2 votes
I would use **user\_is\_anonymous()** function like this:

```
function yourtheme_css_alter(&$css) {
  if(user_is_anonymous()) {
    $exclude = array(
      'misc/ui/jquery.ui.core.css' => FALSE,
      'misc/ui/jquery.ui.theme.css' => FALSE,
    );
    $css = array_diff_key($css, $exclude);
  }
}

```

# Answer
> 1 votes
i guess you use the your theme also as admin theme. just use seven as admin theme, and this hook will not be considered.

otherwise you have to check in the hook if your on an admin page, like

```
if (path_is_admin(current_path())) {}

```

---
Tags: theming, users, javascript
---


# Question
Title: How to replace the date field selects with one text field in Drupal 7 web forms
I am using webforms in Drupal 7. Is there a way to set the date field to a single textfield instead of 3 select fields?

# Answer
> 2 votes
Since it seems like the webfrom module doesn't support this functionality yet, if found that the easiest way to do this, was to use a textfield and use form\_alter to add the datepicker plugin.

```
function custom_form_form_alter(&$form, &$form_state, $form_id) {

  if($form_id != 'webform_client_form_2') return;

  // Alter textfield for date to integrate popup calendar
  $form["submitted"]["expected_move_date"] = array(
    '#type' => 'item',
    'finished_after' => array(
      '#type' => 'textfield',
      '#attributes' => array('class' => array('datepicker')),
      '#required' => TRUE,
    )
  );

  $form['#after_build'] = array('custom_form_uidatepicker');

}

function custom_form_uidatepicker($form, $form_state) {
  drupal_add_library('system', 'ui.datepicker');
  drupal_add_js("(function ($) { $('.datepicker').datepicker({
      showOn: 'both',
      buttonImage: 'sites/all/modules/custom/custom_form/images/calendar.png',
      buttonImageOnly: true,
      dateFormat: 'dd/mm/yy',
    });
    $('.datepicker').datepicker( 'option', 'minDate', 'd' );
    })(jQuery);", array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

    return $form;
}

```

# Answer
> -1 votes
It might be best to use the webform\_scheduler as that has the date popup dialog already installed. More details from the module's project page:

> It adds an optional start date and end date field to the webform form settings. If the current date and time falls outside the specified window, the webform is disabled.

---
Tags: webforms
---


# Question
Title: Adding CSS class to fields (Content Types)
I added a new content type with some fields

I have a field to upload image, I want to add a CSS class to this specific field, Should I done it via node-file.tpl.php

or via the dashboard and where?

# Answer
Try out Field Formatter CSS Class module.

> allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.
> 0 votes

---
Tags: theming
---