# Question
Title: users not able to post to discussion board
I have a simple forum in Drupal 6 that has 3 containers. From the admin perspective I can easily post a comment in either of the 3 containers. However authenticated users are unable to post to any container. The drop down box that allows you to select the container within the forum does not appear for authenticated users. I have attached a screen shot showing the difference between the two. Yes, user permissions are all turned on to enter content for the discussion board. Any suggestions on how to fix this issue?

# Answer
I don't have a Drupal 6 site handy to check this but the problem should be caused by either authenticated user permissions (global Drupal permissions) or if you are using field-specific permissions, that would also prevent a user from seeing that field. Please check what permissions authenticated user has for taxonomy related actions (I'm assuming you are using taxonomy to display forum containers?)
> 2 votes

---
Tags: nodes
---


# Question
Title: How do I hide the end date part of a Date field but not the time?
I have a content type that uses Date, it has a start date with time, and end date and can even repeat. But I need to hide the part of date that handles the end date and leave just the time, most events in this content type happen the same day, so that the user doesn't gets confused when making a new node of this particular content type. Any ideas?

# Answer
> 5 votes
To control the display of the date field, you need to do a few things:

1. **Add a date format** that will match your requirements, for example, display time only from the date. To do that, go to Configuration \> Regional and language \> Date and time \> tab Formats (/admin/config/regional/date-time/formats). Add a new format, for example, for time only, add g:i a
2. **Add a date type** (admin/config/regional/date-time) - for example, call it "Time only" and **use that new format** from #1 that was added (on the list of formats you should now see the time only value)
3. In your **content type, under Display tab, change the date field** to use that new date display "Time only". Optionally, if you want to change how the date is displayed in a View generated page, select that new date display in the date field display options.

# Answer
> 3 votes
Yeah, Drupal date fields just don't think this way. Maybe a better solution would be to only store the starting date and time in your date field, and then have a second field for the length of the event. Then a third field would compute the end time.

Or another approach might be to use Javascript to pre-populate the end time with the date from the start time.

# Answer
> 1 votes
Depending on how you're using the date field on other areas of your site, you could try splitting the date and time information into different fields. For example, you could have a single date field, a start time field, and an end time field. That would allow you to have more granular control over the display of each individual field. Granted, it would lock users into entering events that only spanned a single day (but the idea you proposed above will do that anyway).

If you need to keep your exact field configuration, you'll probably have to write a custom module to control the display of your end date field.

---
Tags: 7, nodes, datetime
---


# Question
Title: Create view containing all content containing taxonomy terms in free text?
I am using a taxonomy together with the Lexicon module to automatically create links to another website (a pretty neat solution with instructions here)

But I would also need to create view that list all nodes that contain the taxonomy terms. I am fairly competent at using the views module but I cannot figure out how to take the list of taxonomy terms and display all nodes that contain the terms in the text and what taxonomy terms the node contain.

# Answer
If I understand correctly, you want to have one page that will display nodes grouped by taxonomy term they belong to so that the result is like this:

* Term 1

+ article 1
    + article 2
* Term 2

+ article 2
    + article 3
* Term 3

+ article 1
    + article 3

To achieve that:

1. **Create a view** to display all content of \[content type name\] and select the node fields you want to display in place of article 1,2,3 (probably title of the node at least).
2. **Add relationship "Content: Taxonomy terms on node"** and decide which taxonomy you want to narrow down the display.
3. Under View field, there should be now a list of Taxonomy related fields. You probably want to **add field "Taxonomy term: Name"**. **Exclude that field from display**.
4. Under View format settings, select to **Group By that taxonomy field**.
> 6 votes

# Answer
If what you want is list all nodes that are referencing a taxonomy term, a way do to it is to:

* Create a Content view
* Add a contextual filter **Content: Has taxonomy term ID (with depth)**

This relationship also lets you display nodes that are not directly referencing the term, but referencing a term in the same tree: with the **depth** parameter.

You might need to add a *Relationship* of your term if you don't have access to the taxonomy term fields you want: **Content: Taxonomy terms on node**

Then to pass the *term ID* argument to the view, I usually use panels to override the taxonomy term page, but I believe you can directly do it with views, or a module like this one: Taxonomy Views Integrator.
> 1 votes

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


title: Add access code per page

text:
# Question
Title: Add access code per page
I need to create 10 or so pages that are linked in a specific order but can only be accessible when the user enters the correct access code.

The first page would be open and "unlocked" - but the user will need to enter some details before being able to see the next page, they would be presented with the access code for the 2nd page and this would be added to their user profile as their current access code level.

To see the next page, the user would require to enter a specific code to unlock that page.

How would I go about getting this to work? From what I know, webforms would be useful for "linking the pages in order" but I haven't found a way where you must enter a "password" access the next page of the form.

The idea is that the 10 pages would act as 10 different levels for a simple learning "game."

# Answer
> 0 votes
My first reaction would be to create 10 roles (Level 0 to 9) and to restrict access to the pages using Content Access to control access to the pages by role. Then use Rules to assign roles based on the tasks you set out in the learning game.

# Answer
> 0 votes
Another way that I was thinking about was to create a webform for each page. Then when the user submits - they would be redirected to the "next stage" node which would be hidden and only viewable when they've completed the webform for the next stage.

Thus: 10 webforms, 9 next stage nodes (or 9 variants to a page panel that use contextual links). Complete first webform -\> get redirected to next stage for "2nd webform" which would show the access code and URL for 2nd webform (which could be via contextual link too containing the access code).

Rules (and/or Trigger?) would be used to grant/disallow access using Content Access or similar modules - unsure if that would work in this case or if I can only grant based on specific role rather than just grant specific user access to node (or at least grant them the option to view if they provide the access code since anonymous users would be able to "play").

# Answer
> -1 votes
You could use workflow for this.

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.
>
> Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

---
Tags: webforms, users
---


# Question
Title: Dashboard is empty for roles apart from admin
I want to create a role specific dashboard on drupal 7. So I have added some blocks on the dashboard and also the "View dashboard" permission for this role. However,when I login using the above role,the dashboard is empty. What is the reason for this and how can I fix that? P.S.Admin can see these blocks on dashboard

# Answer
> 0 votes
May be you have assign blocks to the region of non admin theme. If so, you have to assign the blocks to the region of admin theme(seven or enabled admin theme in your drupal system).

---
Tags: dashboard
---


# Question
Title: Add percentage based fee/tax to specific product types on checkout
In Drupal 7 Commerce, I have two product types, a service product and a physical product. I would like a 6% fee added to all physical products only when the user gets to the cart review page. Ultimately it would be a custom line item like a sub-total or tax.

Currently I've been able to add another sales tax to produce this functionality, however the tax is being applied to all products, rather than calculating the 6% on only the physical products. I'm not sure if this can be done with Drupal Rules, or if I'd need to use hooks.

# Answer
> 0 votes
In the interest of anyone else who is looking for an answer to this, here is how I solved adding tax to only specific product types, based on comment #1 here: https://www.drupal.org/node/1251444

## Add elements to the rule applying tax to the line item

* Entity has field: Parameter: Entity: \[commerce-line-item\], Field: commerce\_product
* Data Comparison: Parameter: Data to compare: \[commerce-line-item:commerce-product:type\], Data value: YourProductType

Add OR/AND for more based on needs.

Hope this helps someone!

---
Tags: commerce, rules
---


# Question
Title: Node translation vs. Entity (field) translation
I would like to know what you guys recommend for a multilanguage site. For example, consider the following case: A page and its content should be available in 3 languages (e.g. German, English, and Spanish); the site uses one profile type, several content types and views, taxonomy, taxonomy-references, node references, user and field references, field collections, menues and so on. All of this informations should be translatable.

As far as I know, there are two ways to obtain this: with Entity Translation and the "node-based" method, or the usual one with the Internationalization modules and l10n.

What way should I choose? In which case and why should I consider a method instead of the other?

# Answer
> 8 votes
Randy Fay recently created a post discussing the possibilities achieved with of Entity Translations, where Gabor Hojtsy commented on some of the considerations to weigh:

> Some good things offered by \[good old\] node translation include support for separate node commenting (eg. your German and English comments will not be intermixed); support for per language revisions; publication workflows (eg. the German node can be in a pre-publication revision workflow while the English is already published, coordinated actions can publish multiple language versions when all reach a certain step in the workflow, etc); different permission handling (eg. certain people can only edit German translations not English originals), thanks to Drupal's excessive node access system, etc. Think about menus. Most sites do not plan to have 1-1 menu structures for all translated versions.

The major caveat as I see it for Content/Entity/field-level Translation right now boils down to that age old Drupalism special case: the node title... Its not really a field, so its not translatable without another module, and potentially some patch work. As of right now, I think field translation is still very much "experimental" ground, but more power to you for pushing forward into new territory.

# Answer
> 5 votes
Suzanne Kennedy and Florian Loretan's presentation at DrupalCon Denver addressed this question. It seems like entity translation is the way of the future and is at least partly slated for integration into core.

Their recommendation was to use entity translation unless you need support for revisioning.

# Answer
> 5 votes
I used Node translation but now after I tried Entity Translation, it's definitely my favorite one!

I think the main problem is the import function with Entity Translation, because there is a long discussion in the Drupal community. Otherwise I read about a new module, but I haven't tried it yet. But I will give you my feedback afterwards!

If you combine Entity Translation with the Title module, you can translate everything. I also prefer the module "Localization update".

So you have to install and enable these contributed modules:

And you have to enable these core modules:

* Locale.
* Content Translation.

Good Luck!

# Answer
> 2 votes
I know I'm raising the dead here but:

From what I can tell, the 6-style node translation method (each translation is a new node) is still the only useful way to translate content, having the benefits of being what everyone is used to and being functionally complete. (Node titles are not fields in 7, and therefore cannot be field-translated, among other silly shortcomings.)

You're always going to use i18n/locale, the only choice (which isn't really a choice) is node level or field-level translation, of which only node translation is likely to be useful.

Edit: Since this was written, Entity Translation + Title module have made field-level translation very effective. If you can use them, you should.

# Answer
> 1 votes
Entity translation makes much more sense in most cases than node translation; but sadly it isn't really a viable option for D7 as many modules still do not support it. People that do presentations and show how great it is simply are only doing very simple work. For example, something as common/popular as field collections is still not supported by ET.

When we start a new multilingual site we always start with ET since it is a great idea. We stick with it until we find too many issues with things not being compatible.. and then eventually we switch back to the old D6 method.

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


title: Re-importing photo from facebook

text:
# Question
Title: Re-importing photo from facebook
At the moment, the module fboauth imports the photo of the person from facebook and adds it as his/her profile picture, when configured to do so. Later on, when the person changes his/her profile picture, the photo will not be updated at the site because subsequent logins only imports fbuid.

How can the user re-import the photo (or any profile data for that matter) at a later point of time, and update it at the profile here?

Please consider guiding me in the right direction and I will try to come up with some code. Will the hook `fboauth_user_update()` work for this? Or should I do the trouble of fetching, saving to server, and editing the db, etc? Please help.

# Answer
> 1 votes
its better to use Facebook realtime update https://developers.facebook.com/docs/graph-api/real-time-updates/v2.2

create your callback to handle this and register it with real time updates

do the following in your callback

1- load user from facebook ID you get it in the posted from facebook

2- get the new image from facebook

3- replace it with the current image

4- save user

or you can forget about real time update and replace the image whenever user login

here the code you can use

1- Make your action by Implementing hook\_fboauth\_actions().

2- use hook\_user\_login to call the action you create which grab the photo and update it

Thats all

---
Tags: 7, social-network
---


# Question
Title: Entity Translation's Language Switcher (Content) is not showing
Before using Entity Translation, I used the `Language switcher (User interface text)` to allow the users to switch between languages on the header.

On the 'Configure entity translation' page, under the heading 'Enable a different language switcher', it states:

> When the Entity translation module is installed, a second language switcher block is made available on the site called Language switcher (Content). Enabling this block rather than the default language switcher block, Language switcher (User interface text), will ensure that the language of the content is updated when the language switcher is used.

However, when I place the 'Language switcher (Content)' block in the header, it does not even show up. Switching back to 'Language switcher (user interface)' shows it again, but then it won't ensure the language of the content is updated using the languages switcher.

# Answer
> 1 votes
Go to *Administration » Configuration » Regional and language » Languages » DETECTION AND SELECTION tab*. (`admin/config/regional/language/configure`)

Ensure that the **'URL'** option is enabled along with the **'Interface'** option.

From the guide:

> To ensure that the language switcher correctly updates the language of the site, the 'URL' method must also be enabled.

# Answer
> 3 votes
if you want to activate the *Language switcher* for User or for Content you have to go to:

```
../admin/config/regional/language

```

Use the second tab "Detection and selection" and activate for "Language switcher user" the first section:

* User interface text language detection - Enabled: YES

After that, you will see the language switcher.

For your "Language switcher content" you have to activate the other section:

* Content language detection - Enabled: YES

---
Tags: blocks, i18n-l10n
---


# Question
Title: Custom Views Filter - won't display as checkboxes
Trying to do a custom filter so that the user can select multiple states to filter the data by. This works (or will when I do some customizing to the query after) but it shows a select box. Any ideas? Tearing hair out :)

```
<?php
class custom_filters_handler_filter_state extends views_handler_filter_string{
  function value_form(&$form, &$form_state){
    $options = array(
     'DC' => 'DC',
     'MD' => 'MD',
     'VA' => 'VA',
    );
   $form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   );
return $form;
  }
}

```

# Answer
> 1 votes
I've the same issue, debugging the code I've seen that the exposed\_translate() method changes any checkboxes form types to select if $form\['#no\_convert'\] and #multiple are not set.

So you need to change it to:

```
$form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   '#no_convert' => TRUE,
);

```

Here is the code:

```
/**
   * Make some translations to a form item to make it more suitable to
   * exposing.
   */
  function exposed_translate(&$form, $type) {
    if (!isset($form['#type'])) {
      return;
    }

    if ($form['#type'] == 'radios') {
      $form['#type'] = 'select';
    }
    // Checkboxes don't work so well in exposed forms due to GET conversions.
    if ($form['#type'] == 'checkboxes') {
      if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
        $form['#type'] = 'select';
      }
      if (!empty($this->options['expose']['multiple'])) {
        $form['#multiple'] = TRUE;
      }
    }
    if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
      unset($form['#multiple']);
      $form['#size'] = NULL;
    }

    // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
    if ($form['#type'] == 'select') {
      $this->prepare_filter_select_options($form['#options']);
    }

    if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
      $any_label = variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('<Any>') : t('- Any -');
      $form['#options'] = array('All' => $any_label) + $form['#options'];
      $form['#default_value'] = 'All';
    }

    if (!empty($this->options['expose']['required'])) {
      $form['#required'] = TRUE;
    }
  }

```

# Answer
> 0 votes
In order to render select elements you should extend `views_handler_filter_in_operator` instead of `views_handler_filter_string`. I'm not aware of this, but it might be that `views_handler_filter_string` interferes with the value form in any way as to never allow multiple input or something like this.

Then, instead of defining the `value_form` on your own (which you can certainly do), you can also limit your impact and thus keep a certain configurability by overriding only the necessary class methods. In your case I would simple override `views_handler_filter_in_operator::get_value_options` like this:

```
function get_value_options() {
  if (isset($this->value_options)) {
    return;
  }
  $this->value_options = array(
    'DC' => 'DC',
    'MD' => 'MD',
    'VA' => 'VA',
  );
}

```

---
Tags: forms
---


# Question
Title: Routing multiple params / paths to single method
I'm attempting to create the following routing :

```
/app/{type}
/app/{type}.{format}
/app/{type}/{limit}
/app/{type}/{limit}.{format}

```

I would like all of these routes to route to a single method. Do I need to declare a route for each of the paths and params ? Does the ranking of the routes also matter ? e.g do I have to place

> /app/{type}.{format}

first before

> /app/{type}

?

# Answer
> 1 votes
Yes, you need to define a route for each path.

The order should not matter, it will put them all in the router table and then "order" them by the best match first.

---
Tags: 8, routes
---


# Question
Title: How to apply Simple Regex Filter to forum signature?
I'd like Simple Regex Filter to be applied to Signatures for Forums to close the loophole for human post spammers on my drupal 7 forum. How to achieve it?

# Answer
It's impossible without your own coding. Currently this module works only on nodes and comments, and this is hardcoded. Given that it is:

> Development status: Maintenance fixes only

you can't hope maintainers will add functionality; they already told they will not.

If you are using Signatures for Forums for Drupal 7, you can try with modules working generically on Entities. As far as I remember Rules could be used for something like that. For Drupal 6, I'm not prepared to even speculate.
> 2 votes

---
Tags: 7
---


# Question
Title: Using Gulp JS in multiple theme development
I use Gulp JS in my themes but the issue I'm having is we work on many themes in our drupal site (sometimes up to 40!).

I want to avoid repeating the same "node\_modules", "gulpfile.js" and "package.json" files in every single theme. If we want to change 1 of those files, we would have to update each file in every theme across all sites which is going to get too messy.

I would like to have the Gulp files live in sites/all/libraries and have gulp watch my theme that I'm working on.

To anyone experienced with Gulp, any idea's on how this can work?

Edit:

1. I have moved the 2 gulp files & node\_modules folder into /sites/all/libraries/gulp
2. I have edited gulp.js to point to the theme I'm working on, code is below (I have tried a few different combinations including an absolute path):

gulp.task('less', function() { gulp.src('../themes/theme\_name/css/style.less')

When I type gulp in the command line in my theme directory I get this error:

Local gulp not found in /var/www/site\_name/sites/all/themes/theme\_name

If I go into sites/all/libraries/gulp, type gulp in the command line, the gulp process starts, but if I edit a Less file and save it, gulp doesn't compile the css.

Thank You

# Answer
I have finally found the best solution for this so I'm posting it incase anyone has a similar issue:

1. Add gulp (package.json, gulpfile.js & node\_modules) to a centralized location (eg: sites/all/libraries/gulp)
2. In the root of each theme, create 3 symbolic links that point to gulpfile.js, package.json and node\_modules
> 1 votes

---
Tags: theming
---


# Question
Title: Unable to log in due to session cookies not being passed in
I have an html5 app which logs the user into drupal via services 3.11 but I am unable to connect.

Using the Chrome Postman plugin I can connect as expected. The difference between Postman and my code is that the cookie session is not being passed from my app. From what I have read the withCredential: true is supposed to pass the session cookie but it's not working for me?

1. api/user/login.json - Logs the user in as expected
2. api/user/token.json - returns the token as expected
3. api/system/connect.json - Always returns the data for Anonymous user 0

The system/connect code sent after login and token is:

```
                jQuery.ajax({
                    type: "POST",
                    url: connectUrl,
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (result) {
                        dosomething();
                    },
                    error: function (result) {
                        dosomething();
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-CSRF-Token', Session.user_token);
                    },
                });

```

# Answer
> 1 votes
For anyone else who stumbles across this problem I did finally manage to solve it with the following which ensures the credentials are pass for each call consistently. I'm assuming where CORS adds in the additional OPTIONS request, the credentials we're going through.

```
jQuery.support.cors = true;
    jQuery.ajaxSetup({
        xhrFields: {
            withCredentials: true   // Pass session cookie with requests
        }
    });

```

---
Tags: javascript, services, sessions, cookies
---


title: Use of relationships (joins) in Views

text:
# Question
Title: Use of relationships (joins) in Views
I use Drupal 7. I have read dozens of questions that revolve around the need to incorporate relationships among tables in Views (even many where the person asking the question phrased it differently, and the person answering the question said "just use Relations in Views"). I have also read various books that nearly always use single tables in example of pulling data from databases. I rarely see any understandable explanation of the use of "relations" in views. What's the point of using a relational database if it is so difficult to use joins? Can anyone shed any light on this? I've read the explanation in Pro Drupal 7 Development, which is arcane at best.

Bruce

# Answer
Views is an awesome query builder and formatter - all through the UI. In my past coding days I did that all manually and recently I started to appreciate the power of views.

Just go into views settings / basic and turn on "Show the SQL query". Then create a basic view of nodes. Now add fields and filters to see how the SQL changes. Add a relationship and you'll see how views adds the "SQL Joins" automatically.

When you add some "fields" it will automatically add some joins without you having to add relationships. For example add "last comment author" field to a node and views will automatically add:

```
INNER JOIN {node_comment_statistics} ...
LEFT JOIN {users} ....

```

When you want to add some fields that you don't see in the selection, for example "author of the node", you add the relationship "Content: Author - Relate content to the user who created it." Views adds the SQL:

```
INNER JOIN {users} ....

```

Now you'll have the user related fields available, for example "(author) User: Picture (Picture)".

So in summary: most views will pull data from multiple tables but most of that detail is hidden from the developers because views does it all for you. If you understand tables and SQL turn on the SQL output and see what views does. Sometimes all those "joins" are not optimal from an optimization standpoint ;-)
> 4 votes

# Answer
For future reference, quoting from https://www.acquia.com/blog/drupal-views-sql-analogy-easier-way-explain-views

The author explains:

> * SELECT {fields list } is in the Fields section. FROM {tables list} -
> * \[This is a bit complex in Views, the base table is determined when we
> * create a view - whether its node, users, terms, node revisions, files
> * etc\] INNER JOIN - is in the Advance Options \> Relationships section
> * in Views WHERE - is defined in the Filters & Contextual Filters
> * sections ORDER By - is determined by Sort Criteria
> 3 votes

# Answer
You can modify views query by using hook\_pre\_execute, i.e.

```
function mymodule_views_pre_execute(view &$view) {
  if ($view->name == 'view_to_modify') {
    $query = $view->build_info['query'];
    $count_query = $view->build_info['count_query'];
    $query->condition(...);
    $query->addJoin(...);
    $count_query->condition(...);
  }
}

```

for the default view plugin, $query is an instance of SelectQuery class, which allows easy modifications
> 2 votes

---
Tags: 7, views
---


title: how using mysql CAST in db_select

text:
# Question
Title: how using mysql CAST in db_select
I want to try doing Mysql Casting in my query by `db_select` but face to error,

```
$q=db_select('node','n');
          $q->join('field_data_field_cinema_type', 'fct', 'fct.entity_id = n.nid');
          $q->condition('n.type',array('movie'),'IN');
          $q->condition('fct.field_cinema_type_tid',11095,'=');
          $q->condition('cast(n.nid AS SIGNED )',11517,'>'); // also $q->condition('cast(n.nid AS SIGNED INTEGER )',11517,'>');
          $q->fields('n',array('nid','type'));
          ym((string)$q);
     $res= $q->orderBy('nid')->execute()->rowCount();

```

and query string

```
SELECT n.nid AS nid, n.type AS type FROM {node} n INNER JOIN {field_data_field_cinema_type} fct ON fct.entity_id = n.nid WHERE (n.type IN (:db_condition_placeholder_0)) AND (fct.field_cinema_type_tid = :db_condition_placeholder_1) AND (castn.nidASSIGNEDINTEGER > :db_condition_placeholder_2)

```

**My question is how can I use `Mysql Casting` in db\_select?Is that supported in db\_select or I should use db\_query on EntityQuery ?**

# Answer
> 2 votes
You can use the `where()` method for a `SelectQuery`:

```
...
$q->where('CAST(n.nid AS SIGNED) > :nid', array(':nid' => 11517));
...

```

So the choice is yours which type of query to use.

---
Tags: database
---


# Question
Title: How to display only one Commerce product variation in Views?
I have a view which displays the list of all Commerce Products on the site.

The problem is that it displays variations as separate products.

I've tried:

1. Enabling Views aggregating checkbox
2. Creating a new view which is based on nodes, instead of Commerce Products
3. Checking "Distinct" under "Query options"

However, neither of that worked. I'm not sure if I misconfigured these settings.

I suspect that it has to do something with aggregation/grouping but I can't figure it out for a couple of hours already :@

How can I limit the display of products to only *one* variation?

Thanks!

# Answer
Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.
> 4 votes

# Answer
You need to associate the product variants with a product display node and then create a view of the product display nodes. If you do this using display suite you then get the option to use display suite in the view (Format: Show: display suite). Doing it this way you don't need to use aggregation.
> 1 votes

---
Tags: 7, views, commerce
---


# Question
Title: Commerce + Views: Distinct on Referenced Product not working
I have a Product Display node view which ignores distinct on the query. The goal is to avoid displaying multiple product displays which refer to same Product SKU. I created a relation with the Referenced Product but this did not change anything.

# Answer
> 0 votes
Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.

---
Tags: 7, commerce, views
---


title: Dynamic css from node?

text:
# Question
Title: Dynamic css from node?
I like to implement this codepen into drupal but the images in the background should come from a ctype within Drupal.

The codepen example: http://codepen.io/AmeliaBR/pen/myPBNg

So basically how to get this line dynamic in a page?

```
article {
  background: url(https://foo.com/fooimage.jpg) no-repeat center;
}

```

Can you point me to the good direction? Is there a module which support this? What tags should I look?

# Answer
You could use:

```
// replace this with the url from the node object
$imgURL = 'https://foo.com/fooimage.jpg';
$style  = 'article {';
$style .= 'background: url(' . $img_url . ') no-repeat center;';
$style .= '}';
drupal_add_css($style, array('type' => 'inline'));

```

For the $img\_url though you need to fond out how to get the image url. You would need to load the node using node\_load() then use dsm() from the Devel module or just use print\_r() to display the field array.
> 0 votes

# Answer
I'm assuming by the "article" css that you want the background image on the on the markup which wraps the content in a node.tpl.php. You can add the style attribute directly to the attributes array in a node preprocess. This example also gets the path to a specific image style for control over the image.

This would go in your template.php with the proper names swapped out to pull in your specific image field and image style.

```
/*
 *
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function THEMENAME_preprocess_node(&$variables, $hook) {
  $type = $variables['type'];
  $view_mode = $variables['view_mode'];

  switch ($type) {
    case 'CONTENT_TYPE_MACHINE_NAME':
      // Ensure we only effect the node page
      if ($view_mode == 'full' && node_is_page($variables['node'])) {

         // Adjust to your specific image field.
         // This may be different apart from swapping field names.
         // Use Devel module and dpm($variables); to find your field's uri in the $variables array.
         $field_uri = $variables['FIELD_MACHINE_NAME'][0]['uri'];

        // Assuming you'll have an image style for it. Enter the machine name in here.
        $image_url = image_style_url('IMAGE_STYLE_MACHINE_NAME', $field_uri);
        $variables['attributes_array']['style'] = 'background-image: url(' . $image_url . ');background-repeat: no-repeat;';

      }
      break;
  }
}

```

The `switch` statement is for code readability should you preprocess other node types in the future. Just add another `case` & `break`.
> 0 votes

---
Tags: nodes, theming
---


# Question
Title: User email being deleted when submitting Profile 2 form
i'm debugging a site that I haven't made. The issue is that the users email address is being deleted.

I've found which form it's happening on; and by using hook\_form\_FORM\_ID\_alter I can see that $form has this information at before sending and not after it's been sent.

I've written a patch that writes it back in but my question is what the best way is to backtrace where the bug actually is. I'm using phpstorm as my IDE and have put breakpoints in modules I think could be at fault but without joy.

Any other tips on this one ?

Much appreciated.

# Answer
> 1 votes
You will have to check that **hook\_form\_FORM\_ID\_alter** and the **callbacks** inside that hook, at least at the end you can check if the **$form** still have all the previously data

# Answer
> 0 votes
Just to clarify the answer from DarkteK.

In the code multi versions of hook\_form\_FORM\_ID\_alter where being run. Its this I needed to search for.

Thanks.

---
Tags: forms, users, debugging
---


# Question
Title: Cygwin Drush throws error in Drupal folders
In my Windows machine I have installed Drush using Cygwin & PEAR. Though it runs fine when I run `drush`; shows me all the available commands but when I run any `drush` command inside a Drupal folder its throws me an error saying:

```
`require_once(d:/wamp/www/d7/modules/system/system.module): failed to open stream: No such file or directory drupal.inc:21                                                          [warning]
PHP Fatal error:  require_once(): Failed opening required 'd:/wamp/www/d7/modules/system/system.module' (include_path='.:/usr/share/pear') in /usr/share/pear/drush/includes/drupal.inc on line 21
require_once(d:/wamp/www/d7/modules/system/system.module): failed to open stream: No such file or directory drupal.inc:21                                                          [warning]
PHP Fatal error:  require_once(): Failed opening required 'd:/wamp/www/d7/modules/system/system.module' (include_path='.:/usr/share/pear') in /usr/share/pear/drush/includes/drupal.inc on line 21
`

```

Even tried creating a `symlink` in my www folder but still it doesn't work.

# Answer
This is a bug in Drush. It would be nice if someone was available to work on a fix; the solution more-or-less exists in the issue. Testing needed.
> 2 votes

---
Tags: drush
---


# Question
Title: How to theme a view that displays content from a relationship?
I have a page for `Organization`. Each organization has a `Featured Person` field which is an unlimited node reference to the `Person` content type. The organization can have many featured people. I also need to be able to customize the markup for each view-row and therein lies my problem.

I set up the view according to another question. The view is able to select and display the correct `Person` data only when **Show: Content**. AFAIK, this does not let me customize the markup for each row because the rendered markup is sent directly to the template.

If I change to **Show: Fields** in order to get more control over the theming, the view will display the fields related to the *organization*, not the *people* (since I am on an organization page, and the contextual filter is set to the organization id, I suppose).

How do I set up my view so I can display the relationship content (Featured People) and still customize the template for each row or people?

# Answer
With **Show: Field**, each individual field can be toggled to any of the relationships in the view. It is similar to **Show: Content** and **Show: Rendered Entity** except the dropdown list is buried one step further down.

Switch to **Show: Field**, and edit each field and set the dropdown list to the Featured Person relationship. Then, go about your theming just as you would with any other fields template.
> 0 votes

---
Tags: theming, views
---


# Question
Title: Flag a node but create a view of the nodes that reference it
We want our logged in users to be able to Flag/Follow our "Fisheries" content type nodes. Users can then create a "Catch" node in the Catches content type and use an entity reference field (Fisheries) to tag the Fishery in which it was caught.

I therefore want to be able to produce a view which shows what's being caught in the Fisheries that the user follows. If they follow 10 Fisheries the View would contain the latest catches from those 10 lakes in date order.

I can see what Fisheries the user is following with this View:

but I want to see what other content type nodes are referencing this node instead. I hope that makes sense!

# Answer
> 0 votes
You may use Entity View Attachement module. This module attaches a view to an object. this object may be a node, user , ... . Select the appropriate bundle and it works well

---
Tags: views, entities, flags
---


title: Custom view for Entityform submission

text:
# Question
Title: Custom view for Entityform submission
I have a simple Entityform where the user selects from a list of Profile2 user profiles (internal staff and external staff). In simpler terms, the user selects from a list of entities (ie. pick 3 from a list of 10).

The Profile2 user profiles are being shown on the form via an Entity reference view so you can see the name (from user profile), picture (from user profile), status (from Profile2 staff profile) etc. associated with the selected users.

Unfortunately, the submission confirmation and submission screens only show the entity name (User Profile) instead of the actual user profile details. Basically I see:

```
Submitted by There, Hello on Thu, 03/05/2015 - 10:53
Person Selection
External Staff
Internal Staff

```

What I want to show is:

```
(picture) Joe Schmoe, Washington
(picture) Alex Trebec, Montreal

```

Does anyone know how to alter the confirmation and submission pages to show more detail about the underlying Entity (and/or associated Entity)?

# Answer
> 0 votes
Here is what I would suggest.

1. Clone the built in View
2. In the Entityform Type edit form select your new View under Submission Views -\> View for submissions reports
3. In your new View add relationship to Profile2 entity via the Entity Reference field on the Entityform
4. Now you can add any field from the Profile2 to the View.

---
Tags: entities
---


# Question
Title: db_update without table prefix on custom table
I installed Drupal with table prefixes in the database. I have my own tables in the same database which I am trying to update. I am getting an error because Drupal is automatically adding the prefix "drupal\_" to the table I specified.

```
$key_cached_update = db_update('my_table')
  ->fields(array('key_cached' => $apikeyinfo->result->key['expires'],))
  ->condition('keyid', $row->keyid, '>=')
  ->execute();

```

> Base table or view not found: 1146 Table 'drupal\_my\_table' doesn't exist

I don't have problems with `db_query` to read the database.

# Answer
> 2 votes
In your settings.php file where you have prefix set in the $databases array. Change this

```
'prefix' => 'drupal_',

```

to this

```
'prefix' => array(
  'default' => 'drupal_',
  'my_table' => '',
),

```

If you want a more wildcard like way to do this you can set the target. So lets say this is what your $databases array looks like inside settings.php

```
$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
  ),
);

```

Change it to this, where everything is the same except the prefix is empty.

```
$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
    'noprefix' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Then in your function call do this

```
$key_cached_update = db_update('my_table', array('target' => 'noprefix'))
  ->fields(array('key_cached' => $apikeyinfo->result->key['expires'],))
  ->condition('keyid', $row->keyid, '>=')
  ->execute();

```

---
Tags: database
---


title: Drupal database connection

text:
# Question
Title: Drupal database connection
Is it necessary to connect to drupal database in order to fetch something from database? OR no if I have drupal installed so no need to make connection in any template file in order to fetch data?

# Answer
The database connection is handled elsewhere, you do not need to write a new connection function in your template file.

You can use this:
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_query/7
> 0 votes

# Answer
The easy answer is yes...Drupal uses a entity value attribute (EVA) data model which makes pulling tabular data directly from a MySQL client challenging at best.

You would be better off installing the feeds or Views data export module(s) to retreive the data you want and export as a CSV.
> 0 votes

# Answer
| I have drupal installed so no need to make connection in any template file in order to fetch data?

You should not be fetching data in template files, I highly recommend you instead create a small custom module and use either a theme\_hook or preprocess functions to push data in your templates. You really want to avoid having "logic" in templates.

You can query the DB with db\_query or any other Database api function in your custom module's code.
> 0 votes

---
Tags: database
---


title: fresh install drupal using drush

text:
# Question
Title: fresh install drupal using drush
I get an access denied on the front page with a fresh install using drush. I can get to the user page fine and login as admin. I read that it might be permissions. Not sure why be default its set like this though. Any thoughts?

Update:

Let me clarify what I need to understand. So previous deployments of drupal using drush I get a fully working site with permissions set correctly. Now I am not sure what is going on wrong but when I run

```
drush si standard (database info)

```

I get a freshly installed site with no permissions on the front page. Now I guess what I am trying to understand what is causing this using drush. From what I know and experienced drush si should install the site to a state in which drupal has permissions of anonymous set correct.

I can manipulate the database after deployment but I'd rather not do that if I can make it work with drush right away.

So what could be causing this issue? Am I using drush incorrectly when deploying it?

update: I think it was a timing issue between mysql and drupal. In any case this is solved.

# Answer
> 1 votes
It may just be your content permissions are not configured.

Go in your admin, people-\>permissions-\>node and look in the "View published Content" permission, make sure anonymous and authenticated user is checked.

---
Tags: drush
---


# Question
Title: How can I programmatically reorder active menu items?
I have an 'audience' menu which has 4 links. When a user visits one of these links, it becomes active, and I want to push it to the front of the menu item list. Outcomes would like like;

```
Pitchers | Catchers | Hitters | Coaches
Coaches (active) | Pitchers | Catchers | Hitters
Catchers (active) | Pitchers | Hitters | Coaches
Hitters (active) | Pitchers | Catchers | Coaches

```

How can I accomplish this programmatically? I can't seem to find the right theme\_ or hook\_ api function to pull this off.

I've tried this, and changing the '#original\_link' weight didn't seem to make a difference (note, I have other things going on here):

```
function apple_menu_link__menu_audience_gateway(&$vars) {
  $element = $vars['element'];
  $submenu = '';

  if($element['#original_link']['in_active_trail'] == TRUE) {
    $element['#original_link']['weight'] = 50;
  }

  if ($element['#below']) {
    unset($element['#below']['#theme_wrappers']);
    $submenu = '<ul class="nav">' . drupal_render($element['#below']) . '</ul>';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $submenu . '</li>';
}

```

Also, I'm using Panels, Panels Everywhere, Page Manager, and MiniPanels — this could inform the ultimate solution.

Thanks all.

# Answer
You need to use hook\_menu\_alter.

Make **sure** you declare the function with the & in front of items argument, this is what allows the function to modify the $items array passed to the function:

```
function MYMODULE_menu_alter(&$items)

```

In your function you can access every menu item in an array structure like so:

```
   $items['node/%/edit/schedulenew'] = array(
            'title' => 'Schedule1',
            'access callback'=>'user_access',
            'access arguments'=>array('view cssswitch'),
            'page callback' => 'cssswitch_schedule',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
            'weight'=>4,
        );

```

If you just redefine the 'weight' property, it will allow you to re-order your menus.

* Be sure to clear your cache after each menu changes, or go to the menu page, load the menu edit page and save it, this also rebuilds the menu.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: Views report for Ubercart Order product totals for date range?
I have been trying to create a view that will provide me with the total number of each product SKU ordered within a specified date range. Let's say there were three orders within the specified date range:

```
Order 101
Product ABC - Qty 1
Product XYZ - Qty 3

Order 102
Product ABC - Qty 1
Product XYZ - Qty 0

Order 103
Product ABC - Qty 10
Product XYZ - Qty 2

```

The View result would look something like this:

```
Total Number Ordered Per SKU for (date range)
Product ABC - 12
Product XYZ - 5

```

It is important for the results to be based on the SKU of the product, not the product title.

I have played around a bit with Views Aggregation on a "Type: Orders" view, but I am not knowledgeable enough to make it do what I need to do. Perhaps there is an easier way?

The purpose of this view will be to have an "at-a-glance" of which products need to be prepared for fulfillment, and how many of each, for the filtered date range.

Thanks!

# Answer
I found my answer. I used the Views Aggregator Plus module (https://www.drupal.org/project/views\_aggregator). I applied "Group and Compress" and "Tally Members" in the "Group Aggregation" column within the Views Aggregator Table options for the SKU field, and I applied "Sum" in the "Column Aggregation" column for the Quantity field. This provided me with the exact result I was looking for.
> 0 votes

---
Tags: 7, views, ubercart
---


# Question
Title: Display a View of Private Organic Groups for 'Requesting Access'
Right now I have it set up so groups are 'Private' in OG 7.2.x on D7

When using og\_extras there is a view that lists the 'Groups'. However, when they are set to private, because the og permissions module is enabled, the groups do not show when an anonymous user acceses the page.

With the correct permissions, non-members can request access to groups, and a URL like this will let users join a Private Group:

example.org/group/node/6469/subscribe

Now, the BIG QUESTION:

How can I get views to show the Group name, Group Description, 'Private', and 'Request Access links' in a public facing view, yet have the content/members of the group be private?

It seems like the idea of a 'Private Group' is that people can't even see the name of it. That assumption is irrelevant to my site, I just want them to not be able to access the groups homepage/content unless they are members, I want them to see the groups they 'could be a part of'.

Thanks! And apologies if this was too indirect.

# Answer
> 0 votes
Answer: edit the OG Extras Group view and do the following. Answer taken from here:https://drupal.stackexchange.com/a/865/2957

---

You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

> Disabling SQL rewriting will disable node\_access checks as well as other modules that implement hook\_db\_rewrite\_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.

---
Tags: views, organic-groups
---


# Question
Title: How can you add the ID to the content type fields?
All I see are classes, and from my understanding seems that there is nothing in the variables.

# Answer
> 3 votes
By default template\_preprocess\_field doesn't initialize the attributes array, so you don't see it when viewing the variables with the Devel module. You can achieve this and any other attributes by adding it in a template\_preprocess\_field() from your themes template.php file. When added it will get output to the field in template\_process\_field(). Here's a generic example of adding an attribute to a field. Swap all caps items for your use case...

```
/**
 * Implements hook_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  $content_type = $variables['element']['#bundle'];
  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];

  switch ($field_name) {
    // We make sure it only effects the correct field ...
    case 'FIELD_MACHINE_NAME':

      // ... and, assuming you want to limit the where an id is used, we only add on a certain content type's full node page.
      if ($view_mode === 'full' && $content_type === 'CONTENT_TYPE_MACHINE_NAME') {
          $variables['attributes_array']['id'] = 'my-id';
      }
      break;
  }
}

```

---
Tags: 7, theming, entities
---


# Question
Title: How to display a variable in callback hook_menu?
I'm creating a page with Hook\_menu and I would like to display the user agent that page. This is my code to generate my page.

```
/**
 * Implements hook_menu().
*/
function custom_module_menu() {
    $items = array();
    $items['custom_module'] = array(
        'title' => 'My Custom Module',
        'description' => t('Best Custom Module'),
        'page callback' => 'custom_module_back',
        'access arguments' => array('administer site configuration'),
    );
    return $items;
}

function custom_module_back(){
        $output =  array(
            'first_para' => array(
                '#type' => 'markup',
                '#markup' => '<p>Test</p> '
            ),
        );
        return $output;
    }

```

I try to set a variable like this `$user_agent = $_SERVER['HTTP_USER_AGENT'];` and then call it after the p tag.

Like this

```
function custom_module_back(){
            $output =  array(
                'first_para' => array(
                    '#type' => 'markup',
                    '#markup' => '<p>Test</p> ' $user_agent,
                ),
            );
            return $output;
        }

```

And this did not work.

How can I display a variable into a callback ?

# Answer
> 2 votes
Based on your code, it should be written as

```
$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '<p>Test</p> ' . $user_agent,
  ),
);

```

rather than

```
$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '<p>Test</p> ' $user_agent,
  ),
);

```

You need the period to concatenate the your string and variable.

**Edited - Full working module**

```
/**
 * Implements hook_menu().
 */
function testing_menu() {
  $items = array();
  $items['custom_module'] = array(
    'title' => 'My Custom Module',
    'description' => t('Best Custom Module'),
    'page callback' => 'testing_back',
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

function testing_back(){
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $output =  array(
    'first_para' => array(
      '#type' => 'markup',
      '#markup' => '<p>Test</p> ' . $user_agent,
    ),
  );
  return $output;
}

```

---
Tags: routes
---


# Question
Title: Add unlimited field collections in a from of drupal
I created a form in drupal for creating a new node. This content type has a field collection with 2 fields, name and amount.
I use the code below in form and add 5 field collections to form, but when submit the form, only the last field collection is saved in $form\_state\['values\] and 4 elements get lost.
How can I add unlimited field collections to a form by programming?

In my form:

```
module_load_include('inc', 'field_collection', 'field_collection.pages');
$form['cooking_type']['cooking_materials']  = array();
 for ($i=0;$i<5;$i++) {
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_cooking_materials'));
$form['cooking_type']['cooking_materials'][$i] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['cooking_type']['cooking_materials'][$i], $form_state);
}

```

in submit form:

```
$material_name= $form_state['values']['field_material_name']['und'][0]['value'];
$material_amount = $form_state['values']['field_material_amount']['und'][0]['value'];

```

# Answer
This is a working code that can be placed directly into your form function. Please see the comments too.

```
$node = new stdClass();
// Replace the value to the content type's machine name where you have added
// the field collection field
$node->type = 'CONTENT_TYPE';

// Prepare the field collection display array
$form['field_collection_display'] = array();

// Get the field collection field's info/structure and return it to the given variable
// w/c in our case is $form['field_collection_display']
field_attach_form('node', $node, $form['field_collection_display'], $form_state, NULL, array(
  'field_name' => 'FIELD_COLLECTION_FIELD_NAME'
));

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
);

return $form;

```

For the "Add another item" display, when you go the the field collection's content manage field settings page it says that the button will only display when it's set to 'Unlimited' w/c isn't your requirement. So you would need to add custom validations to this.

Since this is also custom coding, if you're having a hard time manipulating the field I would also recommend looking at doing the "field collection" functionality by yourself. This is the link https://api.drupal.org/api/examples/form\_example!form\_example.module/group/form\_example/7. You could go to the *form\_example\_tutorial\_9* directly if you want.
> 2 votes

# Answer
You can try this:

```
 module_load_include('inc', 'field_collection', 'field_collection.pages');
 $form['cooking_type']['cooking_materials'] = array();
 for ($i=0;     $i<5;$i++) {
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_cooking_materials'));
    $form['cooking_type']['cooking_materials'][$i] = array();
 }
 field_attach_form('field_collection_item', $field_collection_item, $form['cooking_type']['cooking_materials'], $form_state);

```
> 1 votes

---
Tags: entities
---


# Question
Title: Prevent redirect after submitting the form
In Drupal 7 profile2 module, want to make profile2 edit form to stay on the form itself after clicking SAVE button.

With the following code, it stays on the form itself and displays the values correctly. But it does not save actually. When coming back to the form, it still shows the previous values there.

So the following code makes the submitting to stay on the form itself but does not save the result into database.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'profile2_edit_main_form'){
    $form['actions']['submit']['#submit'][] ='custom_profile2_edit_submit';
  }
}

function custom_profile2_edit_submit($form, &$form_state) {
  unset($_GET['destination']);
  unset($_REQUEST['edit']['destination']);
  $form_state['rebuild'] = TRUE;
  $form_state['redirect'] = REDIRECT_URL;
  drupal_set_message('Changes were saved');
}

```

# Answer
> 0 votes
I have achieved to make the desired redirection like this:

```
function redirect_to_edit_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "page_article_node_form") {
        //$form['actions']['submit']['#submit'][] = '_redirect_to_edit';
        $form['#action'] = '?destination=node/' . $form['nid']['#value'] . '/edit';
    }
}

```

Reference: https://www.drupal.org/node/1074616#comment-5115792

---
Tags: 7, forms
---


# Question
Title: How to delete Content Type created through features
I was trying to use a project feature from openAid features based distribution. So I copied all the features from that distribution and required contrib and custom modules in my drupal installation.

Then I enable the project feature from admin/structure/features which enables few other features like resources and partners.

Any how I was unable to make it work as per my requirement so I deleted all three folders including the features, contrib and custom modules.

but the issue is that it has created three content types Project, Partners and there is no option to delete them.

Please let me know if there is a way to delete those content types which were created through the features which I have already deleted.

# Answer
> 2 votes
You may try the following code for getting the delete link (as we get delete link for the manually created content types) for the content types as created by the feature module:

```
<?php
/**
 * Implements hook_uninstall().
 */
function FEATURE_NAME_uninstall() {

  // List custom content types added by this feature.
  $custom_ctypes = array(
    'CONTENT_TYPE1',
    'CONTENT_TYPE2',
  );

  // Loop through each and unlock the content type.
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, `locked` = 0 WHERE `type` = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  // next to the content type created by the feature.
  drupal_flush_all_caches();
}
?>

```

After executing the above script, you will get the "delete" link as we get for the manually created content type and than you can delete the content type (created by feature module) from UI itself.

---

Another easy way to delete the content type: manually go to `/admin/structure/types/manage/"CONTENT_TYPE_NAME"/delete` it will delete it

Reference: https://drupal.org/node/1055460

# Answer
> 7 votes
Open the content type (for example: article) for editing which should bring you to a URL:

> admin/structure/types/manage/article

You can then append "/delete" into the URL like so:

> admin/structure/types/manage/article/delete

Which should open a form that will let you delete the content type. I don't know if this lets you delete ones that are coming from an active features package, but it definitely does help you delete obsolete content types from inactive features packages. So be careful

---

FYI, if you do this for multiple content types, don't open all the delete forms in multiple tabs and try to be clever by deleting several types at once. Bad things will happen :-p Make a backup and delete one content type at a time.

# Answer
> 0 votes
If you have devel installed, navigate to /devel/php and then node\_type\_delete($type) where $type is the machine name for the content type.

you have to execute the function no matter where,so devel is not required but yes will be a step less to have it.

# Answer
> 0 votes
Instead of trying to do it by custom, you could again install the feature module again and then trough the terminal first disable the module using

> drush dis module-name

and then uninstall the module using

> drush pm-uninstall module-name

This would help you to delete all the entries that the feature module created in your database.

# Answer
> 0 votes
The easiest thing to do (I think) is to use the admin\_menu module (https://www.drupal.org/project/admin\_menu). I already use this on most of my sites so it isn't an extra step for me.

With admin\_menu enabled, you can simply hover over structure \> content types \> any type and the delete link will appear.

I just tested this out by moving a content type and a view from one site to another via features. Disabled the feature but the content type was still there with no delete link. Used the admin menu to delete the content type. Worked fine.

---
Tags: nodes, features
---


title: Add class for a date field

text:
# Question
Title: Add class for a date field
I have a content type "Task" with a Date field to define a deadline for tasks. What I'm trying to do is to add an extra css class to the field wrapper to indicate that today is the deadline. I can do it with JQuery, but its stupid...

So i'd like create a function in my custom module which checks the field date, compares it with today date and if it results that today is a deadline (or the deadline already past), adds an extra class to the wrapper.

Will be very appreciate for any help or advice.

# Answer
this might be what are looking for Adding CSS Classes to Fields in Drupal

> Implementing any type of modular CSS requires fine grain control over classes in your HTML. In my last post, we looked at how we can easily add classes to blocks in Drupal using preprocess functions. Now let's apply the same technique to fields. Fields are a fundamental building block of any Drupal 7 site. Fields contain content and content is king. Before we dig in and start classing up our fields, let's look at how they are rendered to the screen.
> 0 votes

---
Tags: datetime
---


# Question
Title: Create Drupal 7 Multi Site on Mac OSX 10.10
I want to create a Drupal Multisite so I can share my theme and users between two sites. I want to set it up locally before I upload it on a webhost.

I am using Mac 10.10. However, many of the tutorials seem to be written for older versions of Mac OSX and don't work properly.

For example, this tutorial suggests the following:

Edit /etc/apache2/http.conf to add the following:

```
NameVirtualHost 127.0.0.1:80
<VirtualHost 127.0.0.1:80>
DocumentRoot /Users/YOURSITE/Sites/drupal
ServerName drupal1.localhost
</VirtualHost>

<VirtualHost 127.0.0.1:80>
DocumentRoot /Users/YOURSITE/Sites/drupal
ServerName drupal2.localhost
</VirtualHost>

```

Then edit /etc/hosts to add the following:

```
127.0.0.1     drupal1.localhost
127.0.0.1     drupal2.localhost

```

You can now find your site at: http://drupal1.localhost & http://drupal2.localhost

When I do this, I just get the message "It Works" I am unable to go to the Druapl installation page to start installing the site.

I've had a search for other tutorials, but they all seem to be written for MAMP.

How can I fix it, without using MAMP?

# Answer
> 2 votes
It sounds like you don't have your directories configured properly.

Assuming that you have this file structure:

```
/users/
    /drupal/
        /sites/
            /drupal1.localhost/
                /settings.php
            /drupal2.localhost/
                /settings.php

```

Note that the folders under /sites **must match the http.conf server name**. (unless alias's are set up).

With the above structure, your http.conf would look like this:

```
DocumentRoot "/users/drupal"

<Directory "/users/drupal">
    AllowOverride All
</directory>

NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal1.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal2.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

```

Note that the document root points to the base Drupal folder, not /sites. Drupal will handle this part automatically.

Your hosts file would remain the same:

```
127.0.0.1     drupal1.localhost
127.0.0.1     drupal2.localhost

```

---
Tags: multi-sites, installation
---


# Question
Title: How to convert an existing field from Text to Link in Drupal 7
If I have a field in Drupal which of type Text, how do I convert it to to allow a link if the field is already being used on the site without losing data?

# Answer
1. Install the Link module in order to allow link fields.
2. In your database, run:

`UPDATE field_config set type='link_field', module='link' WHERE field_name='YOUR_FIELD_ID'`
3. Then run the following query:

`UPDATE field_config_instance SET data='a:7:{s:5:"label";s:LENGTH_OF_YOUR_FIELD_NAME:"YOUR_FIELD_NAME";s:6:"widget";a:5:{s:6:"weight";s:1:"9";s:4:"type";s:10:"link_field";s:6:"module";s:4:"link";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:10:{s:12:"validate_url";i:1;s:3:"url";i:0;s:5:"title";s:8:"optional";s:11:"title_value";s:0:"";s:15:"title_maxlength";s:3:"128";s:13:"enable_tokens";i:1;s:7:"display";a:1:{s:10:"url_cutoff";s:2:"80";}s:10:"attributes";a:5:{s:6:"target";s:6:"_blank";s:3:"rel";s:0:"";s:5:"class";s:0:"";s:18:"configurable_title";i:0;s:5:"title";s:0:"";}s:10:"rel_remove";s:7:"default";s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:12:"link_default";s:8:"settings";a:0:{}s:6:"module";s:4:"link";s:6:"weight";i:16;}}s:8:"required";i:0;s:11:"description";s:0:"";s:13:"default_value";N;}' WHERE field_name='YOUR_FIELD_ID'`
4. (optional) Go into the table for your field name (field\_data\_field\_YOUR\_FIELD\_NAME) and remove the column field\_YOUR\_FIELD\_NAME\_format
5. In the same table as #4 above, change the column field\_YOUR\_FIELD\_NAME\_value to field\_YOUR\_FIELD\_NAME\_title. This will make the previous values for these text fields now become the title of any links placed in the new Link field.
6. In the same table as #4 above, add the columns `field_YOUR_FIELD_NAME_url VARCHAR(2048) ALLOW NULL`, and `field_YOUR_FIELD_NAME_attributes MEDIUMTEXT ALLOW NULL`

This solution worked well for me.
> 4 votes

# Answer
This is a dynamic Views solution which i believe can do the job quickly for present and new text fields:

You can attach an EVA field views display to the nodes of the content type containing that field. In this views display you'll add the text field and then output it as a link within the replacement patterns option. After that i recommend to use Display Suite (although not mandatory-you can do most of this out of the box also) to put this field anywhere in the node layout and hide the original text field.
> 0 votes

# Answer
While I subscribe to the first answer, I also want to add an alternative. Create a template for your field, and pass the output though l() function which formats an internal or external URL link as an HTML anchor tag.
> 0 votes

# Answer
You can use 'word link' module in Drupal to convert text to link while editing articles. This page has more info on this module - http://www.drupalasisee.com/word-link
> 0 votes

# Answer
https://drupal.org/project/node\_convert is another option - create a new template, add an action and use views bulk operation to convert them all..
> -1 votes

---
Tags: entities
---


title: Two-way Entity Reference?

text:
# Question
Title: Two-way Entity Reference?
I'm building a site for a school, with several content types:

* A **Class** holds the general info about a class: description, tuition, etc. One field in the Class type is an Entity Reference for an Instructor.
* An **Instructor** is the teacher of a Class.

When adding a new Class, the user will add an Instructor using the Entity Reference field (as an "autocomplete" widget). However, I also want the list of Instructors to link to the Classes each one teaches. How do I do this without having to enter the data on both the Class page *and* the Instructors page?

# Answer
Actually found a great tutorial which explains in detail how to do this: Using Views Contextual Filter and Relationship to display reference on referenced node.

Now, I have another, related, question: What if I want to include the Classes taught by the Instructor on the "list of instructors" page (which is a View)?
> 0 votes

---
Tags: entities
---


title: Basic Password Reset steps not working

text:
# Question
Title: Basic Password Reset steps not working
I have reviewed other similar posts, but none matches my problem.

I built a Drupal site based on an old ASP.NET site. I imported the users from the old DB (which had passwords in plain text!). Most users have been able to log in fine, using their old username (email addresses) and passwords.

But a few users are having trouble logging in. In some cases they forgot their password from the old site.

So they request a new password on the login page, get the email with the one-time login link, use it to change their password, but they can't login again using the new password.

## What I have done to test / fix

* tried resetting password myself in a testing account I set up a couple months ago:

+ got reset password email link
    + made sure I was logged out on the site
    + user emailed link to get into the account
    + entered new password
    + logged out and then couldn't log in again with the password I just entered ("`Sorry, unrecognized username or password. Have you forgotten your password?`")
* tried using a different browser, flushed cookies and cache, all to no avail. I cannot seem to login to this account EXCEPT by requesting a password reset email and using the link in that. But if I log out, I cannot log in again.
* installed Password Reset Landing Page (https://www.drupal.org/project/prlp). This moved the password resetting to the page you land on from the email link, but it didn't solve the problem.
* I also just tried making a different **brand new testing account**, asking for a password reset, resetting as before. **This time it worked**. No idea why it works with this new account but not with the other, older testing account. To be clear, the old testing account *still* doesn't work following the same steps that worked for the **new** account.
* I monitored the user table in the DB. The password is being changed, but system doesn't recognize the newly entered password.

Is there anything I can post here to get help investigating this?

# Answer
Tried to reproduce this but wasn't able to make it. Below is my process.

**no prlp module**

1. created new user with notify email
2. used onetime login link
3. changed password
4. logged out
5. logged in using the new password. *SUCCESS*

**with prlp module**

1. request new password
2. used onetime login link
3. changed password in the one time login page. *SUCCESS*
4. logged out
5. logged in using the new password

5.1. using username 'asd'. *SUCCESS*

5.2. using email 'asd@asd.com'. *FAIL (not relevant)*

**enabled logintoboggan (to use email as login)**

1. login using email and new password. *SUCCESS*
2. logout
3. request new password
4. used one time login link
5. changed password in the one time login page. *SUCCESS*
6. logged out
7. logged in using the new password

7.1. using username 'asd'. *SUCCESS*

7.2. using email 'asd@asd.com'. *SUCCESS*

Anything you'd like to add or to test?
> 0 votes

---
Tags: users
---


# Question
Title: Is vbo respect the order set by view while performing operation? or is there a way to tell it to perform in same order as result
In a simple vbo I needed to set field\_serial\_no to row no of view's result. By default view result is ordered by title in ascending and order cannot be modified (not exposed to user).
When these entities are passed to VBO, will it be aware of order of entities always? if yes I can directly access the index and save it in field\_no. I not is there any method?

# Answer
> 0 votes
It actually depends an the specific action. VBO gives the data in the same order as the view. But the action can rearrange the id's. Although most just process it the way they got it.

---
Tags: views
---


# Question
Title: Post to anonymous user's Facebook Wall with rules
I wonder what is the best way to implement post to User's wall for anonymous users. All solutions I came across seem to require creation of a Drupal User Account (using FB Connect) first.

I need a rules action that automatically asks for permission to post and then posts immediately, without creating a Drupal User Account, fetching any additional information and especially without requiring the user to connect manually in advance.

Thank you for suggestions!

# Answer
You didn't say what have you tried, so how can we know if we're suggesting some new solution? Anyway you could try Facebook Autopost https://www.drupal.org/project/fb\_autopost if it isn't on you personal "All solutions I came across" list
> 0 votes

---
Tags: rules, social-network
---


# Question
Title: The %element-title is using the following invalid tokens
I have defined few tokens that are grouped in few separate groups similar to `[node:content-type:name]` scheme. For example I'd like to have a token like `[master:sub_group_1:tokan_A]`. So This is how `hook_token_info()` looks like:

```
function MY_MODULE_token_info() {
  $tokens = array();
  $types = array();

  $types['master'] = array(
    'name' => 'Master group',
    'description' => 'This is the master group',
  );

  $types['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => 'This is the first sub group',
    // this tells this group that it's parent is 'master' group.
    'needs-data' => 'master',
  );

  $tokens['sub_group_1']['token_A'] = array(
    'name' => 'Token A',
    'description' => 'This token prints letter A',
  );

  return array(
    'types' => $types,
    'tokens' => $tokens,
  );
}

```

I'll skip `MY_MODULE_tokens()` as it's irrelevant here, but `token_replace()` works perfectly. It replaces `[master:sub_group_1:token_A]` correctly. But the problem is that `token` module does not list my custom tokens in *available tokens* section and when I try to use `[master:sub_group_1:token_A]` in forms that get validated by `token` module, I get `The %element-title is using the following invalid tokens` error message.

What is the correct method to define custom tokens and group them to avoid conflicts with tokens defined by other modules?

# Answer
It seems that in order to nest those tokens a "dummy" token is needed that matches group name:

```
function MY_MODULE_token_info() {
  $tokens = array();
  $types = array();

  $types['master'] = array(
    'name' => 'Master group',
    'description' => 'This is the master group',
  );

  // This is needed in order to nest tokens:
  // a dummy token that is the same as nested group/type
  $tokens['master']['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => '1st tokens group',
    'type' => 'sub_group_1',
  );

  $types['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => 'This is the first sub group',
    // this tells this group that it's parent is 'master' group.
    'needs-data' => 'master',
  );

  $tokens['sub_group_1']['token_A'] = array(
    'name' => 'Token A',
    'description' => 'This token prints letter A',
  );

  return array(
    'types' => $types,
    'tokens' => $tokens,
  );
}

```
> 0 votes

---
Tags: 7, tokens
---


title: Store array values in schema field

text:
# Question
Title: Store array values in schema field
I am creating a configuration entity for a module and in my config/schema.yml has as field as,

```
mymodule.connection.* :
  type: config_entity
  label: SSO connection
  mapping:
    name:
      type: label
      label: 'Name'
    id:
      type: string
      label: 'Machine name'
    url:
      type: string
      label: 'URL of the endpoint'
    consumerSettings:
      type: text
      label: 'Advanced storage for Consumer like key and secret'

```

In my Entity class I have written the following,

```
class SSOConnectionEntity extends ConfigEntityBase implements SSOConnectionInterface {
  /**
   * The connector machine name.
   *
   * @var string
   */
  protected $id;

  /**
   * The name of the connection.
   *
   * @var string
   */
  protected $name;

  /**
   * OAuth consumer id.
   *
   * @var integer
   */
  protected $cid;

  /**
   * URL endpoint of the connection provider.
   *
   * @var string
   */
  protected $url;

  /**
   * Serialized consumer settings for a connection.
   *
   * @var array
   */
  protected $consumerSettings = array();
}

```

And in the add-form,

```
class SSOConnectionFormBase extends EntityForm {
  /**
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQueryFactory;

  /**
   * Construct the SSOConnection base form.
   *
   * @param \Drupal\Core\Entity\Query\QueryFactory $query_factory
   */
  public function __construct(QueryFactory $query_factory) {
    $this->entityQueryFactory = $query_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity.query'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ssoconnection_configure';
  }

  /**
   * Builds the default form to add/edit connections.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param FormStateInterface $form_state
   *   An associative array containing the current state of the form.
   *
   * @return array
   *   An associative array containing the connection add/edit form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    // Get the entity.
    $connection = $this->entity;

    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Connection title'),
      '#maxlength' => 255,
      '#size' => 60,
      '#default_value' => '',
      '#required' => TRUE,
    );
    // The unique machine name of the connection.
    $form['id'] = array(
      '#type' => 'machine_name',
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#default_value' => '',
      '#disabled' => !$connection->isNew(),
      '#machine_name' => array(
        'source' => array('name'),
        'exists' => 'sso_connection_load'
      ),
    );

    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Base URL'),
      '#maxlength' => 255,
      '#size' => 60,
      '#default_value' => '',
      '#required' => TRUE,
    );

    $form['key'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Consumer Key'),
      '#maxlength' => 255,
      '#size' => 60,
      '#default_value' => '',
      '#required' => TRUE,
    );

    $form['secret'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Consumer Secret'),
      '#maxlength' => 255,
      '#size' => 60,
      '#default_value' => '',
      '#required' => TRUE,
    );

    // @todo: The advanced settings and field mappings.

    return $form;
  }

  public function save(array $form, FormStateInterface $form_state) {
    $connection = $this->entity;

    $status = $connection->save();
  }
}

```

Now I want to save the 2 fields values (key & secret) to the single schema "consumerSettings". How can I do that, the simple $entity-\>save() is not doing it. What is needed to be changed? FYI, I saw the cheatsheet http://hojtsy.hu/files/ConfigSchemaCheatSheet1.3.pdf but not getting it to work properly. Please help.

Thanks!

# Answer
> 3 votes
Don't serialize.

It's a config entity, there is no need for a config entity to have a flat structure. Instead, use type mapping with sub-keys.

To actually get your values that way in the config entity, the easiest way is to have the same structure in the form, with #tree =\> TRUE. Or you can set the values in the buildEntity method.

---
Tags: 8
---


title: Send a form to twig template

text:
# Question
Title: Send a form to twig template
How I can pass a form to twig template in Drupal 8?

For example, I get this:

a form: mymodule/src/Form/MyForm.php

Then on my Controller:

```
public function myController() {

    ??????

    return [
        '#theme' => 'mytemplate',
        ??????
        ];
}

```

mytemplate.html.twig

```
{{ ????? }}

```

# Answer
> 17 votes
Well, I did it, for anyone that needs this:

```
public function pageAction() {
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  // If you want modify the form:
  $myform['field']['#value'] = 'From my controller';

  $build = [
    '#theme' => 'mytemplate'
    '#form' => $myform,
  ];
}

```

In twig:

```
{{ form }}

```

---
Tags: entities, 8, theming
---


# Question
Title: How to print out usernames using EntityFieldQuery
I'm trying to filter users using entityfieldquery (type 'user') by fieldConditions, but I don't know how to print out the usernames on a page. If I use "print\_r", it works. But I don't want to print them out on a white page. ^^ If I use $output, I get only one name. For nodes, there is a function "node\_view\_multiple" to use it like `$output = node_view_multiple($nodes);` Is there also a way for entity\_type user?

Here is my code:

```
global $user;
$angemeldeter_user = user_load($user->uid);
$alter = $angemeldeter_user->field_alter['und'][0]['value'];
$alter_faktor = 4;
$alter_untergrenze = $alter - $alter_faktor;
$alter_obergrenze = $alter + $alter_faktor;

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->fieldCondition('field_alter', 'value', array($alter_untergrenze, $alter_obergrenze), 'BETWEEN');
$result = $query->execute();

if (isset($result['user'])){
global $user;
$angemeldeter_user = user_load($user->uid);
$users=user_load_multiple(array_keys($result['user']));
dpm($users);

foreach($users as $value) {
  $user_list = (array)$value;
  $users[$user_list['uid']] = $user_list['name'];
  $output = '';
  $output .= $user_list['name'];
  return $output;
  }
  }
  else{
    $hihi = 'no results';
    return $hihi;
  }
}

```

# Answer
Since user\_load\_multiple() returns an array of user objects you need to use the '-\>' in order to access them.

```
$output = '';
foreach ($users as $key => $value) {
  $output .= "index: $key; name: $value->name<br />";
}
return $output;

```
> 1 votes

---
Tags: database
---


title: how do i install drupal with drush

text:
# Question
Title: how do i install drupal with drush
First off, I'm a drush newbie, just installed it and now I want to install drupal on my server, so I did a
`drush dl drupal --drupal-project-rename=Quaaout`
and next I want to do a
`drush si standard --db-url='mysql://quaaout:PASS@localhost' --site-name=Quaaout`
but I keep getting
`ERROR 1044 (42000) at line 1: Access denied for user 'quaaout'@'localhost' to database 'information_schema'`
even tho I can login on the shell with
`mysql -u quaaout -p`
just fine when entering my password and also a `show databases` shows me the existing `information_schema` db. Why does it not let me proceed?
I'm on GoDaddy shared hosting with this.

# Answer
> 2 votes
You'll need to create a database first:

```
mysql -u quaaout -p
create database quaaout;

```

Then you can continue your drush install adding a db name after localhost:

```
drush si standard --db-url=mysql://quaaout:PASS@localhost/quaaout --site-name=Quaaout

```

---
Tags: drush, users, database, installation
---


# Question
Title: Can a module install a content type optionally or conditionally?
I have a module which installs a number of different custom content types, each defined in a .yml file in config/install/.

I install my module, and the content type appears and works normally, and I used them to create content.

I was doing some other development that required me to uninstall and reinstall this module. It uninstalled with no problem, and I did not lose any of the content built on the module's content types.

However, the module could not be reinstalled. When I tried, I got the error message:

> Unable to install CustomModule, node.type.custom\_node\_type\_one, node.type.custom\_node\_type\_two already exist in active configuration.

where custom\_node\_type\_one and custom\_node\_type\_two are the content types installed by my theme.

This seems like a potentially serious problem. My module defines blocks that appear on nodes using these custom content types, but they also may contain independent content. If the module is uninstalled for any reason, I don't want to force the site admin to wipe all of that content--but I also don't want the site to be blocked from reinstalling the module.

Is there a way in Drupal 8 to make the installation of a content type conditional, so that the module can be uninstalled and reinstalled without having to first delete all of the site's custom content?

# Answer
> 3 votes
Don't install a module when its default configuration has unmet dependencies adds a config/optional folder, which silently ignores configuration that already exists.

config/optional can contain configuration that will only be installed if the required dependencies of those config entities are met, for example a default view that would only be installed if views is enabled and is not required for the module.

---
Tags: nodes, 8, installation, configuration
---


# Question
Title: How to redirect to www without editing .htaccess file?
What alternative methods are there for redirecting all page requests to the www version of a domain?

I know how to eidt the root .htaccess file but find that this method does not survive core updates.

Is there another way? Perhaps with a module?

# Answer
It's always going to be better to do this with .htaccess, or in other web server config, but if you need to do it in php, put this at the top of settings.php:

```
if ($_SERVER['HTTP_HOST'] == 'example.com') {
  header('Location:http://www.example.com' . $_SERVER['REQUEST_URI']);
  exit();
}

```
> 3 votes

# Answer
instead of looking any module, i advice to add www in your CNAME record at your domain control panel.
> 0 votes

# Answer
I have two domains one of which I was using for development and the other was functional. I simply put a redirection in Index.php to redirect for the one domain.
> 0 votes

# Answer
You can change this behavior in your domain controller section of your cPanel
> -1 votes

---
Tags: redirection
---


# Question
Title: MSSql or SQL Server Wrapper for custom module?
I'm writing a custom module and I need to access data that is currently stored in an MSSql database. It would be great if I could use the built-in database abstraction layer, but obviously that isn't possible.

Are there any modules or resources that provide a similar abstraction layer for MSSql?

If not, how would I go about writing my own? I feel very badly about just putting the connection and query strings directly in the module, it seems so.. antiquated.

# Answer
> 4 votes
Since you didn't specify a Drupal version, I'll try to answer for both Drupal 6 and 7.

## Drupal 7

See http://drupal.org/project/sqlsrv

## Drupal 6

Even if there would be SQL Server integration in the official db-api, it wouldn't help you much because with Drupal 6, you can only connect to multiple databases of the same type. This is why https://github.com/dereine/views\_pgsql was created for example.

However, it might be an option to use the DBTNG project, which is a backport of the new Drupal 7 database abstraction layer and use that in combination with the sqlsrv project. I haven't tested that but it could work. And if not, maybe with a few changes (which you could contribute back)

# Answer
> 1 votes
Module Forena is another alternative to consider. It can be used to query (not update) any MS SQL database. For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here are some variations of the **MS SQL database** part in the questions:

1. Using a **SQLite** instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
2. Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.

---
Tags: 7, database
---


title: Using contextual filter in view

text:
# Question
Title: Using contextual filter in view
All,

I have been reading and experimenting, but have not been able to achieve the desired result - please offer some guidance.

My site has two content types: meeting and presenter. At each meeting, there are zero, one, or two presenters. Content type Meeting has a field type of Node reference whose 'number of values' is set to 2. When a Meeting content item is created, it is very simple to link the associated presenter.

The challenge is properly configuring the view. I would like to show each meeting's presenter(s) with the meeting information, whether I am showing just next month's meeting or an archive of past meetings.

I created a view based on Content type Meeting and created a relationship to the linked Presenter (by checking the box Content: Presenter (field\_presenter\_ref)). Where I am getting stuck, I think, is with the contextual filter. Based on my reading, I should be using Content: NID, but this does not seem to be doing anything for me. Specifically, if I remove date filters, the View shows all presenters from all meetings, not just the one associated with a specific meeting.

Looking forward to learning how to do this correctly - thanks.

# Answer
> 0 votes
In my opinion it's not necessary to add the relationship. When you have added the presenters in the Meeting node by use the node reference. You can just add the Presenters field (node reference field) in the Field section of the view without using relationship. Because the node reference is already taking care of the relationship part.

Does this help in any way? Let me know.

---
Tags: views
---