title: file_save_upload validate file size

text:
# Question
Title: file_save_upload validate file size
I have a simple Drupal 8 form where users can upload a picture.

The issue is that the `upload_max_filesize` is set to 2M on the server. So if I upload a bigger file, the form submission fails:

> Fatal error: Call to a member function save() on a non-object

Here is what I have tried in the submitForm:

```
$validators = array(
  'file_validate_is_image' => array(),
  'file_validate_size' => array(1024 * 1024),
);

/** @var File[] $pictures */
$pictures = file_save_upload('picture_upload', $validators, 'public://');
if(null !== $pictures) {
    /** @var File $picture */
    $picture = reset($pictures);
    $picture->save();
}

```

This actually leads to 2 issues when trying to upload a large `.jpg` image:

1. The file could not be saved because it exceeds 2 MB, the maximum allowed size for uploads.
2. Image type not supported. Allowed types: png jpeg gif

So my questions are: why does the validator not accept a .jpg image? How would I go about avoiding the fatal error and return to the form if the file size is too big?

**Edit:**

I have changed my validator to this now:

```
$validators = array(
  'file_validate_extensions' => array('gif png jpg jpeg'),
  'file_validate_size' => array(2 * 1024 * 1024), // 2MB file size limit
);

```

It works now in the way that it accepts my `.jpg` image and doesn't accept files larger than 2MB. **But** how would I go about returning to the form with an error message instead of going straight to the PHP fatal error?

# Answer
The return value from `file_save_upload()` is:

> array Function returns array of files or a single file object if $delta != NULL. Each file object contains the file information if the upload succeeded or FALSE in the event of an error. Function returns NULL if no file was uploaded.

So you can handle it a few different ways.

```
$picture = reset($pictures);
if ($picture === FALSE) {
  $form_state->setErrorByName('field_name', $this->t('Error!'));
}

```

or

```
$picture = reset($pictures);
if (!$picture instanceof \Drupal\file\Entity\File) {
  $form_state->setErrorByName('field_name', $this->t('Error!'));
}

```

are the first that come to mind.

This code will need to be in a validate method rather than a submit method, so that you're setting errors in the right place. You can leave the -\>save() logic in the submit method, safe in the knowledge that the file has been validated and exists before that code is executed.
> 3 votes

---
Tags: 8, media
---


title: Create pager from db_query

text:
# Question
Title: Create pager from db_query
This my SQL query to fetch the details.

```
$query = "SELECT DISTINCT TITLE, PID, TYPE, SUM(DAYCOUNT) AS tot, ROUND(SUM(DAYCOUNT)/(
        SELECT SUM(DAYCOUNT) FROM REPORT_LIST_VIEW), 4) AS per
        FROM REPORT_LIST_VIEW
        WHERE DAYCOUNT > '0'
        GROUP BY TITLE, PID, TYPE
        ORDER BY TITLE ASC";
        $res = db_query($query);

```

I am displaying out put like this

```
foreach ($res as $row) {
$i++; ?>
<li>
<a href="/page-file-views-user?id=<?php echo $row->pid ;?>&type=<?php echo $row->type; ?>" >
<ul class="inner-ul">
<li class="name"><?php echo ucfirst($row->title); ?></li>
<li class="percentage">
<ul>
<li><?php echo $row->per * 100; ?>%</li>
<li><?php echo $row->tot; ?></li>
</ul>
</li>
</ul>
</a>
</li>
<?php $sum+= $row->tot; } ?>

```

How can I add a pagination (mini pager) at top & bottom of the result?

`<?php
function pager_array_splice($data, $limit = 9, $element = 0) {
global $pager_page_array, $pager_total, $pager_total_items;
 $page = isset($_GET['page']) ? $_GET['page'] : '';
 // Convert comma-separated $page to an array, used by other functions.
 $pager_page_array = explode(',', $page); // outs puts empty array
 // We calculate the total of pages as ceil(items / limit).
 $pager_total_items[$element] = count($data); // output 1
 $pager_total[$element] = ceil($pager_total_items[$element] / $limit); // output 1
 $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1)); // no output
 return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}
?>`

And in my pagination div

`$output = '';
$customArr = pager_array_splice($data, 1);
$output .= theme('views_mini_pager', array('quantity' => 1));
print $output;`

But no result is printing. Any error in my logic.

# Answer
You want to take advantage of the PagerDefault class.

Write your query as a db\_select query which I'll leave as an exercise for the reader because, frankly, I'm not sure if it's possible to create a db\_select query with a subquery as part of an expression like that :). Assuming you build up your select query in a variable called $query, you'd have code along these lines:

```
$query = db_select('REPORT_LIST_VIEW')->extend('PagerDefault');
...build up $query object here...
$res = $query->execute();

$pager = drupal_render(array('#theme' => 'pager'));

```

Then just output $pager wherever you want it.

Also, in general, I'd recommend placing this in a block rather than hard-coding it into your theme so that it's more reusable.
> 1 votes

---
Tags: 7, theming, paging
---


title: image_style_url doesn't create images

text:
# Question
Title: image_style_url doesn't create images
I am using image\_style\_url to get a thumbnail of a picture I added through the administrator interface.

```
// $foo->field_picture['und'][0]['uri'] has value public://foo.jpg
image_style_url('foo-thumb', $foo->field_picture['und'][0]['uri']);

```

The API states that the image will be created when the URL is requested. However, when visiting the page the image isn't displayed (404). The URL returned from the function seems to be well formed, but the file hasen't been created.

The 'foo-thumb' folder is in the public data folder and the file permissions should be OK. I tried flushing the image cache (drupal image-flush foo-thumb) but still no results.

Any ideas?

# Answer
From: https://drupal.org/drupal-7.20-release-notes

> In addition, any code which programmatically generates a link to an image derivative without using the standard image\_style\_url() API function will no longer work correctly if the image does not already exist in the file system, since the necessary token will not be present in the URL.

Instead you can do something like this;

```
$image_uri      = $node->field_image[LANGUAGE_NONE][0]['uri']; // or any public://my_image
$style          = 'my_style';
$derivative_uri = image_style_url($style, $image_uri);
$success        = file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);

$new_image_url  = file_create_url($derivative_uri);

```
> 23 votes

# Answer
One common mistake is that URIs are not properly formatted. Check that your URI parameter is prefixed with `public://`.

# Bad Practice

```
$imageUrl = image_style_url('style_name', 'myimage.jpg');
$imageUrl = image_style_url('style_name', $node->field_x[$node->language][0]['filename']);

```

This outputs a URL to the styled image (with image token), but does not generate a styled image when it hasn't been previously generated.

---

# Good Practice

```
$imageUrl = image_style_url('style_name', file_build_uri('myimage.jpg')); // changes to 'public://myimage.jpg'
$imageUrl = image_style_url('style_name', $node->field_x[$node->language][0]['uri']);

```

This outputs a styled URL, like the above, and generates a styled image if none exists.
> 7 votes

# Answer
The public file system path was wrong.
> 1 votes

# Answer
Another option is to use the theme function.

```
$img = theme('image_style', array('style_name' => 'your_image_style_machine_name', 'path' => $node->field_image['und'][0]['uri']));

```

Rather than returning the URL it will return the html for the img.
> 1 votes

# Answer
```
$fid = file_load($field_yuorfield_fid);
$image_uri = image_style_url('yuor_style', $fid->uri);
fopen($image_uri, 'r');

```

here can use url for create html
> 1 votes

# Answer
Make sure you have `foo-thumb` style, you can check at `admin/config/media/image-styles`.

The first parameters of image\_style\_url is a **style name**, not a **folder** name.
> 0 votes

# Answer
If you receive a 404 when trying to view the image, a possibility is that the image style name is not correct. In my case, the style name that showed up in Image Styles was not the machine name of the style name. When hovering over the style the url will display the machine name of the style name. Either change it to the machine name or delete the current and recreate with the name needed.
> 0 votes

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


# Question
Title: Should I use contextual filters to limit the view results for each type of administrators?
I'm trying to display the View according to the current director, example:

* I have a content type called **faculty news**,and I have two faculties: **Medicine** and **Sciences**, the content type faculty news is all news of medicine and Sciences.
* I have two administrators: **admin-medicine** and **admin-sciences**, each one has permissions to publish, read and write only in his faculty.
* I have the **View**: **Administrator faculty news** with the path http://example.com/administrator-faculty-news

This view display nodes from content type **faculty news**.

Now I want to enhance this view like so: when the admin-sciences administrator uses the path http://example.com/administrator-faculty-news, then only the news of the Sciences faculty should be shown in the Views results, and the same for admin-medicine (only show the news of the Medicine faculty).

With contextual filter? How can I do that?

**Note**: Medicine and Sciences is implemented using taxonomy.

# Answer
# Contextual filters

I suggest you review the (free) video about Contextual filters with paths. It covers topics such as:

* Using contextual filters for filtering Views result.
* Using input from the view path to set contextual filter values.
* Using contextual filter values for changing the view title.

If you like its content, you may also want to watch about 5 subsequent videos, also related to contextual filters (sometimes called "arguments" also).

# Content Access

Even though your question is specific to Views, it seems like you should give it a thought to also get the Content Access module involved in your setup. Here is a quote from its project page:

> This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Just use this module to give appropriate access to each of the groups of users for each of the content types you have. After you do, the view you currently already have will probably not need any (or just a few) refinements. Because Content Access (if configured correctly) will make sure that the view results only include the news from each faculty.

**Bonus**: you'll find other use-cases for this module soon!

# Organic Groups

Organic Groups is possibly an alternative also, which provides 'Groups' for Drupal users, and management of Access Control based on these groups.

In your case, each faculty would probably correspond to 1 such "group". And similar to using Content Access, the view you currently already have will probably not need any (or just a few) refinements.

**Bonus**: you'll find other use-cases for this module soon!
> 1 votes

---
Tags: 7, views, users, tokens
---


# Question
Title: Calendar Prev/Next buttons linking to wrong dates
In the calendar month display for August with the path `calendar/2015-08`, the forward and next page buttons offer the user a link to October -- completely jumping over September straight to October.

That is, the Next link in the above picture jumps straight to `calendar/2015-10`.

I'm at a loss. I've tried cycling Ajax in the view which did nothing.

I'm running the following modules:

```
$ drush pml | grep calendar
 Date/Time  Calendar (calendar)               Module  Enabled        7.x-3.5
 FullCalen  FullCalendar (fullcalendar)       Module  Enabled        7.x-2.0
 dar        (fullcalendar_colors)
 dar        (fullcalendar_legend)
 dar        (fullcalendar_options)

```

And I see the this view is rendered in the `./sites/all/modules/date/date_views/theme/date-views-pager.tpl.php`

```
<?php if (!empty($next_url)) : ?>
 49       <li class="date-next">
 50         <?php print l(($mini ? '' : t('Next', array(), array('context' => 'date_nav')) . ' ') . '»', $next_url, $next_options); ?>
 51       </li>
 52     <?php endif; ?>

```

# Answer
```
drush dl date --select
Choose one of the available releases for date:
 [0]  :  Cancel
 [1]  :  7.x-2.x-dev  -  2015-Jun-16  -  Development
 [2]  :  7.x-2.9-rc1  -  2015-Mar-27  -  Supported
 [3]  :  7.x-2.8      -  2014-Jul-29  -  Recommended, Security
 [4]  :  7.x-1.x-dev  -  2013-Sep-30  -  Development

```

So if I have 7.x-2.8 - It's okay. 7.x-2.9-rc1 or 7.x-2.x-dev both jump ahead by two months.drush dl date --select

Of the ones available, dev and rc1 have an issue with the next button. 2.8 is fine but it defaults the calendar name to include the first day of the month. So you must choose between a bad title format or a bad next button.

**My solution:** I moved back to Date 7.x-2.8 and then overrode `date-views-pager.tpl.php` in my theme with the following:

```
<div class="date-nav-wrapper clearfix<?php if (!empty($extra_classes)) print $extra_classes; ?>">
  <div class="date-nav item-list">
    <div class="date-heading">
      <h3><?php
        print date("F", strtotime($nav_title))
            . ' '
            . date("Y", strtotime($nav_title));
        ?>
      </h3>

```
> 1 votes

# Answer
This appears to be a known issue, with some patches you might consider using. I'd recommend sticking to 7.x-2.8 unless 7.x-2.9 fixed something you need fixed.

See: Calendar block Next/Prev navigation broken

Some of the initial patches fix the monthly navigation but break the weekly navigation, so the patch needs work. If you have time to fix it yourself, please do! Date module needs a lot more people contributing than it has right now.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: How to remove href from last breadcrumb?
I'm altering breadcrumbs using the `theme_menu_breadcrumb_alter` function and was wondering what can I do to make the last breadcrumb **non-clickable** (i.e. it should be just text, not a link).

I tried making the `href` value to an empty string but that just returns a link to the base URL.

**How can I do this?**

# Answer
> 4 votes
If anyone else is looking for this, here is one way to solve it:

In `template.php` add the following function

```
function theme_breadcrumb($variables){
    // get an array with all the breadcrumbs (and their html)
    $breadcrumb = $variables['breadcrumb'];

    // remove the html from the last one and put it into new variable
    $cur_page_brdcrmb = strip_tags(end($breadcrumb));

    //remove the last element from the original breadcrumb array
    array_pop($breadcrumb);

    // add our html free breadcrumb to the array
    $breadcrumb[] = $cur_page_brdcrmb;

    // build the output and return it
    $output = '<div class="breadcrumb">' . implode(' » ', $breadcrumb) . '</div>';
    return $output;
}

```

---
Tags: breadcrumbs
---


# Question
Title: CCK ahah image upload working if admin, but not for others!
A content type have image field. When uploading image as admin, everything works fine. But If i logged in as a normal user, and click on upload , it gives error ahah http error alert!

Also found add another button also giving same error.

What could be the issue?

# Answer
What Drupal version do you use? May I have list of modules you have? What messages do you have in watchdog?

First think I have is drupal permission problem.
> 0 votes

# Answer
Go to the following URL and check if you have given required permissions to the image field.

http://www.your-website.com/admin/user/permissions

If you want the normal user to access the image field, then you have to give required permissions to anonymous user.
> 0 votes

# Answer
I solved creating a new equal content type. Lucky me it wasn't too late. The problem was because something in a migration
> 0 votes

---
Tags: 6, entities, media, ajax
---


# Question
Title: Views: add custom no result behavior to a view?
I am trying to add custom no result behaviour to a view. I have many pages with view panes in them. Sometimes if no results are available, I would like to be able to display a 404. This is not an option when it's a view pane. I would like to do this in a reusable way where if the view pane has that custom option then this happens.

I can hard code this stuff on one of views hook, but ideally I want to be able to configure such behavior.

# Answer
> 0 votes
This is not an option in views panes because a 404 should be returned by the page\_callback handler, which in this case is the panel that is holding the pane.

Option 1, see if this module works views404, but I have not used it so I do not know for sure.

Option 2, use drupal\_not\_found(), though I have not tried this in a panel. Or if you are using contextual filters try this.

Option 3, stop using panels and use view page with Bean and Context and theme regions and a bunch of other things. This way the page\_callback is being handled by the view, so the view has the authority to return a 404 instead of theming the frame and other blocks and presenting those. Downside is you have to restructure the whole site so you probably dont want that.

---
Tags: views
---


title: views_query_alter never called

text:
# Question
Title: views_query_alter never called
I want to alter a query for sorting a field. I read the documentation, it says

> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.

I used to implement all hooks inside my sites/default/realia/template.php so I first went stright and implemented the hook in sites/default/realaia/template.php which obviously didnt work.

```
function realia_views_query_alter(&$view, &$query) {
    print "<h1>I am in alter query</h1>";
    var_dump($query);
}

```

After reading doc carefully which says the hook needs to be placed inside the specific file and in a specific place I totally feel lost. Because I don't see any .module file in my sites/default/themes/realia. This is where my all files provided by realia (3rd party) are placed there is only .info file but no .module file.

There are also other related modules inside sites/all/modules/realia but looks like this folder is not a module itself becuse there are no .info or .module files inside the root but subfolders/modules has it. I went and created a file reala\_submodule.views.inc with the implementation and placed one in each of the modules but I still dont see it really got executed ever.

Of course I did drush cc all every time whenever I doubted there could be caching issue. I will have followup questions related sorting once I get this implementation working. Please help.

# Answer
> 3 votes
Maybe reason can be if you use Search API module, in this case hook\_search\_api\_views\_query\_alter will work instead

link 1
link 2

I have the same problem now and after some search find that when search API module enabled hook\_views\_query\_alter not worked.

# Answer
> 2 votes
It's not called because it's too late to call it from theme layer. You should call it from a module.

---
Tags: views
---


title: Prevent caching of URL redirect to file

text:
# Question
Title: Prevent caching of URL redirect to file
We have complaints that are related to caching. A Global redirect URL points to a PDF file on the server. People claim they get an old version even after an FTP update.

Using Apache 2.4 D7 and Global Redirect module. URL is in a block (example.com/newsletter) which redirects to sites/files/upload/newsletter.pdf

I don't even know if this is client side or server side caching, but I want to make sure that caching expires daily.

Possible approaches:

* Use drupal file system to manage this as a field
* change the redirect type (gloabal redirect supports a few: like 301, 304,307,etc)
* Add something to the a href tag ?

# Answer
I'm guessing you mean the Redirect module, not the Global Redirect module.

One thing to clarify: Are you trying to change the actual destination of the redirect (by initially having example.com/newsletter redirect to sites/files/upload/newsletter.pdf one day, then the next day having it redirect to sites/files/upload/newsletter-2.pdf)? Or (as I think you're saying) are you actually overwriting newsletter.pdf on the server so that it's a different file?

I'll assume you're doing the latter. If so, then the type of redirect doesn't matter. You're facing caching on the browser side and you need to change your mod\_expires settings. Assuming you're allowing htaccess files to influence your apache configuration, you can put the following in the mod\_expires section of your .htaccess file in the root of your site:

```
ExpiresByType application/pdf A86400

```

That would make browsers cache PDF files for a day (86,400 seconds). An alternative, equivalent syntax is:

```
ExpiresByType application/pdf "access plus 1 day"

```

You can adjust that parameter however you like. See documentation here.
> 1 votes

---
Tags: redirection, uri
---


# Question
Title: Prevent loading certain script set in .info file in Drupal 6
I have a theme with several template files using `<?php print $scripts ?>` to load a list of scripts set in the theme's .info file. What's the best way in Drupal 6 to exclude one of the scripts from being loaded in certain template files?

# Answer
> 0 votes
I do not think there's a way to really un-set scripts once they've been added, in D6. D7 provides hook\_js\_alter, but not D6.

Do you have control over the theme? Your best bet would be to remove the scripts from the .info file and only add them as needed by calling drupal\_add\_js(). Which hooks or preprocessors you need to use to make those calls to drupal\_add\_js() will be something determined by the purpose of the scripts themselves. But you'll want them added before template\_preprocess\_page() is called since that's where the $scripts variable is generated.

---
Tags: theming, javascript
---


# Question
Title: Collapsible fieldsets in form using button
How can I make a button collapse a fieldset in my custom form? I tried the following which did not seem to work:

```
$form['stepone']['next'] = array(
    '#type' => 'button',
    '#value' => t('Next'),
    '#name' => 'nextone',
    '#weight' => 1,
    '#submit' => array('collapse_next'),
    );

```

The function is:

```
function collapse_next($form, &$form_state){
    if(isset($form_state['values']['nextone'])){
    $form['stepone']['#collapsed'] = TRUE;
    $form['steptwo']['image']['#collapsed'] = FALSE;
    return $form;
    }
}

```

# Answer
**I figured this one out!** If anyone needs, I am attaching my method. I added the following into my form:

```
'#prefix' => '<class ="panel-collapse collapse fade" data-toggle="collapse" data-target="#name">

```
> 0 votes

# Answer
you may use jquery for this. give some id to your button and on button click trigger the default fieldset collase or use toggle to hide show fieldset. Hope this help!
> 1 votes

---
Tags: forms
---


# Question
Title: What are some ways to tell if you are currently on the same Drupal installation as your code?
Currently I have to manage a few servers and there are a bunch of Drupal directories that all look alike. I'm also logged in as admin on the site, but what I want to find out is:

* How can I tell if I'm working in the correct directory as the site I'm viewing?
* What are some drush commands I can use to tell if I am in fact in the correct directory?

# Answer
> 6 votes
drush status may give you some info that you need, but probably not.

If you have unique site names setup, then this should work:

```
drush vget site_name

```

If not, then read on...

Is this a multisite setup? If so, then the mapping of hostname onto sites/{sitename} will be either fully automatic based on these rules or determined by the configuration in sites.php.

If it's not a multisite setup and you instead have fully separate directories for each site then the mapping of hostname \> directory is determined by your vhost setup.

In either case, I don't think there's any drush command that will just spit out which hostname you should be using to access the site based upon the directory you run it in.

Instead, I'd suggest you set up some drush aliases that let you be much more purposeful about running drush commands against a specific directory and hostname. So, if you have a site at example.com, a simple alias might look like

```
$aliases['example.com'] = array(
 'root' => '/path/to/example',
 'uri' => 'example.com',
);

```

Then, anytime you want to run drush commands against example.com it doesn't matter what directory you're in, as long as you have access to drush (stick it in your path) you can run:

```
drush @example.com arbitrarydrushcommandhere

```

Take the time to set up your aliases and hopefully you'll be more sane.

# Answer
> 4 votes
I like to use the environment\_indicator module -- the 1.x version, not the 2.x version. This module places a sidebar in the web-browser using a message set in your `settings.php` file. Tail your settings.php file, and you can see if the sidebar matches what you see in the current code.

Version 2.x of environment\_indicator stores the messages for all environments in the database, and then tries to determine which one to display based on the runtime environment -- less useful than simply customizing settings.php, in my opinion.

# Answer
> 1 votes
One easy way i believe was searching for the last login via drush command:

```
drush sql-query 'select uid, access, login, name from users order by access desc limit 3 \G'

```

That will return the last few logins and you'll know if your on the correct site as it will show your username.

This is assuming your username is unique from admin. But if its admin, then that might be a little tricky.

---
Tags: drush, users
---


# Question
Title: How to store additional_settings value when adding a node?
Since storing node type `additional_settings` is done without the need for calling any other hooks, I quite have a problem to store a simple string from `additional_settings` on node add form.

After the admin enables a feature on the node type form he/she is offered the following form when adding a node:

```
$form['MY_MODULE'] = array(
  '#type'         => 'fieldset',
  '#title'        => 'Custom String',
  '#collapsible'  => TRUE,
  '#collapsed'    => FALSE,
  '#weight'       => -99,
  '#group'        => 'additional_settings',
  '#attached'     => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.js',
    ),
  ),
);
$form['MY_MODULE']['MY_MODULE_string'] = array(
  '#type' => 'textfield',
  '#title' => t('Enter a string'),
  '#default_value' => '',
);

```

I've seen other modules, like `comment.module` or `nodeapi_example.module` where they then call `hook_node_insert()` and I tried that as well. I happily can see my string within `dpm($node)`, but then I'll get a `PDOException: SQLSTATE[42S02]: Base table or view not found`. Do I have to follow any naming conventions on how to name the table? Or do I have to create it first (where)?:

```
db_insert('MY_MODULE_string')
->fields(array(
    'nid' => $node->nid,
    'vid' => $node->vid,
    'string' => $node->MY_MODULE_string,
))
->execute();

```

# Answer
> 1 votes
Turned out I simply had to look into `nodeapi_example.install` to find out about `hook_schema()` to create a new database table where I then can save my values to. So I created an install file and put the following code inside:

```
function MY_MODULE_schema() {
  $schema['MY_MODULE_string'] = array(
    'description' => 'Stores information of extended content.',
    'fields' => array(
      'nid'    => array(
        'description' => 'Node ID that the string is applied to.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'vid' => array(
        'description' => 'Revision ID, as we are tracking strings with node revisions',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'url' => array(
        'description' => 'MY MODULE string',
        'type' => 'varchar',
        'length' => 19,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('vid'),
    'indexes' => array(
      'nid'   => array('nid'),
    ),
  );
  return $schema;
}

```

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


title: How can I use these modules together?

text:
# Question
Title: How can I use these modules together?
Is it possible to use Mimemail, Mail System, and SMTP Authentication Support modules together?

Currently I am using Mimemail to send HTML-formatted messages; however, because of the configuration of my server, these e-mails are often being recognized as spam. To reduce the chance that they will be recognized as spam, I want to use the SMTP Authentication Support module.

# Answer
> 10 votes
Yes. We can use the Mimemail + SMTP Authentication Support. Plz check the link http://drupal.org/node/1200142 and check the part : Alternative Approach: Mail System + SMTP + Mime Mail

# Answer
> 1 votes
http://drupal.org/node/1200142 is a good way to set up Drupal + Mimemail + SMTP. It needs also Mail system module (as a dependency of Mimemail).

There is a trick: When using the Mime mail\__SMTP bridge for both *Site-wide default MailSystemInterface class* and *Mime Mail module class* is OK when sending email without inline images (I didn't try with attachments).

But when trying to make Mailmime embed images, it results in a PHP Mailer (Drupal) error saying "Mail body empty".

To make the system work,you have to set *Site-wide default MailSystemInterface class* to MimeMailSystem.

I'm not sure this is a reliable way because it could mean you are not using SMTP connection at all. Though, when you run a SMTP test from SMTP module configuration page, it works as expected and when checking received mail headers, it confirms the use of SMTP.

Edit: My bad, send mails with such settings is not using SMTP at all, but it uses drupal default mail system.

I'll open a new question for my needs.

---
Tags: 7, mimemail
---


# Question
Title: How to calculate field values in Views Calc?
In Drupal 7, I have a custom content type containing distance (a decimal field) and time (a date field where only hours, minutes and seconds are entered).

In a view on that custom content type, I would like to show not only distance and time but also speed. (speed = distance / time)

I already tried to create a formula in views calc but:

1. I didn't find a way to get the hour, minute and second values separately from the date field. When I tried to define DATE\_FORMAT (%field, '%i'), I got an error mentioning that i is not an allowed value.
2. I tried to work with the value of %field directly (because I found out that the field contains 101HHiiss as value) but I coulnd't define something like %field / 1000000 because then I would get an error mentioning that 00 is not an allowed value.

# Answer
Edit: Sorry, I overread "Views Calc" before I wrote my answer. But maybe it helps you nevertheless.

---

Views maybe isn't the right place to add your custom code to. You might consider writing a very small custom module. Let Views then maybe display full nodes. And in your custom module you might hook into `hook_node_view()`, grab your node's fields, do the calculation and finally add the result as a new field to the the node's content, which then will get rendered automatically:

```
function MY_MODULE_node_view($node) {
    dpm($node); // start with that

    $time = $node->field_time[LANGUAGE_NONE][0]['value'];
    $distance = $node->field_distance[LANGUAGE_NONE][0]['value'];

    // do your calculations
    // ...

    $speed = $result;

    $node->content['speed'] = array(
        '#prefix' => '<div id="speed">',
        '#markup' => $speed,
        '#suffix' => '</div>'
    );
}

```

When developing your custom module you might find the Devel module quite helpful. After activating it you can easily check out what's inside a variable and then double click the displayed results for a deeper insight. So you might start by calling `dpm($node)` right inside `hook_node_view()`.
> 1 votes

---
Tags: views
---


# Question
Title: Drupal 8: Template suggestion for form-element in a views exposed filter is not working
In Drupal 8 I am trying to add in a suggestion via hook\_theme\_suggestions\_alter() like so:

```
function ua_sc_theme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  print '<!-- hook: ' . $hook . '-->';
  if (in_array($hook, ['input', 'form_element']) && $variables['element']['#attributes']['id'] == 'edit-keys') {
    $suggestions[] = $hook . '__custom';
  }
}

```

...and then I give my template a name of form-element\__custom.html.twig and put it in my theme it doesn't get used an instead the default form-element.html.twig template is used. Any thoughts on what is going on?

# Answer
> 2 votes
Ok, looks like I was too tired. The problem was that the template should be called form-element--custom.html.twig.

Notice the '--' (double dash) instead of the \__ (double underscore).

I also ended up using the more specific hook alter:

```
hook_theme_suggestions_HOOK_alter

```

...where HOOK for me was form\_element.

# Answer
> 1 votes
In your form add `'#theme' => 'input__custom'` to the input element. The 'input' is the theme implementation and '\__custom' is the suggestion.

This hook is for global suggestions.

---
Tags: 8, theming
---


title: Issue with Contextual Filters

text:
# Question
Title: Issue with Contextual Filters
I have a pretty particular issue that I'm running into with setting up an Administration View using Contextual Filters.

I've set up a view to handle `/admin/content`.

Basically, what I would like is for users in a particular role to see the content that **they are authors of**, and **one specific other content type**, for which nodes are submitted by anonymous users through a webform.

So, to recap, users in this role need to see:

* Nodes that they are the author of
* Nodes submitted by anonymous users, of a specific content type

Any thoughts?

# Answer
You shouldn't need contextual filters for this as nothing needs to be passed in via the URL.

It should work like this using regular filters:

1. Create a node view
2. Add a relationship for "Content: Author"
3. Add a filter for "Content: Type" and restrict to the specific content type you refer to.
4. Add a filter for "User: Current" and set it to "Yes". This will be using the relationship you defined in step 2.
5. Click the drop down next to the filter criteria heading and click "And/Or, Rearrange".
6. Change the operator for your 2 filters to "Or". Then you will see on the right it says current user or content type. Then click apply. - Note that if you have other filters set you may have to click the "Create new filter group" button then add these 2 filters to the new group then use "Or" within that group and "And" for the rest.
> 1 votes

---
Tags: users, views
---


# Question
Title: How to extend flood control in a custom module?
I would like to use Drupal's flood control capability in another module. I have a resource I'm protecting with a password.

Can I simply call flood\_register\_event() and otherwise use the variables as used in the code for user\_login\_final\_validate()?

Am I on the right track at all, or how do I use flood control?

# Answer
You need to do 3 things when you validate your password entry form:

1. Use flood\_is\_allowed() to check that the user hasn't already breached their flood limit and set a form error with form\_set\_error() if they have.
2. Use flood\_register\_event() to log failed attempts on incorrect password errors.
3. Use flood\_clear\_event() when the user enters the correct password.

You can also decide whether to do it based on uid, ipaddress, both of those, or something else entirely.

You can see the example of the user module in user\_login\_authenticate\_validate() and user\_login\_final\_validate(). That example may or may not be more complex than you need in your specific case.
> 6 votes

---
Tags: 7, security, users
---


# Question
Title: Does Drupal distinguish types of error messages?
In D7, under `Configuration > Development > Logging and errors` you can set "Error messages to display" to "none".

However, I would think users should still be able to see form error messages, for example when they don't fill out a required field.

Are there different 'types' of 'error messages'?

# Answer
> 1 votes
This setting is for server errors, the drupal form errors will still be shown.

Here is some more information on this topic: https://www.drupal.org/node/1036982

# Answer
> 0 votes
# About 'see form error messages'

There are basically at least 2 approaches to address your question, as further detailed below.

### Use the Disable messages module

You could use the Disable Messages module for this. Here is a quote from its project page:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

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

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).

### Write some custom code

Add appropriate logic in the template of the theme you're using, similar to what is done in the code sample shown in the answers to these questions

# About 'Types of error messages'

The "types or error messages" (as in your question), is what is referred to via the $type variable in the code samples in the above answers. Its value is a string, and can be any of those:

* '*NULL*': **all** messages (= default value).
* '*status*': only **status messages** (informational messages or confirmations).
* '*warning*': only **warnings**.
* '*error*': only **errors**.

Obviously, if you ever change themes, then you have to remember to reapply this logic to your new theme also.

---
Tags: 7, forms, status-messages
---


# Question
Title: If I save created view and visit the view page it showing only filter field
I am new to drupal and I am trying to create `view` for my `content type`, I followed the steps using a tutorial but I am not able to see the preview of the created content view if I save and visit the view page it showing only filter field. Please help me.

I have used the following method to create the view.

1) click on `view` and Add new name.

2) enter the name and in the show field selected the content then i specified my created content in type of field, and newest first in the sorted by field.

3) selected the table format.

4) added the fields of specified content with the help of search box where in i have given the content name so all related fields show up.

5) added the filter field from specified content.

# Answer
> 0 votes
I think you set "age expose field required" it cause in first load nothing show up till user enter something in filter. try it with removing "Required" checkbox.

---
Tags: views
---


# Question
Title: Are blocks still cached when "Cache block" setting disabled but "Cache pages for anonymous users" is enabled?
I have a site which contains a custom block. The custom block contains a menu based on a sub-set of the site's main menu. The problem is that main menu is very large (~1300 items), so generating this particular menu in the block, is quite costly. According to hook\_block\_info() the block is configured to use DRUPAL\_CACHE\_PER\_PAGE | DRUPAL\_CACHE\_PER\_ROLE caching methods.

If I go to the site's performance configuration page I notice that the "Cache block" option is disabled; However, the "Cache pages for anonymous users" option is enabled.

In such a situation would the block be cached or not? If it is cached, then would that only be for anonymous users?

# Answer
> 0 votes
TL;DR **yes**

Well, not per se. But page it appears on is cached, including that block. There is no separate item for the block in any cache in situation you described, but it won't be recreated anyway. Code for it won't be executed. And yes, in default Drupal configuration page caches works only for anonymous users.

---
Tags: 7, blocks, caching
---


# Question
Title: File upload with ajax and without upload button
Is there any example how to set up form element with type file to upload it via AJAX and without upload button. I want to be same as stackexchange.

# Answer
> 3 votes
These modules can help you

HTML5 Drag & Drop File

> HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to drag & drop files into a Image/File Field and uploads it immediately behind the scenes. In theory it should work for as many files as the field allows.
>
> Requires jQuery \>= 1.5.2 (jquery\_update has that)!
>
> It's a start...
>
> ```
> Enable
> Works for all managed_file fields
> You can disable per field in the field instance config
>
> ```
>
> There's a settings form under Config \> Media where you can change the upload method from Series to Parallel (much faster, but slightly riskier). If you dare, try it out. I've experienced (although not for a while) the full entity form being submitted by a file upload.
>
> If you're uploading A LOT of files, you might encounter the server's max file/POST size limit. I've no solution for that yet.

Drag'n'Drop Uploads(you can use dev version,I am using it and work;) )

> The Drag'n'Drop Uploads module adds the ability to drag an image from your local filesystem, drop it onto a node body textarea and have the file automatically uploaded and referenced in your node.

(maybe you just need some custom jquery coding, first hide upload button then fire upload button programmatically in your js)

Plup

> Plup module enables uploads to file fields using the popular plupload library. It does not require any other modules to work, but the plupload library must be downloaded separately (version 1.5.8 is the last supported version).
>
> Please note that you must remove the "examples" folder from the downloaded plupload library to avoid introducing a security vulnerability.
>
> The original developer is no longer maintaining the module, and I will only minimally maintain it until Media 2.x has a stable release that works with plupload and multiform, after which I expect to migrate to those modules.

---
Tags: files, media
---


# Question
Title: How to Fix/Clean Lambda warnings/errors from Views PHP
I used views php to get the values from the field collection of the saved node in order to create a front end select list on views.

It does what I wanted it to do but there are a bunch of warnings and notice and I would like to clean it.

This is just a part of the warning and notice that appeared.

And this:

It's a repetition of errors for my different variables.

This is an example of my code:

```
<select class="number_of_person">

    <?php
    $wrapper = entity_metadata_wrapper('node', $row->nid);
    if (isset($wrapper->field_criteria)) {
    $prices_number_of_person= array();
    $min_and_max_number_of_person = array();
        foreach ($wrapper->field_criteria as $i){
              $price_loop1[] = $i->field_price->value();
              $min_and_max_loop1[] = $i->field_criteria_name->value();

        }
         $prices_number_of_person= implode(",", $price_loop1);
         $min_and_max_number_of_person = implode(",", $min_and_max_loop1 );

         $split_min_and_max_number_of_person = explode(",", $min_and_max_number_of_person );
         $split_prices_number_of_person = explode(",", $prices_number_of_person);

         $length_number_of_person = count($split_min_and_max_number_of_person);

        for ($number_of_person=0; $number_of_person < $length_number_of_person; $number_of_person++) {

        if($split_prices_number_of_person[$number_of_person] !="" ){
         echo '<option value="'.$split_prices_number_of_person[$number_of_person].'" class="options">'.$split_min_and_max_number_of_person[$number_of_person].'... + ₱ '.$split_prices_number_of_person[$number_of_person].'</option>';
        }

         else{
          echo '<option value="'.$split_prices_number_of_person[$number_of_person].'" class="options">'.$split_min_and_max_number_of_person[$number_of_person].'</option>';

              }
         }

     }
    ?>

    </select>

```

I was wondering if there is something that I need to add to my code to get rid of the warning and notice?

Thank you in advance!

# Answer
Before try to explode/implode check that data exist in them as example

```
"$price_loop1"
 if($price_loop1)
     $prices_number_of_person= implode(",", $price_loop1);

```

and for explode

```
  if($prices_number_of_person)
      $split_prices_number_of_person = explode(",", $prices_number_of_person);

```
> 1 votes

---
Tags: 7, views
---


title: Quiz results/score are over 100 points

text:
# Question
Title: Quiz results/score are over 100 points
I have a quiz with 5 questions of 10 points each one. When I score them, some exams save the result of the quiz with more than 100 points.

As you can see, I have an exam with 112 but if I open:

Look that the total score is 92% (but his score is 112).

In the other hand, the user with 100 scores is right.

So, as summary of this, I've got users with right total score but some of them have a wrong final score.

The module that I'm using is Quiz drupal.org/project/quiz version 7.x-5.0-alpha9.

Any idea?

Thanks!

# Answer
Thanks everyone for your answer. Finally, I've achived to solve the problem. At first, this bug comes from last versions.

If you create in this module a Long Question which max score is 0, it creates an inconsistency because you cannot divide by 0.

Some months ago, I found a patch to solve it:

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

But it's incomplete, because the module save the scores of each question in database and then it updates the total score adding the score of each one.

So, the way to solve that is changing the next lines in the same file that the patch file (**../question\_types/long\_answer/long\_answer.module**):

```
db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $points_awarded,
     'is_correct' => $is_correct,
))

```

to

```
db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $calculated_score,
     'is_correct' => $is_correct,
))

```

To note the change is the variable **$points\_awarded** for the variable calculated in the patch: **$calculated\_score**.

With these changes, the patch is complete and everything is working.
> 1 votes

---
Tags: 7, users, quiz
---


# Question
Title: How can I prepopulate a field when creating a new node with the values from a field collection?
I am creating an inventory management system in drupal. I have two different content types: and item and a purchase order.

An item has a name, style code, Colors (this is a field collection with a color name and color code), and a range of sizes (3 to 15 for shoes and XS to 4XL for shirts). Some items don't have colors and some don't have sizes.

In a purchase order, there is a purchase order number and any number of items ordered (a field collection with an entity reference to the item, a field for the number of items ordered, and field for the number of items received). Each item ordered will have one color (one of the colors that the item is available in) and any number of the sizes that was selected in the given item.

My question is how I can populate the color selection (probably a dropdown) with the colors that are in the field collection of the selected item (entity reference). I would also need to populate the sizes list with the sizes that were selected from the item, as well.

I am still pretty new to drupal, and I realize that I may be going about it the wrong way or that I may not have explained everything that someone would need to know to help me. But I am open to new ideas or different solutions. I haven't done much module development, but I would be willing to learn if needed.

# Answer
> 1 votes
You can try and look at this module. It allows to have corresponding node references and hence if you select something from one node, you can prepopulate the other node as well. http://drupal.org/project/cnr

# Answer
> 1 votes
You will probably need to write your own module to handle the content creation with the individual collections. In a bug report on drupal.org, I give a code example that can be used to create a node and field collection (and a field collection within the field collection).

A stripped-down version might look like this:

```
<?php
$container = entity_create('entity_type', array('type' => 'entity_bundle')); // replace entity_type and entity_bundle with your info

// Set default values for fields in $container, except for the collection,
// which will be done later

// Now save the container
$container->save(); // necessary in order to attach field collections

// Create the collection
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_collection_1')); // replace 'field_collection_1' as appropriate

// Set default values as necessary

// Now save the field_collection
$field_collection->setHostEntity('entity_type', $container); // again, replace entity_type as appropriate
$field_collection->save(TRUE); // calling this with TRUE is important!
}

$container->save(); // must be called again, otherwise the collections will not be added
?>

```

There's a lot of `save()` calls in here, but it gets the job done.

# Answer
> 1 votes
First let's review a bit the business model of your purchase order Content Type. Let's say there is an item node that represents a T-shirt that is available in green, blue and yellow colors and S, M, L sizes. Now, I want to buy two of those T-shirts, one small size in green color, and one large size, in blue color. So, the purchase order instance/node for this usecase, would have two field collection items:

1. Item id 3 (let's say 3 is the nid of the T-shirt), color green, size small
2. Item id 3 (let's say 3 is the nid of the T-shirt), color blue, size large

So, your field collection definition in the purchase order CT should have the following fields

* Item id (single value field)
* Color (single value field)
* Size (single value field)

and given that model, I would also add a single value checkbox labeled 'Item received'. So it becomes apparent, that you need to change your current implementation to the one above, otherwise with your current implementation, a user cannot order the same T-shirt in different color/size combination (if I understood correctly from the details you provided)

Now, the CNR module suggested above is not a good solution, because a) it has been deprecated in favor of CER b) it is used in cases you want to populate bidirectional references between entities (if node A refers to B, then B is aware that it is referenced by A), which is not the usecase here.

Again, if I understood correctly, when a purchase order is placed (somehow in your context), the node create form for purchase order CT appears to the end user. Then, if the user selects an item, there should be color and size dropdown menus for choosing the desired color and size, depending on the underlying referenced item availabilities. Is that correct? Well, if this is the case, then coreyp\_1 solution is not applicable either, as it implies that you save the purchase node programmatically. If you change your model to the one suggested above, then you don't have to do so. You will already have the field infrastructure in the purchase order CT and if you manage to pre-populate colors and sizes appropriately while creating a new instance of it, Drupal will handled the saving for you.

So, back to the original question. The solution depends on the field types for Color and Size. Are they taxonomies? Are they plain list items? In any case, the same fields (both for Color and Size) that are originally used for the Item, should be re-used for the purchase order CT as well. And as far as the pre-population is concerned, it can be implemented as suggested here

---
Tags: entities
---


# Question
Title: How to fix the useless 'favicon.ico page not found' log message?
Why is Drupal looking for it in the root dir in first place? The favicon is always placed inside theme at `sites/all/themes/mytheme/`, but it's looking for `favicon.ico` inside home `/` dir.

When browsing website it spams the log error message in the `Recent log messages` page.

# Answer
> 1 votes
It's not really a Drupal bug, but a browser bug (I think Firefox might be a culprit)

The best way I found to fix it is to put:

```
<Location /favicon.ico>
  ErrorDocument 404 "No favicon"
</Location>

```

This code should work in your vhost file or should also work in the .htaccess file, see http://httpd.apache.org/docs/2.4/sections.html for more details

---
Tags: 7, theming, debugging
---


# Question
Title: Faceted search using fields from a related node, is it possible?
Drupal 7 Modules: Facet\_api 7.x-1.3 Search\_api 7.x-1.6 Relation 7.x-1.0-rc4

My site has two nodes, node one provides a description of various astronomical objects and node two are images and their composition details. I’ve built a many to many relationship between the two nodes and there is a node index (search\_api) which contains all fields from the two content types with facets enabled on the primary fields.

I’ve created the faceted search page for the Astronomical objects which works fine and I now want to extend the Astronomical facets to gallery search page (. e.g. Show all images containing an astronomical object of type galaxy) which is where I have become stuck as I can’t see a way to create an index which joins relationships and nodes.

If this approach isn’t possible the only alternative I can think of is building out the relation type with extra fields duplicating the data that I want from either node and building the index on it, which just feels like a hack. Any suggestions?

# Answer
> 1 votes
At the bottom of the fields page you can see additional fields. This allows you to join nodes via relationships.

Search API \> Default index \> Fields \> \[Scroll to bottom} \> **Add related fields**

1. Select your field that is an entity reference.
2. You'll have access to the fields of the reference too.
3. Then select the fields on the referenced node that you need and save.
4. And return to facets.

http://example.com/admin/config/search/search\_api/index/default\_node\_index/fields#edit-additional

# Answer
> 1 votes
I can't post comments, so excuse me, but I think that I should **warn** you about one moment. The first answer is right for me, but you must remember that if related field was changed - you must manually rebuild index. I found one solution: use hook and

```
search_api_track_item_change($entity_target, $entity_ids);

```

search\_api\_track\_item\_change

hook\_node\_insert

Another way is to rebuild index via cron.

---
Tags: entities, search
---


# Question
Title: Are tests built into contrib modules a reliable way of testing the success of a module upgrade?
I have been updating some modules including Views and Feeds. Given these modules are quite complex, I thought a good method of testing whether the update was successful or not was to run the tests which come as part of the module. This can be performed by using simpletest module which comes with Drupal core.

However the tests do not complete successfully (by this I mean that there was not a 100% pass rate). I then rolled back to the previous version of Feeds, and low and behold it did not fully pass either. This is a large site which has many visitors and I am certain that the Feeds functionality has been running fine, otherwise someone would have been complaining about it.

So it seems Feeds is working on the production site, but the built-in tests don't fully pass.

As follow up I did a clean install of Drupal 7.38 and then added latest versions of Feeds, Views, Features, ctools, Job scheduler and Feeds Tamper. Site is a standard install with no content. After running the suite of feeds tests I get even more failures than on the existing site I mentioned previously. In fact almost all the tests fail.

This has got me wondering if in-built tests are a good measure of whether a contrib module is working correctly? Or are they quite unreliable, as I now suspect?

# Answer
# No

Automated tests was created to test code, and to ensure quality of patches. They are meant to be executed in specific, clean environment (e.g. Testbot environment), which your live site certainly is not.

Second reason why it's no is what is tested. These tests only test code. But downloading and unpacking code is simple. Not many thing that can go wrong, and if it goes wrong, you will rather see. The hard and important part is database upgrade - and tests will not try to verify if your data was updated properly.
> 1 votes

---
Tags: 7, feeds, updating, testing
---


title: db_select query advice

text:
# Question
Title: db_select query advice
I have two content types: **development** and **house**.

A **development** has many **house**s.

Each **house** has a *house\_type* field

I'm trying to perform a db\_select query that allows me to search all developments and find the *house\_type*s attached to them.

I've managed to find the developments, then found the attached *houses\_on\_development* (i've used group\_concat for this), ***AND THEN, WHERE I'M STUCK...***

I need to query each of the *house\_type*s of these concatenated house\_ids individually to find out their *house\_type*.

I've started with:

```
$search_type = 'development';
$query = db_select('node', 'development');
$query->condition('development.status', '1', '=');

 $query->leftjoin('field_data_belongs2dev', 'property',
        'development.nid = property.field_data_belongs2dev_target_id');
$query->addExpression('group_concat(property.entity_id)', 'houses_on_development');

```

And now i'm stuck. I know how to write the query to get the house\_types if I was querying house\_id one at a time but don't know how to fit that query into a bigger db\_select. For this I would use:

```
SELECT field_property_type_tid
   FROM field_data_field_property_type
   WHERE entity_id
   IN  ( house_id1, house_id2, etc... )

```

I feel like i'm so close but missing that final bit od knowledge. Please help.

# Answer
> 0 votes
Think your query needs to be:

```
$query = db_select('node', 'development');
$query->fields('property_type', array('field_property_type_tid'))
  ->condition('development.status', 1, '=')
  ->addJoin('LEFT', 'field_data_belongs2dev', 'property', 'development.nid = property.field_data_belongs2dev_target_id');
$query->addJoin('LEFT', 'field_data_field_property_type', 'property_type', 'property.field_data_belongs2dev_target_id = property_type.entity_id');
$query->addExpression('group_concat(property.entity_id)', 'houses_on_development');
$results = $query->execute();

```

Hope this should point you in the right direction.

---
Tags: database
---


title: Image uploading issue

text:
# Question
Title: Image uploading issue
I have uploaded the drupal website on one of my domain and it is working well, then now I need to migrate it to another domain. Every thing was migrated but when I try to upload images from admin panel it is not uploading correct images. Means, if I try to upload let say cat.jpg then sometimes it display another random image from my directory. Strange issue, unable to figure out why?

I am trying to upload the following image:

And when it is uploaded it is displaying a random image:

# Answer
> 0 votes
I suggest you clear you cache and if not getting worked I suggest install image style flush module and flush all your image styles.

Easiest way to flush image styles in Drupal 7.

> Image style flush Overview
>
> This module will allow Drupal to flush all image styles at once or flush each image style individually right from administrative interface. Features
>
> ```
> Flush all image styles
> Flush each image style individually
>
> ```
>
> Known problems
>
> ```
> Private file image styles can't be flushed with this module.
>
> ```

---
Tags: media
---


# Question
Title: How to sort node resource in index call in ascending order the in service module
Hi I am using `service module 7.x-3.12`. I am able to fetch the node resource in index call on several different parameters and its working fine but I am stuck in a situation where I need to fetch the data in ascending order. But by default I am getting the data in DESC. Is there any way I can fetch the data in ascending order by providing a custom parameter say, sort\_by.

# Answer
> 1 votes
It *currently* isn't possible. I have an issue and patch filed to make this a possibility. If you use the patch, it is possible using this query string:

```
?q=endpoint/taxonomy_term.json&fields=tid,name&options[orderby][name]=asc

```

# Answer
> 0 votes
Try **Services Views** Module

> It has currently two features:
>
> * Create view based resource creating Services display in a view
> * Execute any view of the system via views resource call

With the help of this you can create a view of type `service` and you can add whatever fields, filters,sorting you need.

---
Tags: 7, services
---


title: Reservation / register module for D7

text:
# Question
Title: Reservation / register module for D7
I need a simple reservation module for my D7 restaurant site.

What I need in the form is:

1. Customer information fields (Name, email, contact number, address, etc)
2. Number of tables to be reserved by that customer
3. Upon submission of reservation will lead to another link (I will write codes to link to payment gateway)

Admin are able to configure:

1. Price per table (Eg: USD 100 per table)
2. Total number of tables available to reserve (Eg: 100 tables)
3. Closing date for reservation, so that customer can't reserve after the closing date

Admin able to see:

1. Report of reservation
2. Details such as customer name, number of tables reserves, etc

I had tried using Webform, but I can't do the following:

1. Reservation close on particular date
2. Limit number of tables so that overall tables reserved will not exceed 100

Is there any reservation or registration module that I can use?

Or is there any method I can modify my webform to suit the requirement?

# Answer
> 1 votes
Perhaps the Drupal Restaurant Distribution is what you need, and if not it should at least give you some ideas.

It contains a number of modules, including on for reservations which I assume will do all you need, and more.

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

From the feature list:

> **Reservation System** \- Manage your reservations easily from one dashboard. View all reservations for today, this week or this month.

# Answer
> 0 votes
Here are some modules that might be worth further exploring (quotes are from their project pages):

* Availability Calendars (D6 or D7).

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation (D6 or D7).

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

---
Tags: 7, webforms, bookings
---


# Question
Title: Commerce payment for Rooms reserveration only after the order is confirmed
I want to use Commerce \+ Rooms and wonder if there’s a configuration/module for the following procedure:

1. User reserves a room, checks out, but isn’t allowed to pay yet.
2. The room owner gets an email and confirms/declines the order.
3. If confirmed, the user gets an email and can now start the payment process in the checkout.

Rooms offers an "enquiry mode" (instead of the mode for booking directly), but as far as I understand it, this only sends an email (no order is created), so this enquiry never reaches Commerce.

# Answer
> 0 votes
Maybe you want to look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site.

Here are some more details about this distribution (quotes from its project page):

> ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
>
> It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts. Easy booking profile is powered by Drupal Rooms and Drupal Commerce \- widely used and popular contributed decisions, which means active maintaining and timely technical support.

---
Tags: commerce, bookings
---


# Question
Title: Users with no roles are getting onto my system
I am having an issue with my site, there are users accessing it and creating accounts without having a role.

Here we can see user roles is blank. From my understanding someone has found a weakness in our system and has exploited it to create accounts with no roles.

since the account has no role does this mean its not subjected to the rules of any role? Do these accounts have admin access to our site or would it be closer to anon users.

Is there any basic thing that I could do to stop people with no roles getting in? Or is there a way to see how a user with no role is created (understanding the process would help me fix the problem)?

**Edit 1**

Version: Drupal 7

Module: User 7.32

Module: LoginToboggan 7.x-1.4

# Answer
Users with no roles are how the default "Authenticated user" role is listed. I.e. these have the access level that the system gives the role ""Authenticated user".

This by itself is nothing to be concerned about.

If you don't want to allow bots and fly-by users to create accounts, navigate to *Home » Administration » Configuration » People » Account settings* and under *Registration and cancellation*, click that only admins can create new accounts.

If you want people to able to create accounts, but not bots, you need to let the registration process tell bots and humans apart. One of these modules *may* help:

However, in 2015, bots like XRumer *knows* how to do *most* CAPTCHAs including math and "warped" letters - you may need to experiment a bit to find a CAPTCHA configuration that works.

But preventing spam registrations are actually the topic of this question: Unknown User Registered into my system
> 2 votes

---
Tags: users, security, advertising
---


title: why my code does not run on drush?

text:
# Question
Title: why my code does not run on drush?
The following code when i run it out of the drush command all goes fine... But when i want to create a drush command nothing works :/

```
/**
 * Implements drush_hook_my_command().
 */
function drush_my_module_create_driver_licence_term() {
$licence = taxonomy_vocabulary_machine_name_load('driver_licence');
$terms = taxonomy_get_tree($licence->vid);

  foreach ($terms as $term) {
    $wrapper = entity_metadata_wrapper('taxonomy_term', $term->tid);
    $wrapper->field_blablabla->set(4453);
    $wrapper->save();
  }
}

```

# Answer
> 1 votes
You might have more luck starting off with a working example Drush command. See the drushify project for a code generator that will create one for you. From there, if you do not want to set up a source level debugger, you can always add drush\_log calls to print out the values of your variables.

---
Tags: taxonomy-terms, drush
---


# Question
Title: How to implement a booking system using Drupal Commerce for checkout?
I have been playing with Rooms, Availability Calendars, commerce availability, and many other modules to achieve my goal but I have had no luck in trying to achieve exactly what I want to do.

Does anyone know of the best solution to achieve the following:

* A holiday home booking system where users can search node teasers via available dates and checkout via Drupal Commerce.
* Views integration: Search nodes on available dates
* Checkout: be able to choose a date range from available dates and checkout through Drupal Commerce.

# Answer
You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).

Here are some more details about this distribution (quotes from its project page):

> ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
>
> It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts. Easy booking profile is powered by Drupal Rooms and Drupal Commerce \- widely used and popular contributed decisions, which means active maintaining and timely technical support.

**Note**: for some other module suggestions that might possibly help, refer to my answer to the question "https://drupal.stackexchange.com/questions/173341/how-to-create-this-reservation-form-in-drupal/173467#173467".
> 0 votes

---
Tags: commerce, bookings
---


title: Embedding a view in user edit form

text:
# Question
Title: Embedding a view in user edit form
How can I embed a view inside a user edit form depending on that user's role. I have used the Context module but it does not have the right conditions.

At the moment is uses the (user page -\> User account form) condition. I cannot use the User role condition because it is for the currently logged in user.

# Answer
> 5 votes
You can use `hook_form_alter` and `views_embed_view` to alter the form and add the markup for a view.

# Answer
> 1 votes
I finally found an answer to this problem. Its called the context module.

1. Create a new context and define some conditions. For me the condition was a certain role and the User Page (User account form)
2. Define Reactions -\> Add Block ( The Views Block in Question)

A small problem i have that i do not know exactly how to place my views in between specific fields.

I figured out, how to write hook\_form\_alter with views\_embed\_view:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['my views block'] = array(
      '#type' => 'markup',
      '#markup' =>views_embed_view('myview','my_block_display'),
      '#weight' => 1,
    );
  }
}

```

# Answer
> 1 votes
Use https://www.drupal.org/project/embeddedviewfield

EmbeddedViewField module can render a view regardless of whether the user is editing or displaying the entity that has the EmbeddedViewField.

# Answer
> 0 votes
You can try with Panels module. Create a panel page with 2 areas: one for the form and one for the view. The view can be embedded if a block is provided by it.

# Answer
> 0 votes
This is done through user\_profile\_form\_alter. To add to oll's answer to position the field on the profile form - the weight setting positions your field. If you are using vertical tabs/grouping to format you'll also need to put the field in the right group.

```
$form['my views block'] = array(
    '#type' => 'markup',
    '#markup' =>views_embed_view('myview','my_block_display'),
    '#weight' => 1,
  );
      $form['#group_children']['my views block'] = 'group_myverticaltab';

```

# Answer
> 0 votes
Please refer this link: https://www.drupal.org/node/1655012

Or try something like:

```
$viewName = 'view_name_goes_here';
print views_embed_view($viewName);

```

-hope it may help. Thank You.

---
Tags: 7
---


# Question
Title: Mimemail + SMTP + Mail System: inline images make body empty
I'm trying to send HTML mails on a Drupal 7 install. For this, I use Mail System, SMTP authentication and Mime mail modules. I used settings as Alternative approach on this page http://drupal.org/node/1200142

The mail content is built within custom modules I'm writing (not by rules or simplenews, I mean). I tweaked default Mail mime template to my needs, within a separate, light drupal theme.

My mails are sent (and received) without error when they contain only HTML and styles. There are no error also when I had images with absolute url: Mime mail is leaving them as such.

I need to embed a few small images within my mails and when I try to do so, accordingly to what's written in Mime Mail README, I get a "Message body empty" at the top of my page when my code tried to send the mail.

I placed `dpm($message)` along the Mime mail code to locate where the body content is left empty. I finally reached the `class MimeMailSystem implements MailSystemInterface` located in `mimemail/includes/mimemail.mail.inc`

Body content was still there.

Then the `class MimeMailSystem__SmtpMailSystem implements MailSystemInterface` in `default/files/mailsystem/MimeMailSystem__SmtpMailSystem.mail.inc`

Again, my content was still there, along with inline BASE64 encoded images. So the content disappears somewhere after that (in Mail System ?)

As I pointed it out here, switching `Site-wide default MailSystemInterface class` in Mail System settings from `MimeMailSystem__SmtpMailSystem` to `MimeMailSystem` allows the mail to be sent with its images, but the mail is no more sent through SMTP.

I'm pretty sure this is not due to a bug within one of the 3 modules, but I can't figure what I'm doing wrong.

The only thing I doubt from here is how I build the mail content :

* I build some variable HTML content
* I store it in `$message['body'][]` in my module's `hook_mail` implementation
* then I print `$body` in my `mimemail-message.tpl.php` within static HTML part of the mail

The images I try to embed are in public files. I tried to link them :

* with relative paths like `sites/default/files/<filename>`
* with relative paths like `public://<filename>`

with no success.

Does anyone has a magical one character solution for something I missed ? ;)

Regards,

# Answer
Further investigations lost me into the SMTP Authentication Support module It's complicated enough and I couldn't locate something to help me find what was the problem coming form my configuration.

After a quick search within issues of Mime mail, someone was linking to another module to handle SMTP connection: enter link description here

Basically it works the same way than SMTP Authentication support but its benefit is you don't have to create a bridge mail system class between it and Mime mail, it's natively integrating with Mime mail.

To make it work properly, I had to configure Mail system as such :

* Site-wide default MailSystemInterface class: MimeMailSystem
* Mime Mail module class: MimeMailSystem
* PHPMailer module class: DrupalPHPMailer

and in Mime mail settings : \- set Mail engine to PHPmailer
> 3 votes

---
Tags: media, emails, nodes
---


# Question
Title: Show right node revision for View Draft, View Publised links
I am using panels to override node template and on panels I am adding views blocks for the node content. I have workbench moderation enabled for this node. Issue is in showing the appropriate revision of node for workbench for example

* When I use `View published` or `View Draft` link, I am seeing all revisions of node field instead of current revision for `View Draft` and published revision for `View published`.

The view I have created is on base table: `node_revision` and fields I am adding are `Content (historical data)`. from panel I am passing `Revision ID` as context to view and in view I have contextual filter set as `Content revision: Nid`

Do I need to create two separate views display filtered by `Workbench moderation : current` and `Workbench moderation : published` and switch between them on basis of URL having draft or not?

# Answer
Make a clone of the view that workbench itself uses, and use that as a base to work from.
> 1 votes

# Answer
You need to use the 'Content revision' relationship on the field to get the correct link to the node.

Also make sure you have the correct relationship, there's two which both have the same name but are on different fields (nid and vid). There's an issue herethat descibes the naming problem of these two relationships. The one on the nid is the one to use as it brings in all of the revisions for each node.

Then you can add a filter to the view to only show the current state (Workbench moderation : current).
> 1 votes

---
Tags: views, panels, workbench
---


# Question
Title: How to make a reservation and a booking of seminars during the Commerce checkout process?
I have set up my first Drupal Commerce shop that works as it should with fixed booking ("selling") of seminars.

Now these seminars (realized as line items) must not only be booked ("sold") but must also be available for reservation. It is needed that booking and reservation has to be done during the checkout process, where only booked items must be paid.

My problem is now, that I do not know how to combine booking and reservation in one line item and also how to separate it during checkout process, as both need different information and also a variable amount of input fields, depending on number of participants.

Maybe someone can give me some hints how to do it - I am stuck at the moment ...

# Answer
> 1 votes
Your usage of the terms "booking" and "reservation" seems a bit strange to me. In the context of Drupal they are often used as synonyms of each other. I am not sure if I correctly interpret the difference you make, but I think this is crucial for you to differentiate (define?) them:

* **Booking** = item that must be payed at checkout time.
* **Reservation** = item that you must also be able to checkout, but you don't have to pay for it (or at least not yet).

So I think your question actually consists of 2 questions:

* How to integrate this in Drupal Commerce?
* How to ensure availability?

Below is what I think might help you find a possible solution.

# Drupal Commerce integration

You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).

Here are some more details about this distribution (quotes from its project page):

> ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
>
> It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts. Easy booking profile is powered by Drupal Rooms and Drupal Commerce \- widely used and popular contributed decisions, which means active maintaining and timely technical support.

# Check availability

Take a look at these modules, which all have a stable (not alfa or beta only) release:

1. Availability Calendars (Reported installs: 2.061 sites).
2. MERCI (Reported installs: 441 sites).
3. Resource Conflict (Reported installs: 329 sites).
4. Simple Reservation (Reported installs: 202 sites).
5. Room Reservations (Reported installs: 156 sites).

I've ordered the list above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.

---
Tags: 7, commerce, bookings
---


# Question
Title: List of content types posted/commented by users I follow
I'm running a D7 system Where users can follow each other using 'Follow' flag on user's profile.

Now I've been assigned a task to come up with a view where I can have a list of content posted/commented by people I follow.

I tried so many ways but no luck.

# Answer
I've achieved this with the help of contextual filter `content: nid` and then using custom php which is below

```
 global $user;
$flag_items = flag_get_flag_flagging_data('Your_flag_name');
foreach($flag_items as $flag_item){
 if($flag_item->uid == $user->uid){
   $uids[] = $flag_item->entity_id;
 }
}
$nids = '';
$result = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('uid', $uids, 'IN')
    ->execute();
while($record = $result->fetchAssoc()) {
  $nids .= $record['nid'] . '+';
}

$result = db_select('comment', 'c')
    ->fields('c', array('nid'))
    ->condition('uid', $uids, 'IN')
    ->execute();
while($record = $result->fetchAssoc()) {
  $nids .= $record['nid'] . '+';
}
$nids = trim($nids, '+');

return $nids;

```
> 0 votes

# Answer
Humm, I couldn't find a way to easily put them all together (comments and nodes authored by the users followed) but could create separate views.

For nodes created is easier: Create a new View, change from Show Content to Show Users and in the Relationship add a Flags: User flag, choose your flag and Current user.

For comments created: Create a new View, select Show Comments. In the Relationship add Comment: author to expose the Authors ID, select require this relationship. Add new Relationship, this time look for Flag: User flag, select the author's relationship created before and your flag.

As stated before, you might get all the content together but I couldn't get it in any easy way.
> 2 votes

---
Tags: 7, views, flags, users
---


title: How to save field data

text:
# Question
Title: How to save field data
I need to programmatically save field data (during node save I want to take the title & path alias and store it in a link field called `field_alternative_titles_title`).

Which functions can I use here? Do I use `field_attach_insert` or `hook_field_storage_pre_insert` to save the link field?

# Answer
At first you need to implement `hook_node_presave($node)`

> Act on a node being inserted or updated.
>
> This hook is invoked from node\_save() before the node is saved to the database. Parameters
>
> $node: The node that is being inserted or updated.

So it reacts when a node is going to be saved , then you have to check if the node type is the proper node type . then setting field value , so this is some code snippet :

```
function mymodule_node_presave($node) {
  if($node->type == "Your Node Type") {
      //dsm($node);//it will show the structure of node
      // as example
      $data = $node->title.'-'.drupal_get_path_alias('node/'$node->nid);
      $node->field_alternative_titles_title[$node->language][0]['value'] = "data";//check the node structure,this code wont work for sure
  }
}

```

of-course this is just an snippet , to make it work you have to know the structure of your content type , Devel module will help you , install and enable it so dsm function will work.
> 2 votes

---
Tags: 7, entities
---


title: How can I add a custom part to emails

text:
# Question
Title: How can I add a custom part to emails
How can I add create a multi-part email in D7? I need to add custom part to an email.

I am trying to use hook\_mail\_alter to append a new content type. The content type is Content-Type: text/calendar. I can't figure out where to add it in the $message array.

I have tried mimemail but it seems to disregard my SMTP settings.

# Answer
> 0 votes
You could use hook\_mail\_alter to alter the email message before sending it out. you could change or alter the email body, sender, attachments....etc as you wish

---
Tags: 7, emails
---


title: Using the t() function in Drupal 6

text:
# Question
Title: Using the t() function in Drupal 6
So I have used the t function correctly e.g. t('hello world') But I am not sure what else to do to get these strings translated. I tried looking at the hook\_locale documentation, but I wasn't sure what a group was. Could someone help me find some documentation that would help me understand what I need to do after adding the t function?

Thanks.

```
function my_module_block($op = 'list', $delta = 0, $edit = array()) {
    ...
    if ($op === 'view') {
    $content .= '<h2><span style="color: white;"><strong>' . t('my holiday') . '</strong></span></h2>';
    ...
    $content .= drupal_get_form('cool_form');
    $block['content'] = $content;
    return $block
}
}

```

EDIT: added some code. Is this enough code?

# Answer
> 1 votes
All you have to do is to Enable your proper language (using locale module) and then use translate interface (site building -\> translate interface) , and you can translate your string.

after that whenever t('hello world') is called , drupal checks for proper language , then checks if there is a translation for 'hello world' in that language , if true , then it will print translated string.

---
Tags: 6, i18n-l10n
---


title: Inject Link Using Rules->CustomPHP

text:
# Question
Title: Inject Link Using Rules->CustomPHP
Short version: I'd like to change what is displayed in a certain rendered Node field, if the viewing user meets certain conditions. I think the Rules action "Execute Custom PHP" can do this? But I have no experience with PHP.

Less short version: On the site, users read artistic content. A link at the top of the page gives them the option to buy said content. This should give them access to a .zip file that contains Goodies.

The node's Download field shows a link to go and buy the content. On page load, if the user owns the content (determined by a Rules condition), I want the link to be replaced with a download link. Ideally, the new link would be retrieved from a hidden field on the node.

Clever use of the "hidden" parameter could also achieve this effect, but I imagine the solution would look pretty similar. Or is this at all doable in the way I've described?

Pointers to solutions or alternatives would both be appreciated. Thanks!

# Answer
If anyone's interested in what I did here: this is best done using Views and Panels. Determining if a user owned a certain item required Views PHP. Once I got that working, it was pretty extensible, and I was able to implement some other displays based on it.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: How to pay with site credit in Commerce?
I would like to allow users to pay for products with site credit.

A field keeps track of how much credit a user has with us, and if they have enough of it to pay for an order they should have that option. Even better would be if they could dump the last bit of credit onto an order and pay the rest the regular way.

I have a few ideas; I'm just wondering if there's a standard or best practice in this situation. Thanks in advance.

Edit: Some of the ideas:

* Using Rules, add a payment method if the user has more credit than the order total. If this payment method is selected, no validation is needed. The user clicks through and credit is deducted.
* Add a checkbox to the checkout pane called ~"use site credit". If checked, subtract the user's credit from the price (up to the order total). This has the advantage that a user can pay with credit even if they don't have enough for the whole order, but seems much harder to do.
* At the calculate price stage, automatically subtract credit from the order appropriately. Add some notification informing the user that this has been done.

I may update this more as I explore options further

# Answer
you can use user-points module with Commerce userpoints. they work nice togather.
> 2 votes

---
Tags: commerce
---


# Question
Title: Database password changed and I am not able to access my site
I am using xampp for the hosting for my drupal site I started with no password for the database root, and I used this database in the installation process of my drupal site where user name is root with no password. Then I changed the password of the root from the xampp local host. Now I am not able to access my drupal site any more, and I don't no from where I can configure the password of the database for drupal. How can I solve this problem?

# Answer
You can edit settings.php (located in sites/default) to change database information like username and password.
> 0 votes

---
Tags: database, users
---


title: Acquia Drupal 6 Multisite

text:
# Question
Title: Acquia Drupal 6 Multisite
I am hosting an Acquia Drupal site on AWS:

I currently have 2 sites both located in the sites folder:

I am fairly new to working with Drupal Multi-sites and would like to know what is the best way to point to each folder's settings.php with this format and ignore the sites/default folder?

And if it would be simpler in another format what would you recommend?

Let me know if you have any questions.

Thanks!

# Answer
> 1 votes
Assuming you have your web server (Apache, etc) pointing both sites correctly to your docroot, then Drupal will automatically route requests to the correct folder (and settings file) for each domain.

If you want to have it ignore the default folder and its settings.php file, you can delete the existing "default/" folder and create a symbolic link to one of your other two sites. For example:

```
ln -s alumni.something.edu default

```

and all requests to your docroot that don't match a domain in your multisites folder will be sent to alumni.something.edu (or whatever you prefer).

---
Tags: multi-sites
---


title: Book outline in custom form

text:
# Question
Title: Book outline in custom form
I am creating a custom form which creates new nodes of type 'book'. I have been able to get the "book outline" to render on my form using

```
$nid = $node->nid ='nid';
module_load_include('inc', 'book', 'book.pages');
book_outline_form($form,$form_state,$node);
_book_add_form_elements($form,$form_state, $node);

```

My issue is when i select the drop-down for Book, it does not have "create a new book" as an option

Can someone help me with this issue? Has anyone experienced this before?

# Answer
> 1 votes
**I got it to work!** My issue was that `$nid = $node->nid ='nid'` should have been set to `$nid = $node->nid ='new'`.

I also added `module_load_include('inc', 'book', 'book.pages');` to call the function book\_outline\_form();

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


# Question
Title: What is the use of "Add view from template"?
As when we select the view options three links appears but I don't understand what is the use of "**Add view from template**"

because when we click on this link we get this one...

and after further proceeding normal view is created. so what is the use of that link?

# Answer
Modules give you some templates to work with instead of having to figure out the dirty details yourself.

For example:

You have the image module installed, so they give you a gallery template to work with. of course you're not obligated to use it but it's there.

If you download the Calendar module it will give you a bunch of templates as well.

There are several modules that give you templates to work with. And if you write your own custom modules, you to have access to create templates for users to use if you wish to.
> 2 votes

---
Tags: views
---


title: user_mail_tokens is undefined

text:
# Question
Title: user_mail_tokens is undefined
I keep getting an error in a site I am trying to work on, which is base don another. The error is in a custom module, and the code line is

```
if (!function_exists('user_mail_tokens'))
{
    include_once(drupal_get_path('module', 'modulename').'/modulename_e.inc');
 }

```

As I said this is a copy of another site, which runs. grep shows that the file \_e.inc doesn't exist in the other project, so I can only assume that the tokens are defined elsewhere. a Google search implies that the method is sttandard, so I don't want to create a new inf file that redefines it. So where should 'user\_mail\_tokens' be defined?

# Answer
> 1 votes
Matt - The `user_mail_tokens` is a function provided by the user module (Drupal 7 core). Essentially, what your code is saying is:

If the function `user_mail_tokens` exists (which it should because it's a core function, however these conditional checks are awesome and important), then we are going to include an include file located at /sites/all/modules/modulename/modulename\_e.inc.

As to why your code is throwing an error for `user_mail_tokens` that is an interesting question. I'm looking into it now. Part of me wonders if we should just say `module_exists`

What is the need to check the `user_mail_tokens`?

---
Tags: 7
---


# Question
Title: How to trigger module install file ad hoc
I am developing an install script for a custom module, but I can't figure out how to trigger the script once it has already been run once. I know that install scripts are by design intended to only be run once, but what do you do when you need to debug an install script?

I'm running Xdebug so I would prefer if I could trigger the script from the browser UI somehow as opposed to Drush, which will not pause for the debugger.

# Answer
You can do different things depending on your use case.

1. If you really need to test your install script again you need to uninstall your module rather than just disabling it. You can do that by running `drush dis mymodule && drush pm-uninstall mymodule` followed by `drush en mymodule` again. As @Clive mentions if you have the *Devel* module installed you can also `drush dre mymodule` (Devel reinstall). Or disable the module at http://example.com/admin/modules and then uninstall the module at http://example.com/admin/modules/uninstall . You should probably have a `hook_uninstall` function set up to clean up after your install. For example you may need to drop some tables or delete temporary files. See the link below for hook\_uninstall.
2. If you have an update to already the installed module you should use `hook_update_n` instead of `hook_install`. Then you can visit http://example.com/update.php or run `drush updb` Link below.
3. Lastly, you can probably change the database table that records the installation. I don't recall exactly how to do that but I don't think its preferable.

Here are the docs on writing *uninstall hooks*. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_uninstall/7

Here are the docs on writing *update hooks*. Basically the way I do it is make sure that `hook_install` runs the update functions after it runs itself. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_update\_N/7

eg:

```
/*
 * Implements hook_install
 */
function mymodule_install() {
// do some things

// then run the updates
    mymodule_update_7000();
    mymodule_update_7001();
}

/*
 * Implements hook_install
 */
function mymodule_update_7000() {
// do some other things
}

/*
 * Implements hook_install
 */
function mymodule_update_7001() {
// do some more things
}

```
> 3 votes

---
Tags: 7, installation
---


title: Omega template.php form alter

text:
# Question
Title: Omega template.php form alter
I'm trying to edit default user login block.

I successfully changed it by creating custom `block--user--login.tpl.php` inside `omega-starter/templates`, but I don't want to write whole block code. I only want to change certain fields.

I tried to use this code in `template.php` :

```
function omega_starter_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user-login-form') {
    //dpm($form);
    $form['actions']['submit']['#value'] = t("Custom login button!");
  }
}

```

It doesn't make any changes. Please suggest a solution.

# Answer
> 1 votes
Sorry I checked your code again and found the answer , change your code to this :

```
function omega_starter_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user_login_form') { //form ID was changed
    //dpm($form);
    $form['actions']['submit']['#value'] = t("Custom login button!");
  }
}

```

# Answer
> 0 votes
Just for other people dealing with such problem , we tried hard and finally the problem was found , there was a conflict between `block--user--login.tpl.php` and `template.php` . actually `block--user--login.tpl.php` was overriding the output . so one possible reasons in such situation is another function is conflicting the exiting . now how to understad? Theme Developer module could be one solution , this module tells you which functions are building an output , if you want to use it , its 7.x.1.12 version works fine (but still some problems) . check to see "How to find which templates are affecting a display?"

---
Tags: forms, theming
---