# Question
Title: How do I create a container entity that contains variable number of fields
I am interested in creating a content type that contains a variable number of fields. Each field contains an entity reference to another entity, but as I said there may be one field or 4 fields. I'm a little unclear the best way to implement this

# Answer
> 1 votes
I'm not sure if I understand correctly what you want to achieve, but the following two modules come to my mind that could be helpful:

> Field collection provides a field-collection field, to which any number of fields can be attached.

> All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

I suppose in your case *Field Group* would actually be the more interesting module to look at. You can wrap a group of fields and you can then set the number of the field group to `unlimited`.

You can also have groups inside of groups. But things *can* actually get a bit 'messy' when editing a node with grouped groups.

# Answer
> 0 votes
If your intent is not a collection of fields as previously answered, but to have an indeterminate number of a single field, that functionality is built into Drupal. At the bottom of the Field edit page, is a section for the Number of Values:

Here you can set how many fields you want represented in the content. If it is a select list, you will be able to choose multiple items from one list, it will not add a whole new select list for each entry.

---
Tags: nodes, entities
---


# Question
Title: Module update manually multiple versions at once
Actually my website use module views 7.x-3.5 version. The last version is 7.x-3.11, so i need update. My question is if I can upgrade (replace folders and code) directly to version 7.x-3.11 and run mysite\update.php or I need apply each new version separately running update.php for each, e.g. views 7.x-3.6, views 7.x-3.7...

# Answer
You can replace it with the latest version and run **update.php**. Drupal modules keep track of what version data schema it's on; **update.php** will apply the needed DB updates since 7.x-3.5.
> 0 votes

---
Tags: views, 7, updating
---


# Question
Title: Remove js file by template or add condition in info file
I work on drupal 7, I added all js by info file, work well in whole site. But we want to remove or not load of a specific js in a specific content type page.

I try by template.php of following code

```
function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type) && !empty($vars['node']->type) && ($vars['node']->type == 'my_content_type')) {
    $js_path = drupal_get_path('theme', 'mytheme') . "/js/xyz.js";
      unset($vars[$js_path]);
  }
}

```

but load xyz.js. How to remove of this js file.

# Answer
You can use hook\_js\_alter()

> Perform necessary alterations to the JavaScript before it is presented on the page.
>
> Parameters
>
> $javascript: An array of all JavaScript being presented on the page.

Then you should be able to use menu\_get\_object() to load the node type and unset the js file in the $javascript array.

```
function MYTHEME_js_alter($javascript) {
  $node = menu_get_object();
  if ($node->type == 'node_type) {
    unset($javascript['path/to/script.js']);
  }
}

```

Note: I haven't tested this or checked syntax, let me know if it doesn't work and I will test.
> 0 votes

---
Tags: theming, .info
---


# Question
Title: Better exposed filters allows only one checkbox at a time
Im using a exposed filter in views. That filter is displayed as a checkbox using the BEF module. Im allowing multiple selection on that filter.

The problem is that when a user click on multiple checkboxes at once it only selects one. Its like refreshing after you check one selection and then it scrols up the list. You can select more then one option, but not at once.

And yea, Ajax is enebled.

Anyone else has this kind of a problem?

# Answer
Follow the steps:

1. go to advanced tab.
2. Under exposed form section, go to exposed form style setting. (BEF settings).
3. Then under display option of your checkbox field, expand more options and check add select all/none option.
4. Uncheck autosubmit option if checked.
> 1 votes

---
Tags: views
---


title: Clean url for custom query parameters

text:
# Question
Title: Clean url for custom query parameters
I have a custom filter form in my site and the form submitted by the filters adds 2 Get variables to the url. However, the variables appear in the form of:

```
http://example.com/newpage?param1=a%2Cb&param2=c

```

instead of:

```
http://example.com/newpage/param1/a%2Cb/param2/c

```

I have Global redirect clean url enabled and I have pathauto module in my installation and clean url test to checl mysite.com/user/login works fine.

I have tried a couple of plugins eg. query\_parameters\_to\_url but they are not working for that page and I tried adding hook\_url\_outbound\_alter and hook\_url\_inbound\_alter in my custom module but they overwrite all the urls.

Can anyone suggest a way to implement clean urls for somehting like this with affecting the urls for other pages in the website?

# Answer
Are you using Views? If so, you could try using Views arguments for exposed filters: https://www.drupal.org/node/54455
> 0 votes

---
Tags: forms, uri, views
---


# Question
Title: View to filter a list of nodes which has TWO taxonomy terms
I have a content type - 'video post'. This content type has several taxonomy terms associated with it, 'star rating' and 'warm up'.

The 'star rating' taxonomy is a list of numbers: 1, 2, 3, 4

The 'warm up' taxonomy has 3 options: warm up, long, cool down.

What I've been trying to do is to create a view block to display on the content type 'video post' so that it displays a list of nodes which have the exact same set of taxonomy terms as the one currently being viewed.

So if I go to node/1 and this has these two taxonomies as follows:

star rating - 2

warm up - long

I only want nodes to display which also have this same combination of terms.

It would also be great if I could exclude the current node from the list too, as this is obviously not required.

I've tried just about everything that I know, but I always seem to get results that I don't want.

Any help is greatly appreciated.

# Answer
Download the Views PHP module:

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

In Views:

* create a new View of 'video post' content type, as a block and set it up to show all entries for now, in the format and layout you desire
* add a contextual filter for the star rating field (you will need to adjust the field names appropriately):

+ Provide a default value, PHP code:

    ```
    $node = menu_get_object();
    return $node->field_star_rating['und'][0]['tid'];

    ```
* add another contextual filter for the warm up field:

+ Provide a default value, PHP code:

    ```
    $node = menu_get_object();
    return $node->field_warm_up['und'][0]['tid'];

    ```

The first line retrieves the page object (which should only ever be a video post node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

* add a regular filter, Global PHP code:

```
$node = menu_get_object();
if($data->nid == $node->nid) return true;
else return false;

```

The first line again retrieves the page object, and compares its node ID with the node ID of the current entry, filtering it if they match. It may appear backwards, but that's how the Global PHP works for some reason. Returning true excludes the row.

* under `admin/structure/block`, set the view-block to show where you want on the page, restrict it to show only on the content type video post.
> 0 votes

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


title: Create a theme function for form fields

text:
# Question
Title: Create a theme function for form fields
I need to theme certain form fields on the user profile form page differently from other fields, for which I am trying to create a theme function that outputs html its own way, not using theme\_form\_element(). The reason for defining a new theme function alternative to theme\_form\_element() is because the html output is dramatically different.

This is my code:

```
function mymodule_theme() {
  return array(
    'profile_form_element' => array(
      'variables' => array(
        'element' => NULL,
      ),
    ),
  );
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state) {
    $form['field_user_first_name']['#theme'] = 'profile_form_element';
    dpm($form['field_user_first_name']);
}

function theme_profile_form_element(&$variables) {
  $element = &$variables['element'];
  // my html processing would start here...
}

```

...but the theme function has NULL for $variables\['element'\]. What am I doing wrong? I am attaching the structure of my form field (*field\_user\_first\_name*), which was created through the UI at configuration \> people \> account settings \> manage fields.

# Answer
I think one of your problem is with this:

```
$element = &$variables['element'];

```

I don't think you can assign a reference to an array element (the &), so try changing it to:

```
$element = $variables['element'];

```

and I don't see a 'element' element, so unless I'm blind you're trying to access an element that isn't there, so it will always return NULL;
> 0 votes

---
Tags: theming
---


# Question
Title: How does the view filter: Search: Search Terms works? Can I improve it?
I have a View with and Exposed Filter: **Search: Search Terms** to filter the view result based in the keywords entered in this filter.

I works, but not as I expected.

Lets say I have a node with the title "The car, a good transport". Then:

* if I enter the keyword: **car** the node is shown
* if I enter the keywords: **car a good** the node is not shown
* if I enter the keywords: **good car** the node is not shown

Is this behaviour right? I need the node to be shown in all these situations

**UPDATE**: I see that there is already an open issue about this: http://drupal.org/node/1615438

# Answer
If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word"
> 5 votes

# Answer
Search API allows the indexing of multiple fields. This would allow you to search both title and body fields.
> 0 votes

# Answer
It's better to use operator "contains all words". Drupal search is no good, it's indexing everything but then you can't find anything..
> -1 votes

---
Tags: search, views
---


# Question
Title: public files config in settings.php creates .htaccess file
I had multisite previously, two sites sharing same codebase like but having their own files system: -

1. site1 -\> sites/site1/files/FILES\_HERE
2. site2 -\> sites/site2/files/FILES\_HERE

Now I am trying to separate the sites to its own sites and separate codebase to use the normal Drupal structure like: -

1. site1 -\> sites/default/files/FILES\_HERE
2. site2 -\> sites/default/files/FILES\_HERE

but somehow whenever I clear the cache, it creates folder like: -

1. site1 -\> sites/site1/files

and uses this instead of `/sites/default/files`

To overcome that I added some config in **settings.php** file

```
$conf['file_public_path'] = 'sites/default/files/';
$conf['file_temporary_path'] = '/tmp';

```

Now, the **site1** uses proper file i.e. `/sites/default/files` but it creates **.htaccess** files inside `sites/default/files/` folder. The **.htaccess** file contains:

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

The images in the website doesn't load properly because of this file. If I delete this file the Images load properly, but while clearing the cache the file is auto generated and again the image doesn't load.

File permission is not an issue here as its 775 universal except for settings.php file.

# Answer
The main culprit was extra trailing `/` in the files path in **settings.php** file. Which I changed to

```
$conf['file_public_path'] = 'sites/default/files';
$conf['file_temporary_path'] = '/tmp';

```

And deleted the **.htaccess** file, now the files inside `sites/default/files` are readbale by server even after clearing the cache.
> 1 votes

---
Tags: 7, multi-sites, configuration
---


title: Validate URL alias before saving Node

text:
# Question
Title: Validate URL alias before saving Node
I have a custom content type which has a url alias pattern of \[node:type\]/\[node:title\].

How can I validate the node form in order to prevent the url alias from becoming \[node:type\]/\[node:title\]-0 in case the same title is used somewhere else.

Basically, I would like to prevent the node from saving, and display an error message if the url alias will end up having a "-0" at the end.

# Answer
How about using the Unique field module for this? Here is a quote about the module's project page:

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.
> 2 votes

---
Tags: path-aliases, nodes
---


# Question
Title: How to use AJAX form on custom maintenance page
I have been working to customize our maintenance page via custom template and hook\_preprocess\_maintenance\_page(), the intent is to provide the maintenance message, some static text, as well as a basic AJAX form that allows the user to select a state, and then a specific location in that state, once they submit they will then be passed to the appropriate location outside of our site.

This is how I am handling the form:

in hook\_preprocess\_maintenance\_page()

```
$vars['maintenance_header'] = $vars['content'] ? "<p>" . $vars['content'] . "</p>" : "<p>System Maintenance</p>";
$vars['maintenance_content'] = "<p><span class='feature'>Don't go anywhere!</span></p>";
$maintenance_form = drupal_get_form('ajax_example_simplest');
$vars['maintenance_join_form'] = drupal_render($maintenance_form);

```

in maintenance-page.tpl.php

```
<?php print $maintenance_header; ?>
<?php print $maintenance_content; ?>
<?php print $maintenance_join_form; ?>

```

In building the form I noticed that when the Ajax callback fires, the contents of $vars\[maintenance\_header\] is printed to an alert window on the screen, instead of the page being updated as I expect. To validate if this was an issue with my form specifically, I grabbed the simple ajax example which is linked below, and the behavior is exactly the same. https://api.drupal.org/api/examples/ajax\_example%21ajax\_example.module/function/ajax\_example\_simplest/7

In searching for questions around this I continue to find general ajax questions, and questions about theming the maintenance page, but nothing that covers using an ajax form within the maintenance page, so I have started this new topic to see if others have encountered this specific issue. I am wondering whether an ajax form simply won't work on a custom maintenance page or if this is related to how I am handling the form in the preprocess hook?

Thank You, Rose

# Answer
> 0 votes
When you put your site to offline mode, the menu router system (which is called first when a request is received to serve a page).

By default, Ajax forms are handled from the path `system/ajax`, which is not allowed when the site is in offline mode. This is not an issue with Drupal itself, it's just that when a site is in offline mode, there is no guarantee that any system is in working condition.

Ajax forms require the form to be cached, and that cache storage is the database unless you alter otherwise. When the database connection is failed, Drupal returns the same maintenance-mode page. Now, if you embed an Ajax form, imagine how there will be a recursion.

If you still need an Ajax form, you need to implement `hook_menu_site_status_alter()` to alter the site status for a specific path. Then, in your form, your will need to turn off caching (`$form_state['no_cache'] = FALSE`), and add your own `#ajax` properties with especially `['#ajax']['path']` set to your custom path that bypasses site status check (from the `hook_menu_site_status_alter()` hook).

I didn't bother to write an example since your question indicates you already have the Ajax form setup. Disable its cache, add a custom path to handle the submitted data, and make that path accessible with a `hook_menu_site_status_alter()` hook.

---
Tags: theming, maintenance-mode, ajax
---


# Question
Title: How to get field data for Panels style plugin? (ctools context?)
I think this is a Ctools context question. I'm writing my first Panels style plugin and am having trouble getting field values from nodes inside the pane. I'm basically trying to recreate the plugin from this tutorial, http://precessionmedia.com/blog/creating-custom-panels-style-plugin-background-image-support, but I have changed it from a region plugin to pane plugin. The pane contains a list of node fields generated by Views, and I need to get the info from an image field but I'm not sure how to proceed.

In the link above, the render region callback uses this function: `ctools_context_keyword_substitute($string, $keywords, $contexts, $converter_options = array())`, where `$contexts` is `$vars['display']->context`, but this array is empty for me. I'm also not sure what values to use for `$string`. In the example link above, `$string` is replaced by the value entered into the style plugin settings form and the example given in the tutorial plugin is `%node:field_image`, isn't this just a token? I'm not sure if this is the right token to use, but I believe the missing context array is what is breaking this function for me.

Thanks, any help is greatly appreciated.

# Answer
I had to add a Relationship to the File from the Context section of the panel variant (e.g. `File from Node (on Node: Image [field_featured_image])`). Now you will be able to use `%file:url` in the image field. Basically, the token you use needs to be listed in the summary of contexts.
> 0 votes

---
Tags: views, entities, panels, chaos-tool-suite
---


# Question
Title: Overview & help with drupal files and folders on Win 7
I am a newbie. Please forgive me if this is a dumb question.

I'm trying to wrap my brain around what is Drupal and how it works.

I installed Acquia Dev Desktop successfully on my Win 7 computer. I want to make sure that I backup all files and folders, but have discovered that Drupal/Acquia is scattered just about everywhere on my hard drive. I found the following (where "Sam" is my Win 7 username).

* C:\Program Files (x86)\DevDesktop
* C:\Users\Sam\Sites
* C:\Users\Sam.acquia
* C:\Users\Sam.drush

Have I missed any locations? Why is everything not consolidated in one folder? It would make life much easier!

If this is not the proper forum for dumb questions please tell me a better place to post.

Thanks!

# Answer
The confusion is probably resulting from things that differ from the Windows environment compared against the traditional multi-user LAMP environment that Drupal is usually built against.

To explain what those directories are in the order you listed them:

* The DevDesktop application code
* Your sites you're managing with Acquia
* Acquia application configurations
* Drush application configurations

This data is separated mostly to accommodate a multi-user environment. So that...

* All the data for the DevDesktop application is isolated so multiple users can use the app.
* The sites you manage are separate from other users.
* Your Acquia application configurations are separate from other users (e.g. your login info).
* You Drush application configuration is separate from other users (e.g. your site aliases).
> 0 votes

---
Tags: 7, database, files, installation
---


# Question
Title: Trying to convert db_fetch_object for Drupal 7
I am trying to convert a line of code from Drupal 6 for Drupal 7

```
for ($i = 0; $order = db_fetch_object($result); ++$i) {

```

Above is what it is -- and below is what I made it

```
for ($i = 0; foreach ($result as $order); ++$i) {

```

BUT . . . I get a parse error:

> Parse error: syntax error, unexpected 'foreach' (T\_FOREACH), expecting ';' in / \[PATH TO FILE\] on line 483

Which is this

```
for ($i = 0; foreach ($result as $order); ++$i) {

```

SQL syntax checkers find no error in the syntax - I only a novice

# Answer
> 2 votes
the syntax is incorrect, and the error is correct. If you need to track $i, you could do something like:

```
$i = 0;
foreach($result as $order){
  ...
  $i++;
}

```

---
Tags: database
---


# Question
Title: Getting access denied when altering user view route
I want to display custom content for the user profile page instead of the entity view so I am altering the entity.user.canonical route and I am setting a custom controller and title compared to the entity view and page callback that is set by the UserRouteProvider. I am leaving the requirements athey are since I don't need to change anything regarding the permissions.

Strangely though I am still getting Access denied after I flush the cache. The code that I am using in my event subscriber that is run on the RoutingEvents::ALTER event is:

```
  $collection = $event->getRouteCollection();
    $route = $collection->get('entity.user.canonical');
    $route->setDefaults(array(
      '_controller' => '\Drupal\mymodule\Controller\UserController::profilePage',
      '_title' => 'Profile'
    ));

```

If I will use setDefault('\_controller'...) instead of setDefaults() method it will work since I think the \_controller has more priority over \_entity\_view but the \_title does not have priority over \_title\_callback. So this is not a viable solution.

Any idea what the issue with that access might be? Does the \_entity\_access requirement require the \_entity\_view to be used instead of the controller? Should the presence of the entity in the url be sufficient?

# Answer
Can't be sure as you haven't posted your controller, but my guess would be that you are not type hinting the argument there as `UserInterface $user`, so it doesn't get upcasted. That is required for `_entity_access` to work
> 0 votes

---
Tags: entities, 8, routes
---


# Question
Title: moving a drupal website to another server
I've been working on a drupal website in a server for months but after moving it to another server and url some of the files are not read. for example it seems that it does not read colors.css or all of the image files used in the site.

for more clarification I must add that there is a joomla site on www.example.com then I've put my drupal site on www.example.com/test this is the site which does not work properly.

and before that it had been working on www.something.com/test/test1.

I don't have a clue why it has happend! help

# Answer
default files permission was making problem. It's permission must be 755. that was all!
> 0 votes

# Answer
check the sites/default/settings.php for $base\_url

it might have been set for a sub-directory install, and may still reflect the original server location.

if it wasn't set originally, setting it now may help as well.
> 1 votes

---
Tags: files, backups
---


# Question
Title: Import XML with nested elements into field with settings "Number of values" = "Unlimited"
Noob to Drupal here. I'm looking to import 100 xml files into an empty D7 database. Each xml file contains links to other xml and image files. I have Feeds, Xpath Parser, and Tamper modules installed.

Drupal Content type = Article Fields (machine name):

* unique\_xml\_id (Text)
* body (Long text and summary) -\> settings "Number of values" = "Unlimited"
* field\_images (Image) settings "Number of values" = "Unlimited"

Here's the xml. Every xml file has a unique id by combining pid and gid.

```
<testContent pid="5" gid="000007">
  <textContent title="Title 1" ordinal="0">His car</textContent>
  <textContent title="Title 2" ordinal="1">Our car</textContent>
  <textContent title="Title 3" ordinal="2">
    This is my <textLink linkType="int" pid="5" gid="000014">car</textLink> -> link to xml
  </textContent>
  <visualHeader title="Images">
    <visualContent mid="1057" alt="Radiator" type ="thumb"> -> image url, ex: img/1057.jpg
      <visualLink pid="6" gid="001057"</visualLink> -> link to other xml file with parent img
    </visualContent>
    <visualContent mid="1092" alt="Wipers" type="thumb"> -> image url, ex: img/1092.jpg
      <visualLink pid="6" gid="001092"</visualLink> -> link to other xml file with parent img
    </visualContent>
  </visualHeader>
</testContent>

```

OBJECTIVES:

1. Map the concatenation of the xml attributes "pid" and "gid" to field "uniquexmlid" and make this check for uniqueness
2. Map textContent elements to body field values (array?), example: body\[0\] = "His car" body\[1\] = "Our car" body\[2\] = "This is my car" (car is link to other node that does not exist yet in database)
3. Map "car" link to url of other node (not yet created from xml file) with path alias inside body\[2\] field

How do I accomplish these? I'm open to suggestions of other ways of setting up the fields in Drupal.

# Answer
Also when you import from html pages you have to set to html xpath parser.
> 1 votes

---
Tags: 7, importing-exporting, feeds
---


title: Separate css class

text:
# Question
Title: Separate css class
Only for front page I want separate css body class. If a apply in html.tpl.php then it is applicable on each page. How can I apply condition for front page?

# Answer
In your template.php check the `drupal_is_front_page` function, if it is true use the drupal\_add\_css to load extra css styles.
> 0 votes

---
Tags: 7
---


# Question
Title: db_select get all results count when also using a pager
Is it possilbe to get the count of all rows, when using a pager in a db\_select query? My pager is the following:

```
$query = $query->extend('PagerDefault')->limit(20);

```

# Answer
Yes you can use `setCountQuery` if you need to define a count query to return the total number of rows in your resultset.

See the docs for PagerDefault::setCountQuery()
> 2 votes

# Answer
It can be considered as Conditional pager. For example, depending on value of $pager, when all results are needed `$pager='all'`.

```
   if(is_integer($pager)) {
     $query = $query->extend('PagerDefault')->limit($pager);
   }

```
> 0 votes

---
Tags: database
---


title: End date shown on calendar

text:
# Question
Title: End date shown on calendar
I'm using the Calendar, and Date modules to create an agenda on a website. However, when I create an event with a start and end date, it also shows the event on the next day. While this is useful for true multiple day events, it is not for party that start late and end late, as I want them to only show once (at the start date).

Is it possible to fix this?

For clarification: I'm using the Date (ISO format) field.

# Answer
I would check your date/time settings, specifically the sites default time zone. I have seen similar errors when that is set incorrectly.
> 0 votes

# Answer
I imagine the end date is not really important in terms of using the calendar itself, so why not addding the end date as an additional field for information purposes only?
> 0 votes

# Answer
try to follow below steps: it may solve your problem.

1. go to contextual filter under advanced tab in views.
2. select date(node). then in configuration of this date(node), select only the starting date in date field. and check method as AND.

This will display only the starting date on your calender.
> 0 votes

---
Tags: datetime
---


title: How do I add a new content status?

text:
# Question
Title: How do I add a new content status?
What hook would I use to add a new content status under the path admin/content? See image below.

I am trying to give my content type(s) a new status so that I can do some more filtering on it. Specifically, I want to create a new "draft" status. Any pointers on where to start and API's to look at? Or are there any existing modules that do this that I can take a look at the code?

EDIT: I would like the user filling out the form to set their own status as 'draft'. The reason is that I am using the save\_draft module (http://drupal.org/project/save\_draft) that allows the user to save values in a form without submitting it. The problem is that Drupal considers the node to be unpublished. My editors should not see the content type if it is in "draft" mode, but since Drupal saves it as "unpublished", my editors see this and they are not sure if the content is ready to be edited or if the end user is just saving their work and finishing it up later.

The save\_draft module gives me 2 buttons (Publish and Save as Draft). This allows the user to select their own status. I would also like this new "save as draft" status to be searchable/sortable so my editors could find out who hasn't finished submitting their unfinished draft, if need be.

# Answer
I was able to solve my own problem by creating a field that sets the status (e.g. "draft", "to be reviewed").

I then used jQuery to hide this field. Also in jQuery, I made it so that when the user clicks on the "Publish/Save" button, then it sets the value of this hidden field to "to be reviewed". If the user hits the "Save as draft" button, then this hidden field is by default set to "draft".

In other words, my 2 buttons will set the value of this hidden field and the user can decide if their submission is ready to be reviewed or not, and my editors will know based on this hidden field on the form.
> 0 votes

# Answer
You should look at the workflow module. This one is used to create additional work flows and status in your content authoring.
> 2 votes

# Answer
In addition to Workflow you can use Workbench with Workbench Moderation

Its very difficult to alter Built-in Content administration page (admin/content), the filters hard-coded in modules/node/node.admin.inc

```
/**
 * List node administration filters that can be applied.
 */
function node_filters() {
  // Regular filters
  $filters['status'] = array(
    'title' => t('status'),
    'options' => array(
      '[any]' => t('any'),
      'status-1' => t('published'),
      'status-0' => t('not published'),
      'promote-1' => t('promoted'),
      'promote-0' => t('not promoted'),
      'sticky-1' => t('sticky'),
      'sticky-0' => t('not sticky'),
    ),
  );
  ....
  return $filters;
}

```
> 0 votes

# Answer
you can use Custom Publishing Options module for add some status to your content
> 0 votes

---
Tags: 7
---


title: Remove calendar hyperlink

text:
# Question
Title: Remove calendar hyperlink
Can see black circle at the picture below?

How to remove that hyperlink?

# Answer
> 0 votes
I found it. Due to i only want to post month calendar only. To solve this, just disable day, week and year in the view.

---
Tags: 7, datetime
---


# Question
Title: How to get page visit count from access log
I need to display the list of pages(nodes & terms) from access log. I enabled drupal core statistics module.

The view result should include

1. Page title.
2. Total number of distinct pages($view-\>total\_rows).
3. Total views result($view-\>result).
4. Individual visit count of pages ().

I created a view and a template. I am getting points #1,#2 & #3 in my view. But #4 is missing.

I checked access log table in DB, but didn't found the column for page view count. How can get the missing point in my view?

# Answer
## 1. Module Visitors

You may want to consider the Visitors module. As mentioned on its project page, it provides a block containing:

* Total Visitors.
* Unique Visitor.
* Registered Users.
* Last Registered User.
* Published Nodes.
* Your IP.

At this time there is no integration with the Views module ... yet. All reports created today use the `theme` function. Such views integration is being considered though, i.e. in the format of some out-of-the-box example, similar to the view delivered with the charts module.

## 2. Module Forena

If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Views integration of the Forena module. Here is a relevant excerpt about that from its project page:

> Use Views with Forena to create additional more complicated layouts than can typically be created using views. Forena provides a views rowstyle plugin that lets you use a Forena report to format the output of a view.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc.

## 3. Other modules

Modules related to Visitors contains some other modules available, which might be considered as a possible alternative (or maybe 'addition'?), such as the Views Watchdog module.

Disclosure: I'm maintainer of the Visitors module, and co-maintainer of Charts and Forena,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

# Answer
You just need to enable Drupal this core module "**STATISTICS**", after enabling this, go to your view and in view's "**Add fields**" section

1. Click add
2. Select "**Content statistics: Total views**"

This will give you the total number every single page has been viewed.
> 1 votes

---
Tags: 7, views, nodes
---


title: Using token in Block title

text:
# Question
Title: Using token in Block title
I want to use token to show user name in block title. But it is not working. I tried like \[user:name\]

Thanks in advacne

# Answer
The correct format is `[current-user:name]`.
> 3 votes

# Answer
You need to write `[site:current-user]` to get current username.
> 0 votes

---
Tags: 7, blocks, tokens
---


# Question
Title: How to change my homepage based on the time of day?
I have searched high and low for this. How do I change my homepage based on the time of day? To be absolutely explicit, I want:

1. Between 8am and 7pm - Homepage 1 (node/4)
2. Between 7pm and 8am - Homepage 2 (node/5)

So I want to design two completely different homepages and then they change based on time of day.

I tried some code but it doesn't seem to do the job:

```
$current_front = variable_get('site_frontpage');

if($current_front== 'node/4'){
    variable_set('site_frontpage','node/5');
}else{
    variable_set('site_frontpage','node/4');
}

```

**Note**: I am not a code whizz so wouldn't know where to start with hooks and I'm a million years away from creating my own modules.

# Answer
Consider using the Rules module to set the appropriate node as your frontpage.

Based on the sample in the question, I'm assuming that node/4 is what the value is of `site_frontpage`. Here is the actual rule to be created that could work in your case:

1. Create a new rule
2. Event = Content is viewed
3. Condition: data comparison -\> `node:nid` equals `4`
4. Add an extra condition to check if current time is between 7pm and 8am.
5. Action: page redirect to `node/5`

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module. Maybe also review the set of 30 video tutorials about the Views module ... Familiarity with only those 3 modules (**Views**, **Rules** and **Flag**) can get you pretty far in mostly any Drupal site (as a site builder).
> 6 votes

# Answer
I would suggest a custom module with a couple of cron hooks (in one hook\_cron function).

* Set one cron hook (A) to change the front page to node/4.
* Set the other cron hook (B) to change the front page to node/5.
* Install Ultimate Cron, and use the Crontab scheduler.
* Set hook A to `* 8 * * *`
* Set hook B to `* 19 * * *`

Of course, that will only work based on your server clock, and won't change based on the user's time zone. If you want that it'll be more tricky.
> 3 votes

# Answer
Have a look at the Theme Key module. Some more details about it, from its project page:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server
> 3 votes

---
Tags: nodes
---


title: Draggableviews with 2 separate views

text:
# Question
Title: Draggableviews with 2 separate views
I have 2 views. One is used to sort content of type `slider` using draggableviews. The other one displays an image field of the same `slider` content type. How can I use the weigh (sort order) of the first view in the second one?

In other words, I want to have one view that lets me sort my slider content, and another one that displays the slider content in the order defined in the first view. Any help would be appreciated. Thank you!

# Answer
> 3 votes
You can 'connect' both views through the (hidden) node ID:

* add the field `Content: Nid` to the fields list of your first view and check `Exclude from display` on the next screen.
* also add the field `Content: Nid` to the fields list of your first view and check `Exclude from display` on the next screen.
* add `Draggableviews: weight` to the sorting criteria of both views.
* in your second views sorting settings choose your first view under `Display sort as` to connect both.

---
Tags: views
---


# Question
Title: entity eck create new property type or/and behaviour
I guess everyone here has done what I want multiple times and I am probably just stupid but I can't seem to find it.

So in my drupal 7 installation I want to create an entity with a date property(so all bundles have a date that is set by a user). Perfect scenario is that this date is like the date field with calender to select a date.

I can't find how to do this but that's probably because I have no idea what to look for.

Can someone put me in the right direction for this?

Making it more clear: I could just add a date field in all bundles but that seems not the best way to me and I would like to learn drupal in it's best practice.

thanks in advance

# Answer
> 3 votes
You can follow the documentation of eck modules. https://www.drupal.org/node/1370980 The last version introduces the concept of behaviour and you can create your own.

1. Install the module date\_popup
2. Implement the hook hook\_ctools\_plugin\_directory()
3. Create your plugin
4. In the default\_widget callback return a renderable array where the #type is date\_popup

---
Tags: hooks, entities
---


# Question
Title: Drupal Content Access and if anomynous show login block
I have this website where every pages are viewed by anonymous users.

I want to create a new page (and add it to the menu) where **only the authenticated users** can have access to it.

I installed Content Access module but somehow it does not work...

**What I want is this: If it is an authenticated user - show page. If not, show login block, and then redirect to the page.**

I installed Rules module as well but I don't know how can that help me at all...

Thank you in advance, hope you guys can help!

# Answer
This depends what method is used to create the page. Pages that are created by the Views module define the permission settings in the "Access" configuration, as does page manager. But it sounds this is just a typical node page. Content Access should do the trick, but if not, you may want to try the Node Access module instead. Be sure to read the README on these modules, as they usually require you to rebuild permissions after enabling and configuring them. The permissions of the node should be understood by the menu system, so restricted pages will not appear to un-authorized users, which should satisfy the need to hide the menu item. If un-authorized users do land on the page somehow (such as yourself, after clicking a bookmark after your session has expired), then you can try something like the "Redirect 403 to User Login" module Although, in my opinion, the more sensible option might be to simply define your default 403 (Access denied) page as the login page. The only reason not to do this might be if you are trying to obscure the login process from anonymous users for some reason.
> 0 votes

---
Tags: users
---


# Question
Title: Getting "--> ;" on front page after editing custom html.tpl file
I am newbie and using Drupal - 7.

I have added script tags into my customized html.tpl file.

```
<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>

```

And now I am getting this "**--\> ;**" into front page of my website.

This is the code for my customized html.tpl. file with script tags.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
 <!-- <?php print $scripts; ?> -->
</head>
<body<?php print $attributes;?>>
<?php print $scripts; ?>
<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

Can anyone please help me?

Thanks!

# Answer
> 4 votes
I guess your problem comes from this line :

```
   <!-- <?php print $scripts; ?> -->

```

Don't comment things this way. Rather do :

```
  <?php /* print $scripts; */ ?>

```

Or even better just **delete the line** if not needed.

I hope that helps.

# Answer
> 5 votes
it is probably stemming from this line:

```
<!-- <?php print $scripts; ?> -->

```

`<!-- -->` is a commenting system for HTML, but the item you are trying to comment out is php, which uses a different method for commenting.

you would use the html commenting around html elements:

```
<!-- <div>Hello World!</div> -->

```

whereas for php:

```
<?php //print $scripts; ?>

```

or

```
<?php /*print $scripts;*/ ?>

```

would be appropriate.

---
Tags: 7, theming
---


# Question
Title: display description and price field from a term reference
this is my setup: a vocabulary(pulp\_toppings) containing 3 terms(honing, noten, brie). Each term also has a price field, I cannot find a way to display the prices of the terms :/ please help.

I have a line item with a term reference but it only references or displays the term titles.

So I could have toppings above my add to cart button but the prices of the toppings won't show.

I followed this tutorial(the screencast from Josh Miller about customizable items) to get the line item and taxonomy part: https://www.youtube.com/watch?v=j9KsyvQZaAY

What I need is either a solution for the above(changing the way my line item references the terms so also the price of the terms are shown) or a better way to handle toppings(not pricing attributes since it stopped working for me).

setup shown below:

# Answer
> 1 votes
If you have token you could 'rewrite output' on the Configure field: screen. I think yours is called 'form' (your 2nd last pic).

On that edit screen scroll down a little and you will see the rewrite output header. In there you can add tokens for fields that are already called earlier in your display. You can call the value and 'exclude from display' just to load them and have them available.

Unfortunately I can't make out the machine names you have assigned to the terms, but there is a button to show you all the available tokens.

Sooo, you could write the output and have `<label ...>[..field:?topping_ref:name][..field:?topping_ref:name]</label>`

# Answer
> 1 votes
You have to add a relationship to the term being referenced on the content type. Then you'll have access to all of fields available on the terms under your field selection section of the view's configuration form.

EDIT: Since It seems that because in your view you are trying to reference terms from a node that is being referenced from the node that's being displayed, even with grouping and aggregation, it would be difficult to try to create what you want directly in the view. It may be a better option, in your case, to use a view template for the field with the terms.

So it would look something like this (views-view-field--*view-display-name*--*field-machine-name*.tpl.php):

```
<?php
// Example code to grab the current field output value
$doc = new DOMDocument();
$doc->loadHTML($output);
$raw_val = $doc->getElementsByTagName("div")->item(0)->nodeValue;
// Now load the term programmatically to get the price value
foreach ($row->field_*field_machine_name*[0]['raw']['tid'] as $tid) {
  $term = taxonomy_term_load($tid);
  $price = $term->field_price['und'][0]['value'];
}

?>
<?php // print $output; ?>
<!--Now reconstruct the output-->
<div class="whatever-wrapper">
  <span class="whatever-name"><?php print $raw_val; ?></span>
  <span class="whatever-price"><?php print $price; ?></span>
</div>

```

Now you may not need to go through the whole process of loading the term, I just showed that as an example. This data may already be available to you in the other variables in the scope of that file which are;

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

```

Play around with something like that (the file should probably live in your theme's templates directory), and use the Devel module so that you have access to the dpm() function, which will print whatever you put in there on the page in an organized way. I recommend using dpm() on the $view, $field, and $row variables so you can see what you have available to you before trying to load the term programmatically in the template.

You can visit this Drupal docs page for more info on theming single fields in a view.

# Answer
> 0 votes
Thanks everyone for the help but I think it will be easier for me to get the Pricing attributes to work again.

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


title: Devel module and Krumo

text:
# Question
Title: Devel module and Krumo
I super love Krumo/Devel. However, I'm sure I'm missing something obvious, because when I use dsm() and I get my array or object all expandable and awesome, sometimes I have a hard time knowing *which* array or object it is. At the top, it just says `... (Object) stdClass`.

Is there somewhere that it includes the name of the object/array you're exploring? What about on the devel tab of a node?

# Answer
> 4 votes
Unfortunately, as per paragraph 4 here http://krumo.sourceforge.net/ it will not print the variable name. However, as it mentions, at the bottom of the krumo output it will tell you exactly where the call came from (file name and line number).

The object or array being printed out is always the variable inside your kpr call (or dsm/dpm). ie kpr($user) won't state explicitly that it is printing the $user variable.

On the devel tab of a node the object printed is the node object itself: $vars\['node'\] or $node depending on your setup.

# Answer
> 7 votes
Sometimes, if I need to differentiate between different debug items, I'll use something like the following:

```
kpr(array(
  'node' => $node,
  'comments' => $comments,
  'links' => $links,
));

```

Or, if debug items are split in different places, just simply:

```
kpr(array('user' => $user));

```

# Answer
> 4 votes
Again, Search Krumo can help. Let me show how it works. For example, we want to debug two objects:

```
  $user = user_load(1);
  sdpm($user); // user object
  sdpm(menu_get_object()); // node object loaded with menu_get_object() function.

```

We will see something like this:

P.S.There is known bug with `devel/php` textarea: http://drupal.org/node/1696920. So, don't use `sdpm()` there.

# Answer
> 0 votes
Configuration \> Devel settings

Then look at error handlers as they might be switched off.

---
Tags: debugging
---


# Question
Title: REST Server with my module service returns 404
I have set up my drupal REST using `REST Server` and `services`. Also I have created my own module which implements `hook_services_resources()`.

I have configured REST with to use my resource and node.

This works: http://local/rest/node/1

This does not work (returns 404): http://local/rest/hotel\_search

Here is my module:

```
function MY_MODULE_services_resources() {
    return array(
        'hotel_search' => array(
            'retrieve' => array(
                'help' => 'Search for Hotels',
                'callback' => 'MY_MODULE_hotel_search',
                'access callback' => 'MY_MODULE_access_callback',
                'args' => array(
                    array(
                        'name' => 'name',
                        'description' => 'hotel name',
                        'type' => 'int',
                        'source' => 'param',
                        'optional' => false,
                    ),
                ),
            ),
        ),
    );
}

function MY_MODULE_access_callback() {
    return true;
}

function MY_MODULE_hotel_search() {
    $json = array(
        'name' => 'response',
        'status' => 'ok'
    );
    return json_encode($json);
}

```

# Answer
> 1 votes
With the Services module, the "CRUD" resources are typically mapped only to entities, and routed to each based on the HTTP method:

```
GET -> Retrieve
POST -> Created
PUT -> Update
DELETE -> Delete

```

When building a custom service resource, you need to use the `actions` array when building your resource. In your example, your resources array would become:

```
return array(
  'my_module_resources' => array(
    'actions' => array(
        'hotel_search' => array(
            'help' => 'Search for Hotels',
            'callback' => 'MY_MODULE_hotel_search',
            'access callback' => 'MY_MODULE_access_callback',
            'args' => array(
                array(
                    'name' => 'name',
                    'description' => 'hotel name',
                    'type' => 'int',
                    'source' => 'param',
                    'optional' => false,
                ),
            ),
        ),
    ),
  ),
);

```

Your `callback` can just return an array or object, it doesn't need to encode the result, because Services will automatically do that based on the extension on the URL, e.g. `.json`.

You'd then make a call to it with a POST to:

```
?q=rest/my_module_resources/hotel_search.json

```

# Answer
> 0 votes
I do believe that, with the Services module, `json_encode` happens outside of the callback function you write.

Try to just return `$json` without encoding it, and see if that helps. If I'm correct, it will return JSON anyway.

---
Tags: services
---


# Question
Title: Hiding a field title label of a field collections field?
I have created several fields using the field collection module, but I cannot hide one of the field labels (within a collection). I've tried it in the UI and I've tried hiding it programmatically with `hook_form_alter`, but it continues to be displayed.

Is their a 'trick' to hiding the field labels created by this module? Thanks.

# Answer
After our discussion, these are the steps to clear the labels from a published node field collection field.

1. Head to Structure \> Field Collections \> Manage Display (For your collection) Under the label column, make sure all select boxes are set to "Hidden".
2. Next, head to Structure \> Content Types \> Your Content Type \> Manage Display (For your collection) Same as before, Under the label column, make sure all select boxes are set to "Hidden".

This wont hide the labels in the admin node/add/yourcontenttype page, but when you save the node, and look at the published page, the labels will be gone.

To remove the edit, delete and add links, Structure \> Content Types \> Your Content Type \> Manage Display and click the settings icon on your field collection field. Then simply delete the edit, delete and add text from the text fields. Click update. Then save the content type.
> 1 votes

# Answer
Inside `hook_form_alter` make `#title_display = 'invisible'.`

```
$form['your_field_name']['#title_display'] = 'invisible';

```
> 1 votes

---
Tags: entities
---


title: Making a view of simple text sentences

text:
# Question
Title: Making a view of simple text sentences
My aim is to make a view of 20 sentences. The problem is all of them sit in the same Input-field and I really have no plans to open 20 different text-fields, i.e one for each sentence...

Is there Any way I could make a grid view of these 20 sentences easily from 1 input field? Thx.

# Answer
> 1 votes
One option:

* create a content type (sentence) with only a title (sentence 1, sentence 2, etc) and body
* create 20 pieces of sentence content, each with one of the sentences you want
* create a new View, content type: sentence, page, show 20, no pager, table of fields
* add the body field to the table, and remove the title

Now download the Editable Views module:

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.

and set it up for that View of sentences.

* create your normal View of Grid, with the body field from the sentence content type and set it up however you would normally do so

With this set up, you can easily create the grid of sentences you want, plus it will create an easy way to edit those sentences (Editable Views) so that you don't need to go to 20 different pieces of content to update the field - it can all be be done from one View page

---
Tags: views
---


# Question
Title: How to theme checkout completion page in Drupal Commerce
I'm having a problem with theming the checkout completion page. My designer gave me a layout that will show all of the order details in that page(nearly same as the checkout review pane). I already googled it and all of the links that I tried is not working. Please see the links below

theming checkout pages in Drupal commerce http://theoleschool.com/blog/templating-commerce-order-completion-pane

Is there any tpl.php file that I need to include? or hooks to achieve my goal?

Thanks GUys

# Answer
> 0 votes
A quick google search yielded this result:

Templating the Commerce Order Completion Pane

> Turns out that's a fairly simple task thanks to hook\_commerce\_checkout\_pane\_info\_alter. The function passes the variable $checkout\_panes by reference which contains an array of checkout pane arrays. This function is going to allow us to redefine the function that the checkout completion pane is looking to for output.

---
Tags: theming, commerce
---


# Question
Title: Ubercart Discounts (Alternative) needs Content module
I have installed Ubercart in Drupal 7. My client needs to be able to have special pricing for members, so I added Ubercart Discounts (Alternative). I also installed CCK as a per-requisite. However, the installed module says it needs the Content module. I am not able to find this module.

# Answer
Content is the core module of CCK. You can find it under the CCK section of your module install page.
> 0 votes

---
Tags: ubercart
---


# Question
Title: Auto rendered images from external links
I'm trying to make a functionality for users, so when they add a link in a body of some article(in text editor with other text), it displays as an image. Any ideas? Thanks)

# Answer
CKeditor has the ability to add an image to a text field using its url:

> This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.
> 0 votes

---
Tags: media
---


# Question
Title: Fullcalendar is putting my events into the "all-day" category
I'm doing some stuff with fullcalendar and views that, more or less, is working. In particular, a month view properly shows a set of events on the day in which they're scheduled. However, when I switch to week or day view, the events show up in the "all day" part of the calendar.

The nodes' fields containing the dates definitely correspond to specific times. How can I get them properly showing up in the right time areas in those calendar views?

# Answer
> 0 votes
Fixed; my bad. I hadn't (properly) set the granularity of the node's time field. Duh.

---
Tags: 7, views, javascript
---


# Question
Title: A good way to import tweets, blogpost, flickr photos, slideshare,
I'm building a "social corner" on my website and I need to import quite a lot.

I've got these accounts:

* Twitter
* 2 blog
* Slideshare
* Flickr
* YouTube channel

I'm using the feeds-module at this moment, but for some reason, it got overwritten.

I tried with the Media module, but I got an error every time I tried to activate the modues, so that's not an option either.

There is a pretty good module for catching and showing tweets, but there seems none like it for YouTube posts, Slideshare, Blogs, Flickr,...

What is, in your opinion, the best way to import this kind of social media every 30 minutes or so. Because I can't think of any anymore.

# Answer
You're on the right track, but it sounds like your site may have some "too many modules" issues. If you're having modules randomly overwritten or enabling is throwing errors, it is usually time to clean up the site. If you can, start with a brand new site and **only** enable the modules you absolutely need. Keep things as basic as possible. If you want to try out other modules do it on a separate "sandbox" site that is just for testing.

There isn't going to be a single-solution for all social media. However some places to get started:
> 5 votes

# Answer
Yes, Feeds (with Feeds extensible parsers) is a very flexible option to achieve that (you should be able to import almost everything you need if you set it up properly). However, it may be a bit complex if content managers are expected to change its settings.

Social Content is far more limited (and still in beta), but provides a centralized user interface to set imports of the following networks:

* Twitter
* Instagram
* Facebook
* Tumblr
* Linkedin
* Youtube
* Flickr
* Pinterest
> 1 votes

---
Tags: 7, feeds
---


# Question
Title: I want to import my youtube videos to drupal when I upload a video in YouTube
It will sound stupid but what I want to do is I want to get YouTube videos to my drupal installation.

The challenge is one of my clients he wants to see if he can do like while he is walking and liked the video he can upload it somewhere(preferably YouTube) and it comes up in Drupal as field of node.

Is this possible in Drupal ? I am using version 7.

# Answer
> 2 votes
Social Content module allows you to automatically import Youtube videos as nodes. It provides an easy-to-use graphical user interface where you can map node fields with the fields provided by the Youtube API.

To just display Youtube videos, you could map a link field to the Youtube Embed URL, and then output it with Link iframe formatter module (for example).

# Answer
> 1 votes
I was looking into this a little myself, and while I had to put it on hold in favor of other things, I do suggest reading up on the YouTube API, which should allow you to create a new node every time you post a video on YouTube, as well as pull in the video information, which you could pass to fields in your video content type. (Obviously, you will need the Media: YouTube module.)

In short, I would think you would want to approach it something like this:

1. Set up an array in your site code to hold video info.
2. Set up a call to YouTube API, access your channel.
3. Use the API to determine the number of videos in your YouTube channel; if it is larger than the length of your array, add the most recent video to the array.
4. Step through the array and create a node for each key in the array (if it doesn't already exist).

If somebody out there knows a better method, I'd love to hear about it!

Good luck!

---
Tags: entities, files
---


# Question
Title: Redeclare issue user_has_role following upgrade from Drupal 7.34 to Drupal 7.36
Precise error is "Fatal error: Cannot redeclare user\_has\_role() (previously declared in /usr/home/adpca/public\_html/adpca.org.736/modules/user/user.module:863) in /usr/home/adpca/public\_html/adpca.org.736/modules/php/php.module(80) : eval()'d code on line 23"

This is in an eval statement I've been through through code base looking for any duplication of the function user\_has\_role and can't find any. Also been through the databases looking for anything that might trigger the duplicate eval but no joy so far. Anybody got any pointers on what to look for?

# Answer
The `user_has_role()` function has been introduced with Drupal 7.36, as stated here, and detailed here.

Following information given by the error message you received we see that:

* the function is primarily declared in *modules/user/user.module:863*: looking at the code of the *user* module confirm this, ok
* the new declaration is said to happen through *modules/php/php.module(80)*: again, looking at the code of the *php* module confirms that line 80 executes `eval('?> . $code);`, ok
* so the culpry supplemental declaration should be found at **line 23 of the PHP content** of a field which uses a format where the (not so usual) **PHP evaluator** filter has been enabled

IMO you should:

1. review all of your defined text formats, in order to select which of them have PHP evaluator filter enabled
2. from this reduced list, look for any node or block using these text formats (should not be as many)
3. then review the corresponding contents, where you'll probably find that somebody had created its own `user_has_role()` function for its needs, since it didn't exist yet before 7.36

HTH
> 2 votes

---
Tags: updating
---


title: Theme hooks vs module hooks

text:
# Question
Title: Theme hooks vs module hooks
Sometimes when I try to apply a hook, just to realise it's supposed to be in a module file.

Is there a way of knowing what hooks can be implemented in a theme's template.php file, or one in a module?

# Answer
Generally speaking, only alter hooks can be implemented by themes, which means hooks like `hook_form_alter()` and `hook_menu_alter()`, or in short all those hooks that are invoked through `drupal_alter()` in Drupal 7 and lower (`ModuleHandler()::alter()` or `ThemeManager::alter()` in Drupal 8).

Other hooks, which are invoked by `module_invoke_all()` (`ModuleHandler::invokeAll()` in Drupal 8), don't get invoked for themes simply for fact the code doesn't check if the currently enabled theme defines any hook.

```
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

```

In Drupal 8, where the `ModuleHandler` class invokes hooks implemented from modules and the `ThemeManager` class invokes hooks implemented by themes, only the first class implements `invoke()` and `invokeAll()`. This means that in Drupal 8 theme hooks aren't invoked, by Drupal core.

This is valid for Drupal core hooks, and mostly all the hooks used by contributed modules. It is then up to a module to verify a hook is implemented by a theme too, and invoke it. This is what the Views module does.

```
  // Let modules modify the view just prior to rendering it.
  foreach (module_implements('views_pre_render') as $module) {
    $function = $module . '_views_pre_render';
    $function($this);
  }

  // Let the themes play too, because pre render is a very themey thing.
  foreach ($GLOBALS['base_theme_info'] as $base) {
    $function = $base->name . '_views_pre_render';
    if (function_exists($function)) {
      $function($this);
    }
  }
  $function = $GLOBALS['theme'] . '_views_pre_render';
  if (function_exists($function)) {
    $function($this);
  }

```

For hooks used by contributed modules, you need to check the code used to invoke hooks. Chances are that, for themes, only the alter hooks are invoked; in some cases, other hooks could be implemented by themes.

Keep in mind that in the case of themes, not all the enabled themes are checked for hook implementations, contrary to what happens with modules. Only the currently used theme and the base themes are checked, as done from the Views module.
> 13 votes

---
Tags: hooks
---


# Question
Title: How to customize Number of posts on front page in drupal 8
I went to URL:

```
admin/config/system/site-information

```

I can't find **Number of posts on front page** settings available there like Drupal 7 has.

I am using drupal 8 version : `8.0.0-dev`

any help is appreciated.

# Answer
As the front page is a view now, you can find its settings under `/admin/structure/views/view/frontpage`.
> 5 votes

---
Tags: 8
---


# Question
Title: Load all field collections of a given type
Currently I am using a query to load field collections of a specified type, but I wonder if there is a more drupaly way to do it?

```
$query = db_select('field_collection_item', 'fci')
  ->fields('fci', array('field_name', 'item_id'))
  ->condition('fci.field_name', $field_collection_name)
;

$result = $query->execute()->fetchAllAssoc('item_id');
$fcs = entity_load('field_collection_item', array_keys($result));

```

# Answer
> 0 votes
Lets say you have field collection with type 'field\_my\_dates'. So you can get field collection details using node and collection type as given below.

```
<?PHP
    $itemCollection = field_get_items('node', $node, 'field_my_dates');
    $wrapper = entity_metadata_wrapper('node', $node);
?>

```

Thanks

---
Tags: entities
---


# Question
Title: Cant remove description field for new taxonomy terms
Ive created a new taxonomy vocabulary. For some reason I cant remove the description field for the terms, but I only need the title field.

Is this a bug or impossible to do or are the settings hidden somewhere strange? Thanks

# Answer
The description field is a main field. The equivalent to the body field in a node. If you dont need it you have 2 options.

1) You can just ignore it 2) You can use hook\_form\_alter to hide it for this (or all vocabularies)

There is no setting 'hide description field). If you want to hide the field from the form altogether let me know and I can explain hook\_form\_alter if you need me to. Otherwise when I don't need a description field in my taxonomy terms, i just leave it blank.

*Edit to include the hook form alter*

Information on hook\_form\_alter can be found here: http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7

This can go either in your theme's template.php or a custom module, I'm going to assume your theme, and rather than the standard hook\_form\_alter we'll use hook\_form\_FORM\_ID\_alter

```
/*
* Implementation of hook_form_FORM_ID_alter
*
* Hiding taxonomy term description field
*/

function YOUR_THEME_NAME_form_taxonomy_form_term_alter(&$form, &$form_state) {
  $form['description']['#access'] = FALSE;
}

```

Just change theme name for module name if your using a module
> 9 votes

# Answer
You can also use Display Suite and the included Display Suite forms module for this. In that case, choose a layout under "manage fields" on the term, then drag the description field into the hidden group.
> 0 votes

# Answer
I had a similar issue when using custom view modes with taxonomy terms and features.

In my case, I wanted to use the description field for input, but hide it for output on certain taxonomy view modes.

I found you can hide the description field in the vocabulary "Manage Display" page for that view mode. However, because it's not a full field API field, instead "description" is a `hook_field_extra_fields` provided term property, you also need to export the related strongarm variable for the taxonomy vocabulary to export the display settings for the "Description" field with features.

e.g, to export the settings for the topic description field, you need to export the variable:

`field_bundle_settings_taxonomy_term__topics`

It contains data such as:

```
 'extra_fields' => array(
      'display' => array(
        'description' => array(
          'default' => array(
            'weight' => '1',
            'visible' => TRUE,
          ),
          'tile' => array(
            'weight' => '1',
            'visible' => FALSE,
          ),
        ),
      ),
    )

```

Just posting here in case useful to others googling.
> 0 votes

# Answer
To continue on David's answer:

This is how you can set the visibility of the description field via code:

```
  // Shows description field in default full view mode of topics term.
  $settings_term = field_bundle_settings('taxonomy_term', 'topics');
  $settings_term['extra_fields']['display']['description']['default']['visible'] = TRUE;
  $settings_term['extra_fields']['display']['description']['default']['weight'] = -9;
  field_bundle_settings('taxonomy_term', 'topics', $settings_term);

```

This will update the variable **field\_bundle\_settings\_taxonomy\_term\__topics** that David mentions.

'default' refers to the view mode that is used in the taxonomy/term pages.

Set $settings\_term\['extra\_fields'\]\['display'\]\['description'\]\['default'\]\['visible'\] to FALSE to hide it from the output.
> 0 votes

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


# Question
Title: Get view result with sorting option programmattically
I've a view with sorting, that I need to call programmatically like,

```
$view_name = 'view_name';
$display_id = 'page';
$exposed_input = Array
(
    ['field_year_value'] =>
    ['shs_term_node_tid_depth'] => All
    ['field_federal_entity_value'] => All
    ['order'] => title
    ['sort'] => desc
);

$exposed_filters = Array
(
    ['field_year_value'] =>
    ['shs_term_node_tid_depth'] => All
    ['field_federal_entity_value'] => All
)

$view = views_get_view($view_name);
$view->exposed_input = $exposed_input;
$view->exposed_raw_input = $exposed_filters;
$view->set_display($display_id);
$view->pre_execute();
$view->execute();

```

But the result is not sorted.

Is there a way to accomplish this?

# Answer
I did it like

```
    $orderby = Array
(
    [0] => Array
        (
            [field] => node_title
            [direction] => DESC
        )

);
$view->pre_execute();
$view->query->orderby = $orderby;

```

Note: the orderby will be added after $view-\>pre\_execute();
> 0 votes

# Answer
You could check this sample code. It contains additional methods in Views that you could use like in the line:

```
//Here we can alter the order
//$view->set_item('default', 'sort', 'random', NULL);
if(isset($alter['node_created_order'])){
  $view->add_item('default', 'sort', 'node', 'created',array('order' => $alter['node_created_order']));
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Create content types containing other content-types
I've created a custom content-type called "Books."

I need to create another content type named "Catalogs" which may contain one/many "Books" as its fields.

How would I achieve that? I'd prefer some GUI tool to construct my custom content type, from admin panel, or doing some coding, if necessary.

PS: I found this question asked here but the solution did not help. Can someone provide a detailed answer, please?

**EDIT:**

MohammadAliAkbari's answer works perfectly :) One problem - When adding "Books" a user can add Books not created by him - he can add any Book to his "Catalog" - How can I add constraints such that a user can add Books only created by him to his Catalog?

**Solution:**

Using Tenken's answer, I figured out that I can write this code in my module to solve the scenario just mentioned above:

```
function myModule_form_alter(&$form, &$form_state, $form_id) {
//    dsm($form_id); // Use this line to find YOUR-DESIRED-FORM-ID
    switch ($form_id) {
        case 'YOUR-DESIRED-FORM-ID':
            $form['#validate'][] = 'stylesku_add_sku_form_validate';
//            dsm($form); // Use this to find out form's elements
            global $user;
            $currentUser = $user->uid;
            $fieldSku = $form['FIELD-ID-OF-BOOK'];
            $lang = $fieldSku['#language'];
            $fieldOptions = $fieldSku[$lang]['#options'];
            foreach($fieldOptions as $nid=>$nodeTitle){
                if(!is_int($nid))
                    continue; // Needed as the first option in select box is not really any book
                $nid = (int) $nid;
                $n = node_load($nid);
                if($n->uid != $currentUser){
                    // Remove this BOOK, this book was not created by current user
                    unset($form['FIELD-ID-OF-BOOK'][$lang]['#options'][$nid]);
                }
            }
            break;
    }
}

```

# Answer
> 3 votes
Ok, you should be familiar with

1. entity
2. view mode
3. entityreference

after install `entityreference` create a reference to `books` in your `catelogs` content-type, then go to `catelogs > manage display` and for `books reference` select `Rendered entity` formatter and in its options set something like `teaser`

after this go to `books > manage display` and configure `teaser` as you need.

also you can add more view modes by Display Suite or via simple module:

```
function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['render_in_catelogs'] = array(
      'label' => t('render in catelogs'),
      'custom settings' => FALSE,
  );
}

```

# Answer
> 2 votes
I can see 2 options to build upon @Akbari's advice ...

1. the easy way hook\_form\_alter to change the select options to be limited to entityreference node values owned by the end-user. Alter the node submit validate function to assure its one the user owns. So this attempt would just edit the $form item using FAPI tweaks ... you can use FAPI `'#element_validate'` option to set a validate function for the selected $book.
2. the really hard way ... which might work as @Akbari suggested ... you need to alter `EntityReference_SelectionHandler_Generic::buildEntityFieldQuery()` somehow. I recommend using `hook_field_info_alter()` to supply your own `$info['entityreference']['handler']` key in the field info that extends the base class with your own and overrides the buildentityinfo logic with "ownership" logic. You will probably need to make the entityreference ctools plugins aware of your custom handler (somehow) ... an example using hook\_field\_info\_alter can be found in this blog post (not mine) ...

# Answer
> 1 votes
You can use the Multifield or Field Collection module.

# Answer
> 0 votes
You can use node reference cck field. Node reference is a CCK field by which you can create some relationship between the two content types. At the time of creation a catalog you can assign book nodes to the catalog and make it multivalued so you can assign one or more book nodes to the catalog content type.

---
Tags: 7, nodes
---


# Question
Title: Clean URLs with multi-site only with suffixes / sub-folders
In D7 Multisite, I'd like to use clean URLs. However, these sites share the same domain but have different folder names.

For example, the login pages would are currently

```
https://domain.ext/red/?q=user
https://domain.ext/pink/?q=user
https://domain.ext/green/?q=user
https://domain.ext/purple/?q=user

```

How might I set this up to allow clean urls and have login pages as such:

```
https://domain.ext/red/user
https://domain.ext/pink/user
https://domain.ext/green/user
https://domain.ext/purple/user

```

The .htaccess file is untouched. The apache config file `/etc/httpd/conf.d/aliases.conf` contains:

```
Alias /blue /var/www/html
Alias /pink /var/www/html

```

And inside of `/var/www/html/sites/` I have folders

```
/var/www/html/sites/blue
/var/www/html/sites/pink

```

Can I accomplish this by editing the `$baseurl` in each settings.php file and adding a redirect per site in .htaccess?

# Answer
think you will require a separate virtualhost entry for each of the sub-sites. That should direct visitors to the correct location and negate any need for redirection.

At the moment you're using aliases to effectively send all traffic to the same place, I *think* using virtualhosts will separate the traffic a bit better and help you turn on clean URLs.

I'm going to assume your core Drupal files are at `/var/www/html`.

1. You definitely need to read the documentation in `/var/www/html/sites/sites.php` and set that up if you haven't already.
2. You do need to set the `$basepath` in each site's `settings.php`
3. In Apache it kind of depends what OS you're using but you basically want to turn on NameVirtualHost in Apache and then tell it where to send visitors:
    * Here's how to do it in Ubuntu
    * Here's how to do it in CentOS which probably also translates to RHEL/Fedora

Those links give the full setup, so you've probably already done the first few steps. Keep going down the page to find the Virtual Host section.

Finally, clean URLs need to be enabled in each of your sites, one by one.
> 4 votes

# Answer
If you'd enable clean URLs, and enable module Global Redirect, then this is one of the module's features you'd get (from its project page):

> Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.

Wouldn't that be "a" possible alternative to consider to address your question? If not, please explain why not.

PS: maybe consider changing green or purple to blue in your question?
> 1 votes

---
Tags: multi-sites, .htaccess, uri, configuration
---


title: Drupal language icon problem

text:
# Question
Title: Drupal language icon problem
I just started a new project where I aim to provide country Icons. I use two languages in my project. My default language is English, and my problem is that in some pages it works fine, but in some other pages the English language does not work. Also I have a problem as shown below in image:

So what am I to do and how can I remove the English cross text form here. I am new in Drupal.

# Answer
> 2 votes
The strikethrough effect (what you describe as 'cross text') over the language is because the specific content which you are viewing does not have content for that language in the language switch block.

The particular effect comes from the rule `.locale-untranslated` in `modules/locale/locale.css` line 2 (D7.36).

If you wish to remove it, either add content for the particular language, or add a rule as the following to your custom theme:

```
.locale-untranslated { text-decoration: none; }

```

Also for the record (I suppose you already use it) there is a module for displaying language icons.

# Answer
> 0 votes
*Sorry to "spend" an answer for what should simply be a comment: I don't have reputation enough here to comment.*

For your question "how to remove English text": this is a quite dirty way, but to achieve you may simply change the previously added rule to `.locale-untranslated { display: none; }`.

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


# Question
Title: How do I save individual fields of a field collection?
I have a problem saving fields inside a field collection. Here is what I do: I have a node and one of its fields is field collection. One of the collected fields is an audio file and the other three are description, bitrate and duration. I.e. it looks like this:

Node

* FieldCollection field
    + AudioFile collected field
    + Duration collected field
    + Bitrate collected field

I wanted my users to upload audio files on node editing and then programmatically fill bitrate and duration fields on presave using getId3 library. But it seems I can't just set bitrate and duration on presave and wait for node\_save to save them to db. Here is a piece of code that successfully sets both bitrate and duration but doesn't save anything to db.

```
require_once('sites/all/libraries/getid3/getid3/getid3.php');
function mymodule_node_presave($node)
{
    $wrapper = entity_metadata_wrapper('node', $node);

    // Initialize getID3 engine
    $getID3 = new getID3;
    foreach($wrapper->field_song_with_params as $i => $value)
    {
        //getting file info
        $mp3FileInfo = $wrapper->field_song_with_params[$i]->field_mp3->value();
        $id3_fileinfo = $getID3->analyze(drupal_realpath($mp3FileInfo['uri']));

        //setting duration and bitrate
        $wrapper->field_song_with_params[$i]->field_mp3_duration->set($id3_fileinfo['playtime_string']);
        $wrapper->field_song_with_params[$i]->field_mp3_bitrate->set($id3_fileinfo['bitrate']);
    }unset($i);

    //$wrapper->save(); Calling this results in a fatal connectivity error
}

```

So what am I doing wrong and how to set it right?

**UPDATE:** After spending about 3 days on that I figured it out. I'll provide the code here for there may be another unlucky being dealing with updating Field Collection fields automatically, but there's apparently no 'graceful' way to deal with Field Collections (or at least I don't know of such). The code is lame, be warned. But it works.

1) First we add a handler that will be called on form submit. I need a handler only on a certain type of nodes called *article\_song* that contain Field Collection fields.:

```
function mymodule_form_article_song_node_form_alter(&$form, &$form_state, $form_id)
{
    $form['#submit'][] = 'my_audio_file_properties_submit_handler';
}

```

2) Then there comes an abomination. It's heavily commented and I won't go into any details here. *field\_song\_with\_params* is the name of the Field Collection field. *field\_mp3* is a collected field that holds uploaded audio file, *field\_mp3\_duration* and *field\_mp3\_bitrate* are collected fields containing duration and bitrate respectively.

```
function my_audio_file_properties_submit_handler(&$form, &$form_state)
{
    // Initialize getID3 engine
    $getID3 = new getID3;

    // here is how audio file field collection looks like on form
    $song_field_collection_on_form = $form['field_song_with_params'][LANGUAGE_NONE];

    //for every audio file and its params do the following:
    foreach($song_field_collection_on_form as $i => $song_collected_fields)
    {
        //need to check that $i is a real index of a FieldCollection entity.
        //Something belonging to $song_field_collection_on_form is not necessarily a FieldCollection
        //there are other properties there like #theme and so on.
        if(is_array($song_collected_fields) &&
            array_key_exists('#entity_type', $song_collected_fields) &&
            $song_collected_fields['#entity_type'] == 'field_collection_item')
        {
            //Getting file id value
            $file_id = $song_collected_fields['field_mp3'][LANGUAGE_NONE][0]['fid']['#value'];

            //if it is something meaningful (yeah it can be something crazy)
            if($file_id != 0)
            {
                //load file properties from db
                $file_info = file_load($file_id);
                $id3_fileinfo = $getID3->analyze(drupal_realpath($file_info->uri));

                // here is an FieldCollection entity at $form_state that
                // needs to be updated in order to tell drupal that value
                // should persist to db.
                // Normally people use something like form_set_value
                // http://api.drupal.org/api/drupal/includes!form.inc/function/form_set_value/7
                // but to work with it a value must be somewhere in a nested array
                // and in this case a value is in a FieldCollection Entity
                // that in its turn is in a nested array
                $song_field_entity_in_form_state = $form_state
                                                    ['values']
                                                    ['field_song_with_params']
                                                    [LANGUAGE_NONE]
                                                    [$i]
                                                    ['entity'];

                //setting duration
                $song_field_entity_in_form_state->field_mp3_duration[LANGUAGE_NONE][0]['value'] = $id3_fileinfo['playtime_string'];
                //setting bitrate
                $song_field_entity_in_form_state->field_mp3_bitrate[LANGUAGE_NONE][0]['value'] = $id3_fileinfo['bitrate'];
            }
        }
    }
}

```

# Answer
A good post giving examples on deleting/creating/modifying field collection items can be found here:

http://rajanmayekar.com/blog/programmatically-creating-deleting-modifying-field-collection-item-node

I actually had to implement this myself and I did it a bit different. This is how I programmatically add field collection items on node insert/update. There's no logic on how to update the items though, with this they are just created.

```
/**
 * Implements hook_entity_insert().
 *
 * We use this hook as it's called later than node_insert().
 */
function HOOK_entity_insert($node, $type) {
  module_field_collection_stuff($node, $type);
}

/**
 * Implements hook_entity_update().
 */
function HOOK_entity_update($node, $type) {
  module_field_collection_stuff($node, $type);
}

/**
 * Do your magic
 */
function module_field_collection_stuff($node, $type) {
  if ($type != 'node' || $node->type != 'my_content_type') {
    return;
  }

  // Create a dummy node so we can update the real node without
  // triggering all the node fields hooks.
  $update = new stdClass();
  $update->nid = $node->nid;
  $update->type = $node->type;
  $update->status = $node->status;
  $update->language = $node->language;

  $values['field_name'] = 'field_collection_field';
  $values['field_item_first'][LANGUAGE_NONE][0]['value'] = 'value';
  $values['field_item_second'][LANGUAGE_NONE][0]['value'] = 'second';

  // Create new field collection item.
  $field_collection_item = entity_create('field_collection_item', $values);

  // Attach it to the  node
  $field_collection_item->setHostEntity('node', $update, LANGUAGE_NONE, true);
  // Save field-collection item, without trigger the nodes own save.
  // This is because you might want to insert multiple field collection items.
  $field_collection_item->save(TRUE);

  // Update the fields.
  field_attach_presave('node', $update);
  field_attach_update('node', $update);
}

```
> 5 votes

# Answer
I dont know if it can help you here I update my node (add anew field collection)

```
 $mynode = node_load(25);
            $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_joinedmembers'));
            $field_collection_item->setHostEntity('node', $mynode);
            $field_collection_item->field_members_name[LANGUAGE_NONE][]['uid'] = $user->uid;
            $field_collection_item->field_initiative[LANGUAGE_NONE][]['nid'] = arg(2);
            $field_collection_item->save();

```
> 0 votes

# Answer
```
  if (isset($profile->field_childrens_info[LANGUAGE_NONE][$i])) {
    // update
    $fc_item = reset(entity_load('field_collection_item', array($profile->field_childrens_info[LANGUAGE_NONE][$i]['value'])));
  }

```
> 0 votes

# Answer
The call to $wrapper-\>save() will work if you switch to user 1 first:

```
// switch to user 1 to update field_collection_item
global $user;
$original_user = $user;
$old_state = drupal_save_session(FALSE);
$user = user_load(1);

$wrapper->save();

// be sure to switch back to the original user
$user = $original_user;
drupal_save_session($old_state);

```

The user-switching code comes from a feature request on Views Bulk Operations, https://drupal.org/node/1334088#comment-5870512.

This indicates some kind of permissions problem with updating field collections, but I haven't been able to sort it out that way.
> 0 votes

# Answer
This is my contribution to answer the original question on how to update a field\_collection before it is saved (and avoid using the proposed technique on form hooks).

I had a field collection attached to a node and I wanted to update one field of the collection. This can be achieved through a call to hook\_field\_collection\_item\_presave(FieldCollectionItemEntity $field\_collection\_item).

function mymodule\_field\_collection\_item\_presave(FieldCollectionItemEntity $field\_collection\_item) { $field\_collection\_item-\>field\_addr\[LANGUAGE\_NONE\]\['0'\] = "XXX"; }
> 0 votes

# Answer
you can use below code to save/update field collection details by item id

```
<?PHP
global $user;
$field_collection_item = entity_load('field_collection_item', array($value));
$field_collection_item[$value]->field_members_name[LANGUAGE_NONE][]['uid'] = $user->uid;
$field_collection_item[$value]->field_initiative[LANGUAGE_NONE][]['nid'] = arg(2);
$field_collection_item[$value]->save();
?>

```
> 0 votes

---
Tags: 7, entities, hooks
---


title: Removing /Drupal from the URL-path

text:
# Question
Title: Removing /Drupal from the URL-path
I know this question has been asked many times for the past versions of Drupal, but none of the solutions I've found works for Drupal 7.12.

I used to have an .htaccess file placed inside the document folder alongside with Drupal, and it partially worked on older versions when entering the front- and live-page of my website (which you can now only enter via "default-URL"). For reference, you were able to to enter the live page with http://pavescorner.com/live, but after the patch and some other maintenances on my website, the link has to be like this http://pavescorner.com/drupal/live.

During those tests, when I tried to make another working .htaccess file, I accidentally destroyed the version working for me, and now you can only enter my homepage with the /drupal subdirectory.

What should I put in my .htaccess file so that /drupal doesn't appear in the URLs for my site?

# Answer
> 1 votes
Using mod\_rewrite within .htaccess, in your server's document root. Untested, but something like this should work.

```
# Enable from .htaccess
RewriteEngine On
Options +FollowSymLinks
# For all URLs not starting with drupal
RewriteCond %{REQUEST_URI} !^/drupal
# Serve the same content from the /drupal directory instead
RewriteRule ^/(.*) http://pavescorner.com/drupal/$1

```

# Answer
> 0 votes
I guess your root is changed to drupal.

Follow some steps which could help you to solve your problem.

1. go to etc/hosts file. add your sites address with the name you wanted to set it to be. (Domain name)

e.g.

```
127.0.0.1  abc.com

```
2. In httpd.conf file. add following lines which makes your drupal as root.

> ```
>  <VirtualHost yourproject.com>
>         DocumentRoot path_upto_your_project_directory/yourprojectdirectoryroot
>         ServerName yourproject.com
>     </VirtualHost>
>
> ```

hope this will solve your problem.

---
Tags: uri, .htaccess
---


# Question
Title: Views Auto-Refresh giving ajax error after some time
After creating views and implementing the views auto refresh on that it works fine for 8-10 minutes but after that giving error in alert "An AJAX HTTP request terminated abnormally.Debugging information follows.Path: /?q=views/ajaxStatusText: errorResponseText:ReadyState: 0" and stop refreshing then. why it is happening and how to resolve it?

# Answer
> 0 votes
It happened to me when views auto refresh ajax had not finished loading and I clicked on a link.

Here is a link to the drupal forum talking about this. https://www.drupal.org/node/1232416

I personally used the sandbox module in comment #183 to solve my problem.

---
Tags: views
---


# Question
Title: Creating a tag list in a view of multlingual nodes
I am creating a multilingual site in English and Swedish on Drupal 7.

I have a content type called ‘News’ which has a taxonomy term field that categorises the news posts. I have the content type set up with ‘Multilingual support’ set to ‘Enabled, with field translation’.

The views at /en/news and /sv/nyheter are working to the extent that they only show news in the users language. However, I can’t work out how to create a tag list in a block that shows the taxonomy terms for the users language. i.e. when I am at /en/news I get a block which shows only English tags, (e.g. Fundraising (4), Events (2), Membership (2)) and and when I am at /sv/nyheter I only see Swedish tags (e.g. Insamling(4), Evenemanger(2), Medlemskap(2)).

What Translation mode should I use for the taxonomy?

What settings (fields, filters, relationships, etc.) should I use in the view?

Is it possible to create a view with two paths, one of the Swedish /sv/nyheter and one for the English /en/news?

I can provide more details on how I currently have it set up if necessary, and am also up for changing how it is set up to get it working. If you can point me to examples of this working with a views export and details of how you have the taxonomy set up that would also be really handy.

Thanks!

# Answer
You should use " Translate. Different terms will be allowed for each language and they can be translated." in the vocabulary's settings.

In the view's settings, make sure that "news category" content field's "formatter" option is selected as "Link (localized)" or "plaintext (localized)".
> 0 votes

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


# Question
Title: How to add google analytics code for onclick functions in drupal 6
My requirement is that, i need to my site to be tracked when i click on categories, menus, submenus, send mail button and shopping carts. Need to add onclick function for each tags and that onclick functions need to be tracked.

# Answer
What you're looking for is the GA Event Tracking module. It allows your custom module to select web page elements (via CSS selectors), bind them to jQuery events (e.g. clicks, mouseover, etc.), and send them out to the GA Event Tracking API.
> 0 votes

---
Tags: 6, google-analytics
---


# Question
Title: Display suggested search result on search page if search result is empty
There are any way or module to display search result from suggested keyword on search page if search result is empty. just like google search, But result should come from my Apache solr system.

# Answer
The Search API Spellcheck module might be a starting point. It interfaces with the Search API Solr module.

Hope it helps,
> 1 votes

---
Tags: search
---


title: OWASP security and drupal

text:
# Question
Title: OWASP security and drupal
Recently, To improve our site security we implemented and enabled OWASP security in our server using mod\_security.

After we enabled the OWASP security, whenever I try to create or edit contents in my site after logging in as admin, It is showing it as SQL INJECTION and it does not allow to crate or edit new node.

When I edit content it redirects me to `"/node/1078/edit"` and then it shows error

```
"Error
The website encountered an unexpected error. Please try again later."

```

I also tried to find solution here but so far nothing helps. We have used `drupal database API` for all our database operations. I am not sure why OWASP is showing "SQL INJECTION".

How can I fix this?

# Answer
I don't think it has something to do with Drupal. I faced similar issue before in WordPress and it was because of mod\_security rules. Mod\_security was blocking passing parameters in URLs. The top answer in this post might help you.
> 3 votes

# Answer
It would appear that OWASP think your site is vulnerable to SQL injection. You'll need to find the exact reason yourself (it requires debugging with the site in front of you), but here are some pointers:

* Make sure your core version is \>=7.32. There was a massive SQL hole in Drupal before that update.
* Once that's confirmed, start disabling custom and contrib modules one-by-one, checking the edit form each time. If one of those is to blame, that simple process will find it. If you find a contrib module that's to blame, be sure to open a bug report on Drupal.org.
* If your Drupal core version is up to date, and none of the custom/contrib modules are responsible, you'll need to contact OWASP to ask them for their criteria, and how they've arrived at the conclusion that your site is vulnerable.
* On the off-chance they respond by pointing out another SQL injection vulnerability in Drupal core (very, very unlikely), be sure to report it to the security team. Same thing for contrib modules (more likely).
> 3 votes

---
Tags: 7, database, security
---