# Question
Title: Modify widget in Entity Reference field select box?
I am using an Entity Reference field to refer to users in another content type. The default widgets for the field use the User Name as the label for the dropdown, but I'd like to change that to another field from the user profile entity (ideally combining 'first name' and 'last name' fields). I've looked at Entity Reference Views, but it isn't released and I could not get it to work based on available docs.

# Answer
Entityrefence 7.x-1.x-dev allows you to use results from a View in the select box, which will allow you to do what you need.

* create/edit a view, add a new display of type "Entity Reference" to it, setting properly the fields you want to be shown;
* edit the entityreference field, find "entity selection mode", set it to "views: filter by an entity reference view" then select the proper "view used to select the entities" option created on previous step.
> 4 votes

# Answer
It has taken me a while to understand how to build this Entity Reference within D7. If it helps anyone, I will describe how I think it can be built here.

In my case, I am creating a Project (node entity) and relating it to a Primary Investigator PI (profile2 entity). It is a 2-way relationship, but we will be adding PI to the Project (instead of adding a Project to the Profile, at least initially). So, Project content type will contain an Entity Reference to Profile.

The least confusing way, in my opinion, is to create the view for the entity first. Add an Entity Reference display to any existing or new view (any best practice advice here?). The Format should be Entity Reference List and show Inline fields. The Filter criteria should list the type of Entity you are referring to - in my case Profile. Add more Fields that you would want to appear for the user to select from - in my case Last Name and First Name. Then go back to the Settings for Entity Reference List and add those items to the Search fields list. If desired, set up Sort Criteria for your list, which should now show up in your Preview. Save this View.

In the Project content type, add a new field referring to the PI profile \[label: prof\_ref\_pi, field type: Entity Reference, Widget: Select list (have not been able to get Autocomplete to work as of yet)\] and Save. Target type in my case is Profile. Choose Mode: Views: Filter by an entity reference view (I could not figure out how to get the Simple filter to show field values but Views does work). Select the Entity Reference display in the View you created earlier, and Save. Save your Content Type.

Go to Content and create/edit a piece of content - in my case, Project. The reference field there should have a drop-down with the View information you specified.

To use in a View, for example to show a Project and its PI, choose to create the view on a Content of Projects using Fields and add the Relationship Entity Reference - in my case, project\_ref\_pi. Then, in Fields, choose from the Projects fields and those items from the Profile fields using the relationship.
> 1 votes

---
Tags: entities
---


title: Add id to image inside views

text:
# Question
Title: Add id to image inside views
I have created a grid in views in which there are stored webshops (it's for a website on which you can find all kind of webshops). It shows a picture, a title and a bodytext for each webshop. And now I would like to edit the images only for that page in a seperate id. Only I have no idea how i should add an id for the css of the image, how is this possible in drupal, css or php?

# Answer
> 0 votes
If you add the "NID" field to your view's fields, (as the first entry, for reasons I won't get in to here), you can then use the "rewrite output" function to attach a unique CSS ID using the NID to your image.

---
Tags: views, theming, media
---


# Question
Title: Drupal registry table not populated with test class files
I tried to write tests for custom modules and I found that registry database table is not populated with .test files and thus admin/config/development/testing displays only one SimpleTest test. I tried to rebuild registry with http://drupal.org/project/registry\_rebuild but there is still no files. Is this a Drupal 7.19 bug?

# Answer
> 3 votes
Do you by any chance have the contrib 'simpletest' module installed? (as opposed to the core simpletest module that comes bundled with drupal 7)

I had the same problem you have.

What fixed it for me was uninstalling simpletest. Than completely deleting the the contrib simpletest module. Then reinstall simpletest (with the contrib module gone, this will install the core module)

And voila, my test classes started showing up in the registry and all is peachy :)

# Answer
> 0 votes
\_registry\_update() adds to the Drupal registry only the files that are referred from the module .info file, and simpletest\_test\_get\_all() looks for any class whose name is present in the registry database, and contained in a file matching the SQL pattern %.test. Those classes need to implement the method `getInfo()`, and not to depend on modules that don't exist.

If all those conditions are met, then the test class is shown in the list of the tests.

---
Tags: 7, testing
---


# Question
Title: Add a display by copying settings from another display in Views
I may be missing the obvious, but how can I add a display in a view (content pane for instance) and have it copy all the settings (fields-relationships-headers-etc) from another display in that view? (in my case a page).

# Answer
> 4 votes
If you want an exact copy of the page, you can clone the display. In Views 3 on Drupal 7, you do this by opening the view to edit it and clicking the downward-pointing triangle next to `view page` above `Advanced` and choosing `clone page`.

EDIT: Sorry, missed that. By default, Views will use all *applicable* settings data from the `Master` display (hidden by default in Drupal 7). So your content pane should inherit whatever the settings are in the `Master` display, which will be the same as those for the first display you created (the view in the first row) in that view, assuming you didn't override anything. (note that some things may not apply to content panes when moving from a page but your fields, relationships, etc. Should definitely be pulled in by default under normal circumstances.)

To make the `Master` display visible so you can see if there's something going wrong with it, you can visit `admin/structure/views/settings` and check `Always show the master display`.

It sounds like you have multiple displays and the one you want is not the master display. I don't think there's an easy way to copy settings back to the master display so your best bet is probably to make the master display visible and reset it to what you want before making more displays.

# Answer
> 3 votes
For copying overridden fields and filters into the same type of display (i.e. page and page), just use clone.

For copying overridden fields and filters into a **different** type of display (i.e. page and feed), do as @Countzero recommends above:

* Clone the page
* Export the view
* Edit the export to change the display type of the cloned item... for example, change `$handler = $view->new_display('page', 'Page', 'page_2');` to `$handler = $view->new_display('feed', 'Feed', 'feed_2');`
* Import as a new view (you may need to edit a few settings that don't jive between the two display types.)

---
Tags: 7, views
---


# Question
Title: DB API: How to add the result of an embedded query and a retrieved value
More fun with the DB API: I'm tracking the number of views of instances of a particular node type: I have a table that collects entries of the viewed node's `nid` and the timestamp of the view (which makes sense for a variety of reasons in the situation). These nodes, being regular nodes, can also have comments.

I want to retrieve a set of nodes that is ordered by the sum of the number of views and the number of comments on that node. (Don't ask why... :) The following code almost works:

```
$the_tasks = db_select('node', 'n')->range(0, 5);

    $the_tasks->condition('n.type', 'whatever');

    $the_tasks->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');

    $count_task_views = "(select count(*) as count from {vr_task_view_log} where tid = n.nid)";
    $the_tasks->addExpression($count_task_views, 'count_task_views');

    $sum_of_views_and_comments = "(count_task_views + ncs.comment_count)";
    $the_tasks->addExpression($sum_of_views_and_comments, 'sum_of_views_and_comments');

    $the_tasks->fields('n', array('nid', 'title'));
    $the_tasks->fields('ncs', array('comment_count'));

    $the_tasks->orderBy('sum_of_views_and_comments', 'desc');

$the_tasks = $the_tasks->execute();
$the_tasks = $the_tasks->fetchAll();

```

Like I said, it almost works: `sum_of_views_and_comments` is coming out as just the number of views -- the number of comments (which are getting successfully retrieved and returned as part of the query) aren't getting added in. I've also tried omitting the "ncs." qualifier from the addition statement, but that has no effect. Any advice on how to make it work?

# Answer
This was indeed a database question; a fix for the "unknown column" problem can be found at https://stackoverflow.com/questions/14879342/can-i-do-math-on-the-result-of-an-embedded-query-in-the-parent-query (short answer: the computing of `count_task_views` needs to be done in a lower-level SELECT). Back to Drupal: I have my query working as pure SQL handled through `db_query`; I should probably figure out how to do it via the API, but that's going to wait for awhile...
> 1 votes

---
Tags: 7, database
---


# Question
Title: Field in Custom Content Type Stripping out <img> tags
Drupal6: I have a custom content type, with a custom field, set to textarea. The content type's instance filter is set to Full HTML.

When I add an image tag to the custom field, the image renders in the WYSIWIG in edit mode. When I save the node, the tag doesn't show up at all. When I view source, the tag simply isn't there.

I returned immediately out of my module's hook\_nodeapi, and disabled all custom filters in the full html input format, to no avail.

If I put the same image tag in the body field of this content type, the image renders when viewing the node. Any ideas?

# Answer
A custom field doesn't have the same attributes as the standard body area.

Another approach would be to add a second field for the image and separate the two types at the content entry stage. You can combine them using Views. You could hide the first field and then rewrite the second field to display them together. A possible problem here is that the image will appear at the beginning or end of the copy -- float the image to have the text wrap around it -- but you won't have an option to place anywhere else.
> 0 votes

# Answer
1. if the image tag not printing, you may have a filter problem. try to build a custom filter to check if it works.
2. Try fetching the path directly. Do you get an image?
3. Look at your server's error logs.

However, manually fetching that URL causes your Web server to throw a 500 error (internal server error).

This is not a Drupal problem. It is a problem with your Web server configuration; check its error logs.

and as a mention:

> what kind of WYSIWIG do you use? it might be the WYSIWIG configuration, check it. also if your site is online browse to admin/settings/file-system and set your FILE SYSTEM PATH, and TEMPORARY DIRECTORY, see if it helps
> 0 votes

---
Tags: 6, media, input-formats
---


# Question
Title: How do I set the custom upload directory for a plupload from field?
My module uses a plupload form field. I'm trying to define a custom directory for my plupload uploads.

A normal upload form for a managed file looks something like this:

```
$form['managed_file'] = array(
    '#title' => t('Managed file example'),
    '#type' => 'managed_file',
    '#upload_validators' => array(
        'file_validate_extensions' => array('jpeg jpg png gif'),
        'MODULENAME_validate_not_filename' => array('test.')),
    '#upload_location' => 'public://imagebank',
    '#progress_indicator' => 'bar',
    '#progress_message' => 'One moment while we save your file...',);

```

Plupload integrations module suggests using following code to integrate an Plupload form in a custom module:

```
$form['my_element'] = array(
    '#type' => 'plupload',
    '#title' => t('Upload files'),
    '#description' => t('This multi-upload widget uses Plupload library.'),
    '#upload_validators' => array(
    'file_validate_extensions' => array(
        'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
        'my_custom_file_validator' => array('some validation criteria'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5',
        'chunk_size' => '1mb',
    ),
);

```

In a managed file form there is this parameter to set upload location uri:

```
'#upload_location' => 'public://imagebank',

```

In the plupload form I see no such parameter.

I'm still learning custom module development so the answer might be obvious, but it isn't for me atleast. Could someone please point me in the right direction? The files should be uploaded to public://imagebank

# Answer
> 3 votes
I eventualy found the solution in the plupload.module file itself. In there there is a page that can be found on folowing url: /plupload-test.

The form has a submit callback function:

```
/**
 * Submit callback for plupload_test form.
 */
function plupload_test_submit($form, &$form_state) {
  $saved_files = array();
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['pud'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      // @todo: move this to element validate or something and clean up t().
      form_set_error('pud', "Upload of {$uploaded_file['name']} failed");
    }
  }
}

```

I ended up using the same function in my custom module but adding my custom directory to the $destination the function now looks like this:

```
function plupload_files_submit($form, &$form_state) {
  $saved_files = array(); //Array to capture file objects
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  $directoryname = 'imagebank'; // Directory where images are collected
  $imagebankpath = $scheme . $directoryname;
  file_prepare_directory($imagebankpath, FILE_CREATE_DIRECTORY); // Create the folder if it doesn't exist
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['uploadfiles'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($imagebankpath .'/'. $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      form_set_error('uploadfiles', "Upload of {$uploaded_file['name']} failed");
    }
  }

```

# Answer
> 1 votes
so - upload works ?

and goes to public directory - or what ?

maybe check this thread here: http://drupal.org/node/1816438

---
Tags: 7, files
---


# Question
Title: How do I display a field that's set to "Hidden" by the content type in the template?
I have an existing site where a bunch of the fields are set to **Hidden** in the **Display fields** for the content type. I don't want to change that because I'm not 100% sure how that will affect other aspects of displaying the page.

When I do a var\_export($node, TRUE) I can see the field values are present in the node, they just aren't being rendered in $content.

Can I use hook\_nodeapi() to change the field display to "Default" or "Trimmed", etc?

# Answer
> 2 votes
$node-\>content will be a string containing the generated HTML output of the node's fields that will be displayed.

In hook\_nodeapi() the $node-\>content is already generated, but you can append the hidden field's value to it if needed, with *something* like this:

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    switch($op) {
        case 'view':
            if($node->type == "mytype") {
                $node->content .= "<div>".$node->field_myfield[0]['value']."</div>";
            }
        break;
    }
}

```

# Answer
> 0 votes
you can try `field_view_field` function on your node template for your content type:

```
 print render(field_view_field('node', $node, 'field_name'));

```

---
Tags: 6, nodes
---


# Question
Title: Add more fields to content type dynamically
I am looking for the ability to let the user who is creating the page add more fields to the node rather than the entire content type.

For example if I had a content type called Book and each content type I wanted the user to select how many authors the book had. Some books might have 5-50 authors. It does not make sense to be to create 50 fields in the content type, id rather let the user select how many author fields they will need with an "add more" button.

In my case I am using videos and the Brightcove video module that adds a custom field to my content types. I figured the process would be the same. What is the best way to create this add more experience?

# Answer
This is in core for the field types supported by the *fields* module. When you add the field to the node type, just pick `Unlimited` as the maximum number of values the user can enter for this field. Every time the user adds a field, a new one ready to be filled in will appear.
> 3 votes

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


title: Where to put formatting

text:
# Question
Title: Where to put formatting
I am building a custom module to grab data from an XML feed, however some of the data comes in badly formatted and I would like to change some of it around (for example put line breaks after certain words). Where would be the most Drupaly place to put the code that does this? In the module's .inc file? Preprocess it in template.php? Or put it in a field template file?

# Answer
> 1 votes
I would add the necessary reformatting of the badly formatted XML to the input processing of the custom module (the one you're writing).

If that is not an option (e.g. if the client insists that the XML feed is saved verbatim), then I would create a custom filter for this content. Drupal filters do not change the input - it only changes the presentation.

---
Tags: theming
---


# Question
Title: How to create a Hook_Schema for Fieldset Form?
i have a form i would like to have the values submitted into a table in mysql database using hook\_schema in a .install file. problem is i have no idea how to properly write it out being new to php and all. i basically have a custom form with over 50 total field divided up into 3 different fieldsets displayed to user depending on checkbosed clicked. what is the best way to write a hook\_schema to upload the submission values from my form into my database?

# Answer
is your schema already defined for a table in MySQL somewhere, did you already make it in like phpmyadmin? ... if so, the Schema module will show you the exact PHP needed for hook\_schema

I recommend:

* make a table in your drupal database using something like Navicat, phpmyadmin, mysql admin ... whatever. The table columns are your form field inputs and at least additionally a primary key.
* install Schema module and goto `admin/structure/schema/inspect`. Copy + Paste + Profit

```
// in yourmodule.install
function yourmodule_schema() {
  // ... paste the $schema['your_table'] textarea stuff Schema page auto-generated for you.
  return $schema;
}

```
> 2 votes

---
Tags: forms, database
---


# Question
Title: Does 'managed file' type form api support the properties #prefix and #sufix?
Does *managed file* type in drupal 7 form api work with *#prefix* and \*#sufix * properties?

```
$form['myfilefield'] = array(
            '#title' => t('Image'),
            '#type' => 'managed_file',
            '#title_display' => 'invisible',
            '#id'=>'edit-image-example-image-fid',
            '#prefix' => '<div class="myDiv">',
            '#sufix' => '</div>',
            '#default_value' => variable_get('myfilefield', ''),
            '#upload_location' => 'public://myimages/',
);

```

# Answer
> 7 votes
Yea..all though drupal 7 form api for managed\_file shows #prefix/#suffix is supported, it did not work for me either.
So I tried using `#field_prefix` and `#field_suffix` and it worked. :)
I know this is a old post but I am posting answer hoping it will help someone. :-\>

# Answer
> 5 votes
As of this posting, no it does not. `file_managed_file_process()` in `modules/file/file.module` clobbers whatever you set. See line 470:

```
// Prefix and suffix used for Ajax replacement.
$element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
$element['#suffix'] = '</div>';

```

This feels like a bug; I've posted an issue at http://drupal.org/node/1918630.

`#field_prefix` and `#field_suffix` *can* work but it depends on what you're trying to do. If you need to wrap the file\_managed in a table cell, for example, you may end up having to put it inside of an empty container to get fully outside of this element's `<div>`:

```
$array['rows'][] = array(
  'file_managed_container' => array(
    '#prefix' => '<td>',
    '#suffix' => '</td>',
    'file_managed_element' => array(
      '#type' => 'managed_file',
      ...
    ),
  ),
);

```

---
Tags: forms
---


title: testing a function

text:
# Question
Title: testing a function
I have setup a file called mymodule.test and in the module I have file called mymodule.inc. Every is working but I am unsure about the following. Below is mymodule.test file.

```
class MyModule extends DrupalWebTestCase {

  public static function getInfo() {
    return array (
      'name' => t('my module'),
      'description' => t('my module.'),
      'group' => t('My module'),
    );
  }
  public function setUp() {
    parent::setUp('mymodule');
  }
}

```

Inside mymodule.inc I have the following function

```
function mydisplay(){ returns "This is true" }

```

How I do I tell tests class I want to do an test assertion of true or false on the mydisplay function?

# Answer
You need to add a method whose names start with test, for example `testMyDisplay()`, where you test the value returned from the function.

```
public testMyDisplay() {
  module_load_include('inc', 'mymodule');
  $this->assertEqual($expected_result, mydisplay());
}

```

Clearly, this code is valid if the function is not a form builder; otherwise, the code needs to be different. Since you used `DrupalWebTestCase` as base class, and not `DrupalTestCase`, I guess you need to do more than just checking the result returned from a function, or that function is not simply a function that returns a string.
> 1 votes

---
Tags: testing
---


title: How should I implement hook_menu()?

text:
# Question
Title: How should I implement hook_menu()?
What are the fundamentals of implementing `hook_menu()`?

I would like to see the basics covered in a single question, to avoid having to answer the same similar but different questions over and over.

# Answer
This information is valid for Drupal 6 and 7. In Drupal 8, `hook_menu()` has been replaced by new routing system. Below we implement `hook_menu()` in three simple steps.

### Step one

Create an empty module following the instructions in How to create an empty module. In the code shown here, it's assumed the module is named *helloworld*.

### Step two

Add the following code to the module file.

```
/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return 'Hello world!';
}

```

### Step three

Enable the module, and visit http://example.com/hello. (Replace example.com with the domain name for your server.)
You should see the message "Hello world!". That's it! You have a fully working `hook_menu()` implementation. What follows are various more advanced topics regarding `hook_menu()`. In particular, you may want to read about permissions, as the page above will be viewable by anyone.

### Arguments

If you want to pass more data to the page callback, you can use page arguments to achieve this. Page arguments should be an array of arguments to pass on to the page callback. If an integer is used as an argument it will represent a part of the URL, starting from 0, incremented once for each slash (/). In the following example, this means the 0 will be turned into 'hello'.

```
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(0),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

```

Strings will be sent on verbatim, so `array(0, 'world')` could be used to get `hello world` out again.

```
function helloworld_page($argument1, $argument2) {
  return $argument1 . ' ' . $argument2;
}

```

"Wildcards" can be used to accept arbitrary data from the URL.

```
function helloworld_menu() {
  $items['hello/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

```

Visiting hello/world, `$argument1` will equal `world`.

### Argument autoloading

Often a URL argument will be the number identifying, for example, an entity. To avoid duplicating code that converts this ID into its corresponding object, Drupal support autoloading for "named" wildcards. When a named wildcard is used, Drupal will check for a function with the same name as the wildcard, suffixed by `_load`. If such a function is found, it will be called with the value of the value in the URL, and whatever is returned by the loader function will be passed to the page callback in place of the original value. Since Drupal already has such a function for loading nodes, `node_load()`, we can get nodes autoloaded and passed to the page callback.

```
function helloworld_menu() {
  $items['hello/%node'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid)', array('!nid' => $node->nid));
}

```

### Advanced autoloading

Sometimes, it will be necessary to auto-load more based on more than one argument. Since only the named argument is passed to the loader by default, one needs to explicitly tell Drupal which extra load arguments should be passed on to the loader. For example, to load a specific revision of a node, it is necessary to pass to `node_load()` a node ID and a revision ID. That can be accomplished by the following code.

```
function helloworld_menu() {
  $items['hello/%node/revision/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
    'load arguments' => array(3),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid, revision ID = !rid)', array('!nid' => $node->nid, '!rid' => $node->vid));
}

```

### Permissions

`'access callback' => TRUE,` is necessary to make the simple example above viewable at all, but it's hardly ideal, as it allows no control what so ever. Anyone that tries to visit /hello will be granted access. The easiest way to provide some measure of control, is to provide a access callback, much like the page callback from above. The following code still allows access to anyone, but shows how to move the logic to a function called at access time, thereby allowing more complex logic.

```
/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_access',
  );

  return $items;
}

/**
 * Access callback for /hello.
 */
function helloworld_access() {
  return TRUE;
}

```

This isn't necessarily the best way, as using a custom function will often needlessly duplicate code. A better way will be, most of the time, to use `user_access()`. Together the access callback it is possible to set access arguments. It is possible to require the page to be viewable from the users with the *access user profiles* permission with the following code.

```
/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
  );

  return $items;
}

```

Since the access callback by default is user\_access, it can be left out, as in the above code.

### More advanced topics

The official `hook_menu()` documentation provides a lot more information about the most complex use-cases for the hook.
> 153 votes

---
Tags: 7, routes
---


# Question
Title: Should store input format in the database?
When using the WYSIWYG editor, should I store not only the text but also the format ("Full HTML"/"Filtered HTML"/...) in the DB?

# Answer
> 2 votes
Yes, if you have your own form elements that are using the WYSIWYG, and are storing those results in th database, then you should also save off the input format. I did a survey of well-used modules looking into this a few weeks ago, and didn't find any that didn't do the same.

Even if you don't need it now, you will have some need in the future tho render out that input, and you will need the format to pass to check\_markup.

---
Tags: wysiwyg, input-formats
---


# Question
Title: in drupal 7, how can drupal link to another remote service, consume the data in the web service such as nodejs?
I am using the drupal 7 for my CMS server, at the same time, I have a nodejs based server, I need the drupal link to my nodejs server in order to make drupal consume the data in the nodejs based server, which will expose the restful service interface

Is there such a module that could link to the remote web service like nodejs rest, consume the data in the web service and expose the remote data as a view? and how to establish the authentication between drupal and nodejs?

# Answer
> 1 votes
You can always use the API from Node.js project. And build a module using it to consume your node.js server.

# Answer
> 0 votes
http://drupal.org/project/mongodb could be used to share it fairly simply, you could also use services see https://stackoverflow.com/questions/10428014/steps-to-make-a-mobile-application-using-drupal-as-a-back-end-or-service

Both will provide you with JSON data basically and can easily be used in node and many other Web/Mobil applications.

---
Tags: services
---


title: Search nodes and taxonomy terms

text:
# Question
Title: Search nodes and taxonomy terms
I need to implement functionality for search nodes and taxonomy terms through one search form and display results in one listing.

I try to use these modules:
1. Apache Solr
2. Search API
3. Search API Solr Search
4. Search API multi-index searches
5. Search\_api\_views

I can't make apache solr module add taxonomy terms into index. It's possible? What I do wrong? Now my apache solr index only nodes.

I configure apachesolr module https://i.stack.imgur.com/dQa01.png Also I configure Search API https://i.stack.imgur.com/BPCBK.png

Any help is appreciated

# Answer
> 1 votes
I do face similar situation and I am trying with http://drupal.org/project/apachesolr\_term module.

> This module provides basic indexing of the taxonomy terms for the multi entity branch of the Apache Solr Search Integration Module

I will post back my findings soon.

---
Tags: search
---


# Question
Title: Remove the "upload" button from the image field form element in drupal 7
As the title suggests I need to remove the upload button from an imagefield form element within D7.

I can't seem to find the element itself within the form array (via hook\_form\_alter) and I'm just wondering if it needs to be done a different way perhaps.

(I do realise the button can be hidden with CSS but I'd rather not take that option if I can help it.)

# Answer
> 3 votes
Put this code in template.php of your theme, and rename the function.

```
/**
 * Implementation theme_image_widget($variables)
 */
function THEMENAME_image_widget($vars){
  unset($vars['element']['upload_button'], $vars['element']['remove_button']);
  return theme_image_widget($vars);
}

```

---
Tags: 7, forms, media
---


title: Threaded comments pager ajaxified

text:
# Question
Title: Threaded comments pager ajaxified
I require threaded comments with pager but instead of loading a new page when pager is clicked, I want the data to be loaded via ajax. There are 2 problems I have with page load -

1. Loading a new page itself
2. I have a number of contents with there comments on a single page and clicking a pager for any comments list takes me to a new page, hence a new page for all the comments lists on the page, not only the one I had clicked.

Any help is appreciated. Thanks.

# Answer
> 2 votes
install views module and create a new view with comments as base, block as output, and the actual node as context. set it to use ajax, et voilà.

then - add this block to the content section and limit its visibilty to the corresponding content type.

to make sure the JS of views is added you have to add them manually. so in you template.php - add `function YOURTHEME_preprocess_page(&$vars, $hook) {
//Reload the javascript into the scripts. $vars['scripts'] = drupal_get_js(); }` \- may be even better to check the $vars if you're on the desired content type

---
Tags: 7, ajax, comments
---


# Question
Title: how to differ start date and end date in a table views
in D7 i have a date field with start date and end date and configured like start=now and end date=+30days. both dates are displayed well in two columns in a table views seperately. now i want a third column to dispaly like end date-start date = 30days. how? any help please.

# Answer
> 0 votes
You can add a global php field where you have the end date available as a token, you can get the current time using now and then get the difference between the 2 dates in days.

---
Tags: datetime
---


title: WHERE NOT IN using an Array

text:
# Question
Title: WHERE NOT IN using an Array
My issue here is that I would like to execute Query 1, return an array of values from Query 1, and then exclude those values from Query 2. The reason for this is I will be performing an insert function in between (and want to leave my insert function untouched).

Query 1:

```
$notquery = db_select('uc_packages', 'p')
           ->fields('p', array('package_id'))
           ->condition('p.order_id', $order_id)
           ->condition('p.sid', NULL)
           ->execute()
           ->fetchAll();

foreach($notquery as $foo) {
  $notarr->pid = $foo;
}

```

Insert function:

```
uc_shipping_package_save($package);
...

```

Query 2:

```
$query = db_select('uc_packages', 'p')
             ->fields('p', array('package_id'))
             ->condition('p.order_id', $order_id)
             ->condition('p.sid', NULL)
             ->condition('p.order_id', $notarr, 'NOT IN')
             ->execute();

```

This returns an error:

> Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute() (line 2139 of /var/www/seven/includes/database/database.inc).

It is understandable. My question is how do I pass my array through that query.

# Answer
> 1 votes
Try for the first query:

```
$notarr = db_select('uc_packages', 'p')
           ->fields('p', array('package_id'))
           ->condition('p.order_id', $order_id)
           ->condition('p.sid', NULL)
           ->execute()
           ->fetchCol();

```

That way, you'll get the array of package\_id, without needing the additional foreach, and avoid the stdClass string conversion error

Presumably also query 2 should be checking package\_id instead

# Answer
> 1 votes
The problem is with query 2:

```
$query = db_select('uc_packages', 'p')
         ->fields('p', array('package_id'))
         ->condition('p.order_id', $order_id)
         ->condition('p.sid', NULL)
         ->condition('p.order_id', $notarr, 'NOT IN')
         ->execute();

```

The variable $notarr is an object, however you need order\_id over here instead. May be you should try with

```
$notarr->order_id or something..

```

---
Tags: database
---


# Question
Title: Drupal 7 Hierarchtical Taxonomy Translations
I currently have hierarchical select installed but on the pages it's it doesnt apply basic localization. I need it to use the translations i have set up in the translation database of drupal. I have searched around google but havn't had luck finding a working solution.

Any help appriciated, thanks!

# Answer
> 0 votes
You need to enable Taxonomy translation module (Comes inbuilt with the Internationalization module).

If you are not using Internationalization module, please do make use of it to translate the taxonomy related values.

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


# Question
Title: jQuery ui embedded calendar on a drupal 7 form
I have a drupal 7 custom form written in PHP where the user can add periods of time to define his/her availability. Created periods of time are showed in a tableselect list with a button to delete them one by one. Now I want to delete this table and show the periods on a jQuery ui embedded calendar instead. How can I do that?

Given the fact drupal 7 form api has no calendar type I guess one solution would be to write a custom block in PHP where I could print the calendar. Then I could show/hide this new block when needed with Context module new rule. Do you think this solutions is good or there is a better approach?

Any suggestions would be appreaciated! Thanks!

# Answer
> 1 votes
I have already implemented my approach on a custom module and it's working fine! Here's my code:

```
function calendar_block_info() {
    $blocks['embedded_calendar'] = array(
    'info' => t('Calendar block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function calendar_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'embedded_calendar':

      //JS code based on: http://stackoverflow.com/questions/5578259/jquery-ui-datepicker-how-to-add-clickable-events-on-particular-dates

      drupal_add_css(drupal_get_path('module', 'calendar') .'/calendar.css');
      drupal_add_library('system','ui.datepicker');
      drupal_add_js('jQuery(document).ready(function() {

                      var events = [
                        { Title: "Five K for charity", Date: new Date("02/01/2013"), class: "red" },
                        { Title: "Dinner", Date: new Date("02/02/2013"), class: "green" },
                        { Title: "Meeting with manager", Date: new Date("03/01/2013"), class: "blue" }
                      ];

                      jQuery( "#embedded_calendar" ).datepicker({
                                                   numberOfMonths: 2,
                                                   regional: "es",
                                                   beforeShowDay: function(date) {
                                                      var result = [true, "", null];
                                                      var matching = jQuery.grep(events, function(event) {
                                                          return event.Date.valueOf() === date.valueOf();
                                                      });

                                                      if (matching.length) {
                                                          result = [true, matching[0].class, null];
                                                      }
                                                      return result;
                                                   },
                                                   });
                    });', 'inline');

      $block = array(
        'subject' => t(' '),
        'content' => '<div id="calendar_region">
                      <div id="embedded_calendar"></div>
                      </div>',
      );

      break;
  }
  return $block;
}

```

---
Tags: 7, datetime, javascript
---


title: Omega using wrong grid class?

text:
# Question
Title: Omega using wrong grid class?
So, I'm using Omega (with custom subtheme), and I'm running into a strange issue. I have a logo block in header first which only displays on the front page (and has grid-3 class), and I have a menu in header second which is displayed everywhere (and has grid-9 class). The front page is fine, but on every other page the region-header-second div with the menu keeps the grid-9 class, which is kind of messing with the layout. Shouldn't this automatically be set to grid-12 when the block in header first is absent? Has anyone run across this? It sort of feels like this is just 'stuck', but clear cache, etc. hasn't

# Answer
> 0 votes
Within your subtheme settings drill down to the specific region you have problems with and make sure the prefix and suffix settings are correct.

---
Tags: theming
---


# Question
Title: add arbitrary descriptions div in a node edit or add form
the need seems simple but I don't find anything about this.

I'd like to add descriptions (div class="description"), non related to specific cck fields. I though I could use these to compute informations inside it (to sum up some of the choices of tricky content types) or to show up an information when choosing a particular option (like, to show a "cck description" rather than a true cck widget when using conditionnal field).

template.php does not seems to be the right way : I got a lot of ccks, and a lot of content types, I just cant create a hook for each case I need this is not flexible enough. I suppose.

is there any 'dummy' cck field with just a description array and no widget I could use like a normal cck, and locate as any other cck in my forms ? or : how could I write a 'cck description' module (I'm ok with php and drupal module simple setup)

Im using D6.x

# Answer
> 1 votes
it sounds like you want a custom div to show for certain form values ... or on some conditional ajaxy thing on the form ...

I would basically use hook\_form\_alter with a case statement probably, or some use of nested array keys to add `#prefix` elements into the form.

The simplest example would be:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_content_type_node_add') {
    $form['field_FOO']['#prefix'] = '<div class="description">a description goes here...</div>';
  }
}

```

You said you had a million of these, all over the place ... no big deal. Somewhere in your module as a variable or tucked away in a function:

```
// A simple array lookup of $form_id => $fields => $descriptions ...
$descriptions_map = array(
  'my_content_type_node_add' => array(
    'field_FOO' => 'a description goes here ....',
     ),
    'field_ANOTHER_BAR' => '...',
  ),
  'some_other_content_type' => array ...,
);

```

Using this simple lookup table (which could help tidy up your code) ... you then make hook\_form\_alter use it by looking at the array keys and eventually setting form values ... I'm leaving out an ugly bit of code with for loops and calling like array\_keys but ...

```
$form[$field_key]['#prefix'] = $field_key_description;

```

---
Tags: 7, forms, nodes
---


# Question
Title: How to use voting results to boost relevance for solr search?
I am using search api with the solr backend to index thousands of nodes. All of them have votes (vote api). Now I am wondering how to boost the relevance of these notes by their vote. I don't want to sort the result completely by votes (this would be easy), but that the votes boost the node's relevance for a certain percentage. Is that possible? How to do this?

# Answer
Do you have the voting api results in your apache solr index? If you do and they are stored under a name ss\_votingapi, here is what you need to do:

```
/*
 * Implements hook_apachesolr_query_alter().
 */
function MYMODULE_apachesolr_query_alter($query) {
  $query->addParam('fl', 'ss_votingapi');
  $query->addParam('bf', "recip(rord(ss_votingapi),1, 1000, 1000)");
}

```

More here, here and here
> 1 votes

---
Tags: search
---


title: Mixed public/private file upload

text:
# Question
Title: Mixed public/private file upload
In Drupal 6, the Private Upload module allows you to specify that a node file attachment should be stored in the private file system, so that it is not directly accessible by URL. There is a checkbox that toggles public/private.

In Drupal 7, some of this functionality has been moved into core. When you create a File field, you specify whether it uploads into the public or private file system. However, you cannot toggle public/private on each upload.

So what would be the best way in Drupal 7 to be able to specify that some file attachments be be in the public file system, and some be private? I could create two kinds of file fields, public and private, and have each node type have both kinds of file fields. Or I could have separate (though probably otherwise identical) public and private node types, with corresponding file fields. Both ways are awkward.

Any modules that would help with this that I have missed? (I put in a core feature request for a public/private toggle in the field, but that won't help in the short term.)

# Answer
> 3 votes
What you want is to build a custom `widget` for the `file` field type, that has a checkbox that says *"this file should be private"*. Drupal 7 natively handles per-file public/private upload, so at this point it is nothing more then a UI issue.

It has been stated that Private Upload will not be ported to Drupal 7, but I think this is wrong. It should be ported and provide two features:

* An upgrade path from the custom, hackish, storage of private files in Private Upload to proper private files (this is not going to happen by magic)
* A custom widget that allows the user to choose between public and private during upload

# Answer
> 2 votes
With OG, I have created my own switch by using file\_field\_paths and entering \[node:group\_content\_access\]/\[node:nid\] as the path to store files. In my case every node published should be in an OG. Depending on the visibility of the node published, the files are put into a public or private section.

Note however, that this heavily depends on the contents of the group\_content\_access or Group Visibility field.

---
Tags: 7, files
---


title: confirn in link on overlay lists

text:
# Question
Title: confirn in link on overlay lists
I create in administration list of some content and create link delete. On link delete I add attribute

```
onclick="return confirm('Are you sure?);"

```

but when you click "cancel" on confirm block drupal still go to link href:

```
http://www.supermarket.hr/#overlay=admin/categories/delete/6939/0

```

How can I anticipate some hidden overlay functions that ignore added confirm?

thx

# Answer
> 0 votes
Some code:

```
$option_delete = array(
        'attributes' => array(
            'onclick' => "return confirm('Delete order?');",
            'class' => "delete"
        )
    );

```

link:

```
l('delete', 'admin/orders/categories/'.$node->id.'/'.$page, $option_delete),

```

this link is showing up in list on administration overlay.

---
Tags: navigation, modal-dialogs
---


title: HTML5 and Full HTML Filter

text:
# Question
Title: HTML5 and Full HTML Filter
I have the following markup:

```
<figure>
<img src="file.jpg">
<figcaption>
<h3>The Father</h3>
<p>Born in 1972, a fisherman by trade</p>
</figcapion>
</figure>

```

With the Full HTML filter:

* The "add line breaks" option adds in lots of superfluous `<br>`'s
* The "correct faulty HTML" means that adding `<p>` and `<h3>` sees the caption get chucked outside of the mangling the layout

The thing is, I like automatic line breaks and I like faulty HTML being corrected, and I don't want my content creators to have to think which filter to use, or have to add in paragraph tags because they decide to use a `<figcaption>` tag.

Is there any module/option that can make these parts of the Full HTML filter work nicely with HTML5?

# Answer
> 1 votes
I just came across the same issue, and although this is a rather old question I thought I'd give my solution in case any others find their way here.

Text formats have the option to correct 'faulty' HTML, although it's not the best choice if you'd still like to make sure that actual faulty HTML is corrected, you can turn this off by navigating to:

```
HOME > ADMINISTRATION > CONFIGURATION CONTENT AUTHORING > TEXT FORMATS > %your format%

```

Deselect 'Correct faulty and chopped off HTML' and Drupal will stop mangling section, article, figure, and other useful HTML5 tags.

---
Tags: 7, input-formats
---


# Question
Title: Do I need to build a custom page to list nodes by content type?
# Environment

* Mac OSX 10.8.2
* MAMP
* Drupal 7 (just downloaded the stable today)

# Objective

Create a menu item in the main menu to list **recent** and **all** nodes of a specific content type.

# Question

It appears that I'm going to need to build a custom page, and leverage an API, to simply list nodes by content type. I just know I'm missing something. Can somebody point me in the right direction on how to do this?

I ran this Google searche, drupal 7 list nodes of content type, to come to the conclusion that I'm going to need to build some kind of custom code.

# Answer
> 2 votes
No need to build a custom page. What you want to do is very simple to do with the *Views* module.

Just build a View to list nodes, and under `Filter criteria`, add a filter that only displays nodes of whatever content type you want to single out.

---
Tags: 7, nodes
---


# Question
Title: When creating a content type programmatically, is there a way to disable promoting to the front page by default?
In Drupal 7, I'm creating a large number (15+) of content types programmatically. There is one in particular that should never be promoted to the front page. It would be really nice if, by default, the box to do this was unchecked. I'm aware that this can be done through the front-end, but my goal is to make the web application as portable as possible. That is, other than content, I want it to be able to be moved completely and properly by only installing the correct modules.

I'm removing authoring information, for instance, by setting the variable `node_submitted_{content type name}` to `FALSE`. It would seem like there should be something like this available for promoting by default.

Thanks.

# Answer
Whether nodes of a particular content type are promoted to the front page by default is stored in the Drupal array variable `node_options_{content type name}`:

```
$node_options = variable_get('node_options_{content type name}', array());
$promote_key = array_search('promote', $node_options);
if ($promote_key !== false) {
  unset($node_options[$promote_key]);
  variable_set('node_options_{content type name}', $node_options);
}

```
> 0 votes

# Answer
BEWARE: when the `node_options_{content type name}` variable is not set a default is used that features the promote option.

so I needed to actually set the options just to 'status' that means published:

```
variable_set('node_options_drupal_projects', array('status'));

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Workflow, Multistep, and "Save" vs. "Done"
I have a Multistep node submission form with a couple of behaviors:

* The user can save it, leave, come back, and edit it further. Paging between the steps as well as clicking "save" produces this behavior. (This is already implemented)
* The user can also submit it by clicking "Done" on the last page. Currently all this does is save it the same way as the "Save" button, but it redirects to a display of the node that was just saved.
* The desired behavior for the "Done" page is to "freeze" the node and prevent further editing by the user.

I'd like to use Workflow states or at the very least a permissions-altering Rule to remove the ability to edit the node upon clicking the "Done" button, but not upon clicking the "Save," "Next," or "Previous" buttons. Currently they all do the same thing (save the node) so as far as Triggers, Rules, etc. can tell, it's the same event.

How can I differentiate which button was pressed and use that to trigger a rule or workflow state?

# Answer
> 0 votes
I forgot about this until Community poked it.

I ended up getting around this by adding a custom submit handler that calls code that adds/removes the necessary roles on the `$user` and `$node` objects. I could have also added Rules hooks but it wasn't necessary.

# Answer
> 0 votes
You could use the Button Field module and rules.

---
Tags: rules, users, workflows, forms
---


# Question
Title: Maintenance mode doesn't work on front page without www prefix
I have my site in sub directory and it works both with and without www prefix but when I place it in maintenance mode I've noticed it doesn't work for the front page without www prefix until you either try log in or go to another linked page.

Is there anyway I can fix it so it works on that front page when no www prefix?

# Answer
Add this to your .htaccess file:

```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

```

(Per this tutorial)
> 2 votes

---
Tags: maintenance-mode
---


title: Error in User Edit form

text:
# Question
Title: Error in User Edit form
Have searched a lot for this issue. I am not sure if it is a php issue or Drupal issue but the error message is pointing towards Drupal. Whenever i go to the user edit form in Drupal 7 i get the following error:

*`Notice: Undefined index: #title in user_account_form() (line 1070 of /opt/lampp/htdocs/modules/user/user.module)`*

I have searched a lot. This seemed relevant http://drupal.org/node/1088964 but it did not work out for me. Any suggestions would be appreciated.

Thanks

Edit 1: I am using 7.18 and yes i have done some changes in user registration form...i have commented the lines in bold and added a placeholder. Now when i uncomment them then no error occurs but then in my user registration form those fields show up...let me clear this through 2 images...1st image shows the case when i commented the lines(in bold) and added a placeholder (this is what i want it to look like):

However this gives me the error in user edit form. Now when i uncomment, it looks like

I do not want the labels Username and password to show up there. How can i achieve this without that error bugging me. The line number 1070 is inside user\_account\_form as well. I have realized the error is because i have commented out and it is looking for a title field or password field but then my registration form looses its appearance as i want. Is there a way round to do this.

```
function user_account_form(&$form, &$form_state) {
      global $user;

      $account = $form['#user'];
      $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

      $admin = user_access('administer users');

      $form['#validate'][] = 'user_account_form_validate';

      // Account information.
      $form['account'] = array(
        '#type'   => 'container',
        '#weight' => -10,
      );
      // Only show name field on registration form or user can change own username.
      $form['account']['name'] = array(
        '#type' => 'textfield',
        **//'#title' => t('Username'),**
        '#maxlength' => USERNAME_MAX_LENGTH,
        //'#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
        '#required' => TRUE,
        **'#attributes' => array('class' => array('username'), 'placeholder'=>t('Username')),**
        '#default_value' => (!$register ? $account->name : ''),
        '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
        '#weight' => -10,
      );

      $form['account']['mail'] = array(
        '#type' => 'textfield',
       **'#title' => t(' Email Id'),**
        '#maxlength' => EMAIL_MAX_LENGTH,
       // '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
        '#required' => TRUE,
        '#default_value' => (!$register ? $account->mail : ''),
        **'#attributes' => array('placeholder' => t ('E-mail')),**
      );

```

The lines where the error points to :

```
if (!$pass_reset) {
      $protected_values['mail'] = $form['account']['mail']['#title'];
      $protected_values['pass'] = t('Password');

```

# Answer
You shouldn't be modifying any core files. Removing a declaration for a value that needs to be used elsewhere is causing your problem, and the solution is to make your changes using hooks and templates in custom modules and themes, which are Drupal's way of allowing users to modify behavior and output.

This thread contains discussion of theming the user edit page, and has links to helpful information.
> 1 votes

---
Tags: 7, users
---


title: How to show taxonomy terms and tags?

text:
# Question
Title: How to show taxonomy terms and tags?
i have two separate contents in two different content type. The other one is in the basic page, other one is in the content type i made(regional malls). The taxonomy terms or tags is showing in basic page when i publish but my problem is in the regional malls content, when i published, taxonomy terms or tags does not show up, any ideas why is this happening?or advise how to overcome this?

# Answer
> 0 votes
Create separate .tpl for content types and then put the code to print taxonomy term

```
<?php if($node->field_category): ?>
<div class = "top_tag">
  <?php print $node->field_category['und'][0]['taxonomy_term']->name;?>
</div>
<?php endif;?>

```

put this code in template.tpl.php

```
function mytheme_preprocess_page(&$vars) { // replace mytheme with your theme name
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

hope it helps you!

---
Tags: taxonomy-terms, nodes
---


# Question
Title: When should I use Apache Solr instead of Drupal core search?
I'm in the process of migrating a medium-sized on-line magazine to Drupal.

I do not know much of Drupal's internal search engine capabilities, but I'm aware of the Apache Solr Search Integration module, which integrates the java-based search engine from Apache. Unfortunately, Solr is something new to me too.

So my questions are:

* When should I use Apache Solr instead of the Drupal core search? In what type of websites core functionality is not enough? Should I care about the performance gains of using Solr if my visitors only do hundreds of searches per day?
* Will learning how to use and integrate Apache Solr cost me lots of weeks/months?

# Answer
Learning and integrating solr could take no more than a couple days. There is ton of documentation on the API and a wealth of resources on Drupal.org.

Your use case sounds like a great candidate. Here are three good reasons I would use it on a particular site.

* You have a significant amount of searches being made from the site and *limited server resources*, Solr will increase efficiency.
* *You need specific search control beyond core*, core search really is just search content inside of nodes, It will ignore block, pane, etc. content. (There are other options that dont require non-php based environments).
* *Search is a major part of your site*. It is common that users are finding content through google and other major search engines so search is not as important as it once was. However, some sites encourage or even require the user to search the content of the site. For anything like this, I would suggest solr, in addition to the other listed items, SOLR offers more control and search power (facets and related content) and less limitations.
> 2 votes

---
Tags: search
---


# Question
Title: How to hide some administer option from all users?
I want to hide some administer options (such us: *Actions, File system, etc*) from all users, including admin (*user='1'*).

How can I do that?

Thanks

# Answer
Another, reasonably easy, option to disable access to those menu items is with

hook\_menu\_alter

and changing the access callback to `FALSE`.

You'd need the relevant URL path to add the access check to, e.g

```
/**
 * Implements hook_menu_alter
 */
function mymodule_menu_alter(&$items) {
  // Example - disable the page at admin/config/media/file-system
  $items['admin/config/media/file-system']['access callback'] = FALSE;
  // Remove unneeded access args too
  unset($items['admin/config/media/file-system']['access arguments']);
  // Example - disable the page at admin/config/system/actions
  $items['admin/config/system/actions']['access callback'] = FALSE;
  unset($items['admin/config/system/actions']['access arguments']);
}

```

See system\_menu for other relevant menu item definitions.

Clear cache at *Admin \> Config \> Performance* to apply.

P.S: As an advanced option, you could add your own 'access callback' and 'access arguments' to utilize a custom access check function.
> 3 votes

# Answer
User #1 is special. This user bypass all access control, so the only way to make sure that *no* user have access at this level is to disable user #1. However, disabling user #1 is *not* a good idea. At one point, you may need to have access to a special user account that can access *all* areas in order to fix some serious problem with your site - and in some cases, the all-powerful user #1 is the last resort.

However, you can approach this by creating a *second* admin user account (name it `lesser_admin`) and give this user account all the administration rights *except* `Administer users` and other rights you want to withhold. You then stop using user #1 as admin and instead log on as `lesser_admin` when you (or someone else) want to perform admin tasks.

To make sure, you may give user #1 as very long and impossible to remember password and write this password down and put in a sealed envelope in a bank vault. That way, neither you or anyone will have access to the user #1 account. However, when the day comes when you regret doing this, you can go to the bank vault and retrieve the envelope.
> 3 votes

---
Tags: 7
---


# Question
Title: WYSIWYG tinymce editor unwanted tags showing in drupal 7
I have css define set and themes/garland in the input for the directory but when I go to test all tags are showing.

Do I need to deselect an option in buttons to stop this or is it something else?

# Answer
> 1 votes
Sounds like a text format settings issue, review the formats at

*Admin \> Config \> Content authoring \> Text Formats*

e.g *Filtered HTML \> Limit allowed HTML tags*

and add the allowed tags if necessary.

---
Tags: wysiwyg
---


# Question
Title: Re-Indexing on Search setting, What for?
What is the function of re-index in the search setting in Drupal? And if not re-indexing, what happened? What different with run cron?

# Answer
> 1 votes
The possibility to re-index makes sense if your structure has changed or you gather information for the index in another way. For example if you want to show on a node a referenced node in another viewmode (e.g full instead of teaser). But this depends on your general setup and how you configured your content types and viewmodes.

The re-index option deletes the current search index. The "run cron" writes the new search information to the search index everytime the cron runs.

---
Tags: cron
---


title: custom form submit in a new browser tab

text:
# Question
Title: custom form submit in a new browser tab
I have a custom form in Drupal 6 and every thing works perfectly except I want the form submit to open in new window.
I tried using the following code as per form api for drupal 6 but it does not work

```
$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
          '#attributes' => array('target' => '_blank'), // this does not work
);

```

Was anyone able to achieve this? Please help!

# Answer
> 8 votes
You have to set the `target` attribute in the form tag itself:

```
$form['#attributes']['target'] = '_blank';

```

Put this code somewhere in your form function.

**Update:**

To get this functionality to a particular button, you have to be tricky.

```
$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
      '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

```

When clicked, this will set the parent form element's `target` attribute to `_blank` which opens in a new tab when pressed. If you clicked the button once and when you click some other button in the same form, it will open in a new tab as well because the previous `onclick` event set the `target` attribute to `_blank`.

To workaround, you have to set this onclick event to ALL submits.

**To submit the form in same page/tab:**

```
$form['save'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#attributes' => array('onclick' => 'this.form.target="_self";return true;'),
);

```

**To submit in a new tab:**

```
$form['save_and_print'] = array(
      '#type' => 'submit',
      '#value' => t('Save and Print'),
      '#attributes' => array('onclick' => 'this.form.target="_blank";return true;'),
);

```

demo

---
Tags: forms, 6
---


title: MariaDB vs MySQL for Drupal 6?

text:
# Question
Title: MariaDB vs MySQL for Drupal 6?
I am wondering whether it is a good idea to convert a large D6 database of a community site (with 80% read 20% write and about 1300 qps, using MyIsam engine) from Mysql to MariaDB?

MariaDB seems to be highly desirable:

> MariaDB is a database server that offers drop-in replacement functionality for MySQL. MariaDB is built by some of the original authors of MySQL, with assistance from the broader community of Free and open source software developers. In addition to the core functionality of MySQL, MariaDB offers a rich set of feature enhancements including alternate storage engines, server optimizations, and patches

However I'd like to hear first-hand experiences of fellow drupallers about the expected performance gains. I know that MariaDB uses XtraDB (InnoDB improved) storage engine by default. In fact my site slowed down significantly once I moved the Mysql database to InnoDB engine, so I am a bit unsure about the supposed performance gains.

Also I'd like to know about caveats (possible incompatible modules, etc) of converting to MariaDB.

Thanks

# Answer
> 3 votes
MariaDB is the way to go.

I just can say my anecdote.
For a long time, I have noticed that mysql is my site's bottleneck. About a week ago, on a busy D6 (+2500qps) I moved from MySQL 5.5 to MariaDB 10 after reading that MariaDB uses, among other enhancements, 'xtradb' which is highly optimized for scaling compared with innodb. Also, I saw that MySQL 5.6 which is supposed to embarace many of the same enhancements is still not available in Debian repository, (not to mention that Oracle, the new owner of mysql, has been criticized as diverting from its open source pledges). It was also reassuring that Drupal.org is also using MariaDB since 2010.

So I did the bold decision to ditch MySQL. The transition was incredibly smooth. MariaDB is a real 'drop-in replacement. I just added MariaDB 10 repositories (generated by MariaDB website) to my Debian 6 and installed MariaDB. And voila, MariaDB takes care of the rest. Nothing else needed to be changed.

Since then, I've noticed a significant improvement in the database performance with less load, and no crash due to bad queries.

# Answer
> 8 votes
CAVEAT : This commentary is solely based on MySQL not Drupal.

I have personally worked with Percona Server and MySQL, not with MariaDB as of yet. Percona provides support for MariaDB, Drizzle, Amazon RDS, and other MySQL products.

I learned at Percona Live NYC that Percona gets the latest version of MySQL and injects 30,000 lines of C/C++ that is unique to its Performance Enhancements. MySQL (eh, Oracle) tries to keep up with its own enhancements of InnoDB.

Unless your Drupal website is very heavily trafficked, there is no decent performance difference you can feel or see. However, if you do have high traffic and you want to compare MySQL, Percona, and MariaDB, I have posted an article in the DBA StackExchange on how to go about doing this.

---
Tags: database
---


# Question
Title: Allow users to annotate content in Drupal 7
Is there any way to allow users to add some private annotations when reading a book page for example ?

It seems that the annotate module is not anymore supported.

# Answer
The book Pro Drupal Development is probably the most popular book for learning how to build Drupal modules. In the 3rd edition, which covers Drupal 7, the author uses the **Annotate** module as an example of how to build a module from scratch.

If you read the first chapters of the book you could easily write the module yourself, or even better, try to port the module you mention to 7.x. By the way, remember to check Errata of the book first.
> 2 votes

---
Tags: 7
---


# Question
Title: What is the difference between context layouts and the delta module?
I was recently introduced to the Delta module and I think it is fantastic. Specifically the way it works with the Omega theme in Drupal 7. It allows me to copy the theme settings and create layouts to load in context as a response. This is great, but as I went to enable the module on my system I ran across the context layouts module and am left wondering if I shouldn't just use the context layouts module.

So I am wondering if anyone can provide some insight into this. I will go ahead and check both out here in a minute, but I think they both do almost the same thing. I guess it really just depends on what restrictions on layout the context layouts module offers along with whether or not it can let me use the settings in the theme and modify those based on a context.

This also will be interesting to see if the delta module creates files or if it puts all of this into the DB. I suspect the latter, but am concerned about the former for packaging things up into features.

# Answer
The Delta module is not an alternative to Context Layouts, you should use them together.

* **Delta** allows you to create different versions of your Omega theme with different settings/layouts each.
* **Context Layouts** is part of the **Context** module, and will allow you to switch the different layouts you previously created with Delta, when a specific 'context' is active.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to disable Commerce, but still have the module for later use?
So I have a client that needs the ability to have a store without the actual eCommerce right now. Later, the client will enable the checkout/payment features of Commerce and run it like normal. So basically:

1) Client still needs the catalog, create products, show products and pricing, etc. 2) A customer can't actually purchase anything, there is no cart, you can't checkout, etc.

Is it as easy as disabling the cart submodule? Or would hiding the add to cart buttons and requiring higher levels of auth to view /cart? I've thought of both but don't know what would be foolproof.

I know I can just create custom content types that will do the same thing as creating products, but I know in about six months or so they want to turn the ecommerce on and I don't really want to have to convert everything to products and do all the work then. I'd like to just create the products normally right now and just flip a switch later.

# Answer
> 1 votes
Drupal modules in general can be disabled and uninstalled without major problems. Last version of Drupal Commerce (1.5) includes 20 modules, and some of them are totally independent. You definitely can disable **Cart** and **Cart UI** modules without disabling others such as the **Product** and **Tax** modules.

However, there is an important bug in Drupal Commerce relevant to re-enabling modules that it's still not fixed. See http://drupal.org/node/1361562

---
Tags: commerce
---


# Question
Title: Design query for job site using subdomains
I'm designing a job site in D7. Ideally for better SEO each state or city should be in separate subdomain(this what I've learnt).

For city Paris it'd look like: paris.myjobsite.com

I'd post jobs using taxonomy categorization e.g. city,state, zip code, field, salary, qualifications.

Now I can host a new Drupal site on each sub domain so for 100 city/states it'd have 100 separate Drupal databases using multi site setup.

The other solution is to have a rewrite rule translating subdomain to site's internal url.

I'm unable to think beyond this.

I'd appreciate help as to how this design issue can be met in Drupal.

# Answer
This is what the Domain Access module was meant for: multiple sites with their own URL, running out of the same database, sharing some but not all content.

In your case, each city would be an "affiliate" site. Each subsite could have it's own theme, but they could same theme, too.

The end result is all of your subsites run out of the same Drupal installation and share the same admin.

I have only used the Drupal 6 version, but it works fairly well and integrates nicely with other modules, especially ctools, Views, and Panels.
> 0 votes

# Answer
You are looking for Purl, and would perhaps also benefit from using Spaces.
> 0 votes

---
Tags: 7, subsites
---


# Question
Title: Google analytics module vs direct code insertion in tpl file
Shall I install google analytics module or just put GA code in page.tpl file as there are too many modules and I dont want to add one more module. what do you suggest?

# Answer
> 6 votes
It is fine if you want to put the snippet in the page.tpl.php file. You will basically benefit Google Analytics module's conditional-snippet features.

If you put the snippet in page.tpl.php file,

* Admin theme will not be tracked (which is usually Seven, which is in core - *don't hack core!*)
* Users cannot opt-put for tracking (See your drupal.org account edit page for an example). this is independent from browser's **Do Not Track** (DNT) header.
* You will find it difficult to track custom variables.
* You will find it difficult to track events (downloads, etc). But you can put a modified static snippet and it should work as if it was from Google Analytics module. You can also track messages (`$messages`) using GA module.
* You will need to edit all your page.tpl.php variants to add the code.
* Other modules will not be able to control your snippet. Not compatible with js\_alters.
* You will find it difficult to track internal search.
* All users, including admin roles, which is usually not necessary to track.
* Cache the code locally.

In my opinion (and some little home-done tests), caching the code locally is not a good idea. GA service is so popular so the chance of having a locally cached version of ga.js is very good. If you cache it, browser will have to download the same code from your server (But you can track users those who have blocked ga.js using AdBlock plugins).

For sites that I maintain in long run, I'm fine to use the snippet directly (in page.tpl.php or html.tpl.php). Many sites don't require A/B testing, goal tracking, custom variables and other bells and whistles. If you explicitly call `node_load()` , `user_load()`, `user_access()`, or other functions, that's a signal that you might want to use GA module instead of the in-house coding.

# Answer
> 0 votes
It is fine to not use the module, but the right way to do this is to put the tracking code in a js file and use drupal\_add\_js() or even better, drupal\_add\_library(). This way the code can be cached and is not reloaded on each page.

# Answer
> 0 votes
When making this decision, it might be a good idea to review http://drupal.org/node/1788586 and http://productforums.google.com/forum/#!category-topic/analytics/report-bugs/djSplZp1Crg , as the google\_analytics module cannot put the js in the (odd) location that Google requires it. This is a limitation of drupal\_add\_js, so it won't really help you to write your own version of the ga module with your own call to drupal\_add\_js. Note that a workaround exists in ga; if you put the code at the very end of the page (Google's old location), then Google will pick it up. Before I discovered this workaround, I just pasted the required Javascript into my theme template file, and that has been working pretty well for me.

---
Tags: 7, google-analytics
---


# Question
Title: What are differences/advantages of Invite vs. Referral modules?
Are there any distinct advantages for choosing either the Invite or Referral modules for the purpose of allowing existing site users to get their friends to check out the site and create an account?

I'm trying to determine which module will be the best solution for us, but they seem like they essentially do the same thing. Am I wrong?

We'll want to be able to award points for successful sign ups, and maybe some other type or rules integration to reward those who get more people to sign up.

# Answer
> 3 votes
Invite module is more popular and is a more active project. The last commit was 4 weeks ago, while User Referral git repository has been inactive for more than 1 year. Considering that the last version of User Referral is still in beta, I would check Invite first.

Back in 2007, there was an idea of merging the two into Invite, but apparently did not happen.

You can see some differences between them discussed in the previous link. Some of them are:

* Invite sends a coded registration link by e-mail whereas User Referral displays it.
* Referral's tracking uses a session variable to store referral information. Invite's tracking code is lost if the user moves away from the registration page.
* Invite codes are always unique and can be used only once.
* Invite codes have an expiry date.
* User Referral display a referral link (such as referral/123) in the user's page.

They also seem to provide integrations with different modules.

---
Tags: 7
---


# Question
Title: Override default profile view with profile2's profile fields
I have made 2 profile 'A' and 'B' with profile2. Profiles are searchable by all users including 'anonymous' user type.

A user search for user named 'a' then search result appears. When I click on that result, it shows default user profile view (Only History: Member for) not the profile2 fields associated with user 'a'.

As I want to show profile2 field in search not the just default one. Please help in this regard.

# Answer
> 1 votes
I thought Profile2 had an option to override that.

Maybe you could use Global Redirect or Path Redirect to redirect users visiting the account page to the profile page.

Another option could be creating a view for the searches, and then adding the user/profile relationship.

---
Tags: users
---


# Question
Title: User information based on external database
In one of the community portal based on Drupal,

Now, there is a rich user information which is also used by external applications. This information can be LDAP, MySQL or any other different database per say. (the choice here is still open).

Now, we are also considering using Profile2 for rich user information, for authentication as well as and also for various social features.

So essentially, there are two different Applications (Drupal and External) that need to access the same data and both might need to read/modify the information. (we can be safe here in terms of simultaneous access because traffic will be very minimal.)

So what should be the right approach ? Should Drupal look up to the external database or should the external application directly modify Drupal's own database? Or should there be some sort of DB to DB sync?

Is any of the approach possible and if so, how can this be achieved?

Please note: this approach requirement is only for User specific information not any general purpose other content in Drupal.

# Answer
Personally, I would fetch and update the fields on Drupal when the user logins, and update the remote database when the user in Drupal is updated. If you user Profile2 you might have to use other hooks.

An other option may be running a script outside Drupal to synchronize the two databases.
> 1 votes

---
Tags: users, database
---


title: Content sharing issue

text:
# Question
Title: Content sharing issue
My site allows users to create content and share them with their friends. The relationships are created using UR module. The content type itself has a "Share:",a User Reference field, where the user can select multiple users, from their list of friends. Then there is a view, in which users can see the content created by others and shared with them. The problem is that, well, they cant see it, i cant get my head around the filter. What would be the easiest way to filter this? I've come up with this: if the currently logged in users name is in the contents share field, the data is shown. How to implement this in the view? Any help would be greatly appreciated!

# Answer
You want a Relationship on your View.

If you're displaying nodes, add a Relationship on the User Reference field that your node has. Then add a Filter for User = Current User, using the relationship you just created.
> 0 votes

---
Tags: nodes, views
---


# Question
Title: How to append #rss to each RSS feed item's URL built with Views?
## Problem

**I have an RSS feed built with Views on a Drupal 7 installation. I want to append the following string to each feed item's URL but don't know how: "#rss"**

For example, let's assume my RSS has a feed item linking to a blog post

http://www.example.com/blog/post.html

I would like to add the hashtag to the end of it, so I get

http://www.example.com/blog/post.html#rss

## Why?

*This hash tag will allow me to see who is visiting the site from my RSS feed* as it'll appear on my Analytics program.

I could use Feedburner or other 3rd party feed tracking alternatives, but I am purposefully staying away from them, for reasons we don't need to go into.

Anyhoo, I only managed to get the Views RSS to work recently and have no idea how to modify the feed item URL. Can anyone help? Please assume I am a novice at this.

# Answer
> 0 votes
In the RSS view, look at the format section. If you're like me, you'll have the following

**Format:** RSS feed
**Show:** Content

1. **Make sure to switch "Content" to "Fields"**, otherwise you won't ever see the "rewrite" options that the commentators keep mentioning above. Add all the necessary fields you'll need for the RSS feed. You should get something like this (Ignore the field Hardcoded...)
2. Now, click on the "Content:Path" field (which you should've added), expand the "Rewrite Results" section, and **tick the "Rewrite the output of this field" checkbox**.
3. **In the provided textbox, add your custom URL parameter.** In my case, I wanted a hashtag, so I added the following:

```
[path]#rss

```
4. **And, you're done!** You may be asking, how did you know what to put in that textbox? Scroll down a bit and expand the "Replacement Patterns" section. You can add all types of stuff. I found this post useful. Of course, I discovered it after I had solved the problem. Still good to know.

Feels good solving my own problem, though special thanks to Remi who pointed me in the right direction.

It *seems* pretty obvious after the fact and maybe that's why no one wanted to actually write out an answer but for beginners like me, it's obscure. Anyway, I wrote this out in detail in the hopes you won't get stuck here. Hope it helps :)

---
Tags: views, feeds
---


# Question
Title: Product Variation as Thumbnail rather than Dropdown
I am wondering if someone has tackled having product variations as thumbnails rather than a dropdown option.

Have a look at this page: http://www.partytimerentals.com/catalog/product/basic-poly-rounds

You see that I have loads of variations for that particular table linen, but my end user has to look through a load of item options. I need a way to show them the associated swatch, and when they click load that variation. The same as now, just as I said, an image thumbnail rather than a select box.

Any direction on this would be greatly appreciated. Thanks.

Here is a mockup of what I am looking for: http://cloud.um-me.com/0f1a2p1b1T0A

Aaron

# Answer
I ended up writing a custom to module to handle this. I did a db\_query to pull the attributes and thumbnails, and used jQuery to change the select menu upon clicking the image.
> 1 votes

# Answer
Once i've got the same problem and I went through this issue Here there are different solution and suggestion.

I was looking for a module who shows the color instead of text so I have chosen this module Fancy Attribute . You can create a taxonomy with a field color and add the hex code of the color, then you can use it as a variation.
> 3 votes

---
Tags: commerce
---


# Question
Title: anonymous voting using poll module invalidates cache
I am not sure if this is a common problem. I use drupal 7 site with caching enabled. One of my pages is a simple poll. After anonymous voting, all cached pages are invalidated for current user. The cached pages remain in database so after clearing browser cache, current user sees cached pages again. Does poll use some sort of cookie that invalidates cache? How can I avoid such behavior? Thank you

# Answer
> 2 votes
After hours of testing, it looks like the Advanced Poll module does the job. Here is an excerpt about it from the module's project page:

> ... a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.
>
> * Voting systems: Basic polls, Approval Voting, Borda Count, and Instant-Runoff Voting.
> * Vote management: view each user's vote, delete all votes, or restrict the poll to a list of users.
> * Time management: schedule when to open or close the poll, and choose when to show results.
> * Choice management: write-in choices, and support for HTML (or other input filter).
> * Usability: fast Ajax interaction and customizable default settings.
> * Migration: convert regular Drupal polls into Advanced Polls.

# Answer
> 0 votes
Pages with functionality that need to change or request information from the database, in general can not be cached. Something like the Ajax Blocks module or a custom solution can help work around this. Here is an excerpt about it from that module's project page:

> Permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user. It is suitable for sites which are mostly static, and the page caching for anonymous users is a great benefit, but there are some pieces of information that have to be dynamic.

---
Tags: 7, caching, polls
---


# Question
Title: book module navigation horizontal submenu
I am using the book module navigation block to display links to book pages. I was wondering if it was possible to alter it so rather than the children links appearing below the parent, they would appear to the side. This is because I want a horizontal navigation

Thanks

EDIT: For anyone wondering, the way to get book links to appear on the same level, you just need to make sure the child pages are pointing to the same parent, then just display that level of links to get a nav bar, styled this gives you a horizontal nav bar.

# Answer
> 1 votes
You can override **node.tpl.php** and customize where to render `$content['book_navigation']`.

Have also look at book-navigation.tpl.php and template\_preprocess\_book\_navigation().

---
Tags: routes, nodes
---


# Question
Title: How do I add a thumbnail to the teaser of a blog post containing an image?
I am using Drupal 7 and have added an image field to the blog content type. The image comes in fine when creating the blog post, but when viewing the teaser of the blog entry in the list of user's blogs, there is no thumbnail in the teaser showing that there is an attached image. Is this possible to have? How do I do it?

# Answer
> 4 votes
Go to display settings for your content type ('blog post'), and then select teaser ex.:

/admin/structure/types/manage/article/display/teaser

From here you can control which fields will display in your teaser (or full, or other defined formats). Your image field is most likely hidden for your teaser, you'll want to have it displayed and style accordingly.

---
Tags: nodes
---


# Question
Title: No wysiwyg filter present in text format
I keep reading you select the wysiwyg filter in configuration-\>content authoring-\> text formats but it doesn't exist for me.

How can I get that filter to appear in list?

I have the wysiwyg module correctly installed and enabled.

# Answer
> 2 votes
I recommend you to do the following:

* first add new text format from `admin/config/content/formats`
* then check the correct options for your new custom text format
* now go to wysiwyg configuration page `admin/config/content/wysiwyg`
* you should see your new custom text format along with dropdown list to choose TinyMCE editor
* make sure to select TinyMCE editor and click save

Note: in order for you to see/select different text format you need to have more than one text format (other than Plain text)

---
Tags: wysiwyg
---


title: Calendar & subscriptions modules

text:
# Question
Title: Calendar & subscriptions modules
Is it possible for anonymos users to subscribe to calendar events created using the Calendar module? If so, how would I go about achieving this?

# Answer
> 0 votes
Yes its possible for anonymos users to subscribe to calendar events created using the Calendar module.

---
Tags: datetime, notifications
---


# Question
Title: How to create a collapsible Webform form?
I'd like to make a webform collapsed by default, and have a Sentence/paragraph at top of the page with a checkbox next to it. Upon ticking the checkbox I would like the webform to be displayed.

Similar to Form 2 - Adding Fieldsets on this site: http://dev.sencha.com/deploy/ext-4.0.0/examples/form/dynamic.html

How would I go about doing this?

# Answer
Okay, the easy way would be to go through FORMS API http://drupal.org/node/37775

You may also look into MultiStep module once you are done with the FORM API overview.

Below are some links that you can follow:-

1. http://www.youtube.com/watch?v=EgGhUN2zKw4
2. http://randyfay.com/states
3. Search youtube/drupalize.me/buildamodule.com for more Form API tutorials.
4. http://tedbow.com/content/drupal/webform-conditional-demo-form

Please go through Form Api first.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Gallery Formatter Adjusting the Width of Gallery-Thumbs
I am using a Gallery Formatter on my site. The thumbnails are appearing below the main image, the size of thumbs-gallery is exactly the same size as gallery-slides. I actually want thumbs-gallery to appear from one corner of the window to the other. My div which contains this Gallery formatter gallery has 100% width of the document, So I gave the thumbs-gallery the width 100% which does what I want but when I am clicking the arrow to scroll the thumbs it at the end of the thumbs gives a large blank space, on clicking again it starts fine from the start.

Please suggest how to achieve my desired result.

Following is the link of my page on which I am getting problem, just click the arrow to scroll twice to see the problem

http://zgphotographydubai.com/content/industrial

# Answer
I was looking for a way to make thumbnails to appear from left edge of the document to the right edge for this I tried to make some CSS tweaks but that do 1 thing right and 2nd thing wrong. So I have tried Galleria Module from its configuration settings I select the width Auto. It did the trick for me. There are several other configuration options available in galleria module which are not available in gallery formatters.
> 0 votes

# Answer
make shure the empty li's have no width specified (or are now shown at all). change

```
<li class="empty" style="width: 121px;"/>

```

to

```
 <li class="empty"/>

```

if you cannot manage that - do it via css

```
.gallery-thumbs li.empty { width: 0px !important; }

```
> 0 votes

---
Tags: javascript, media
---


# Question
Title: restrict user access to sub domain if assigned to another sub domain
I have a site using the domain access module. I created 2 sub domains. agent1.example.com for agent1 and agent2.example.com for agent2. However, I can login to agent1.example.com with agent2 login info. I only want agent1 to login to agent1.example.com and agent2 to only be able to login to agent2.example.com.

The reason why I am using domain access instead of multi site is because I am sharing training videos, documents, and corporate documents across all sites. However, each agent will have their own page where they can track clients and sales statistics, so I want only them to see it.

What is the best way to go about this, or is there a better module for this? Or is there a way to share content across multi-site domains?

Thanks, cquigs

# Answer
> 2 votes
the Domain Bonus module can help you solve this problem.

> The Domain Bonus is group of modules that extend functionality of Domain Access module.

check the "Domain Bonus: Login restrict" sub module

---
Tags: users
---


# Question
Title: Views pager not rendered for teasers with comments
I have a views which displays teasers. Pager is also set.

When comments in teasers is enabled pager doesn't show up, however it does when comments are turned off.

I cannot figure out what the issue might be, please anybody any clue to this?

Thanks.

# Answer
> 2 votes
Have you tried to give your pager another "Pager ID" (in the pager options on the view). Try to enter a number bigger than 0.

---
Tags: 7, views, comments, paging
---


# Question
Title: Custom theme css separate from editor css
I have a custom css file in my custom theme folder which has a few changes I made throughout site but does not affect the tinymce editor but probably overrides it making so no changes in text.

I have two problems, one I don't actually know what to put in separate custom css to make buttons work in tinymce editor. I am used to finding a specific div or creating one and then adding the css. I am not familiar with setting up classes for this editor (as it offers in wysiwyg profiles) and correct syntax to do so. Also I would have thought I needed to bring over a generic copy of the css for the editor into my custom theme folder (?) And two I am unclear on how to set the path in define css for the editor profile, if ever I manage to create of find the correct file.

I hope I am making some sense and my question is clear enough.

# Answer
First, let me add that the answer that I am about to give is the way I would handle it. This could be done in many ways.

Create a separate stylesheet for your text styling (we usually call it `style-type.css`) and place it somewhere appropriate in your theme (for example `/sites/all/themes/your_theme/css/style-type.css`), also use this file for your front-end. Only add styling in this stylesheet for **textual styling**, so for `h1`, `h2`, `strong`, `em`, etc...

Then use the `admin/config/content/wysiwyg` admin page to define the CSS in the appropriate format. We mostly don't use the replacement patterns (like %b) and simply fill in the path relative to your Drupal install (of course, the patterns could be applicable in your case): `/sites/all/themes/your_theme/css/style-type.css`. Make sure `Define CSS` is the active option above the path.

If you need extra styling for stuff like highlighted text, simply make sure you have that styling in your `style-type.css`. For example `.highlighted { color: yellow; }`. And then define it in the `CSS Class` textarea as follows:

```
Highlighted=highlighted

```

Then also make sure you've got the plugin `Styles` enabled. This will give you a dropdown list on the WYSIWYG editor which allows you to add styling that you defined to texts.
> 2 votes

---
Tags: theming, uri
---


# Question
Title: What better way to add new features on a project already in production?
We know that drupal is based on nodes.

I feel it difficult to make updates to a project already in production.

Currently I have two environments. A testing, and other production. I make changes in the test environment, then I redo the production environment.

Is there any way I can do packages with content types, views, and maybe even taxonomy nodes, and import them into production?

Thank you.

# Answer
I think you are looking for what KiamLalluno is answered in the comments. I would just like to supply it by saying These module have been helpfull for me when I was in your situation

Deploy Module

GO live checklist

Drush

Feeds Module

Features Module

Enviroment Indicator

Hope it helps
> 2 votes

---
Tags: migrations, importing-exporting, backups
---