# Question
Title: How can I alter the title of a node upon save?
I want to automatically set the title of nodes with content type **ABC** to the node ID. (I want to hide the title field from the form in the UI, and I don't care about titles for this content type.)

For now, I am putting in dummy data (Title and Body) to test this.

At first I tried hook\_ENTITY\_TYPE\_presave():

```
/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'ABC') {
    $entity->setTitle($entity->id());
  }
}

```

However, this fails because the entity ID has not yet been assigned. So next I tried hook\_ENTITY\_TYPE\_insert():

```
/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'ABC') {
    $entity->setTitle($entity->id());
  }
}

```

This does not result in an error, and I get the status message *ABC 23 has been created.* However, the node title shows the dummy title I entered, not the node ID. I tried to fix this by adding `$entity->save()` to the `insert()` hook, but this results in a *duplicate key* error.

How can I change the node title to the node ID upon saving the node for the first time?

# Answer
I'm not sure why exactly you need the ID, if you don't care about it, wouldn't the date or something like that suffice too?

If you really want the ID, then you need both hooks, because you can't save the node without a title. So you need to set a dummy title in presave and update it again in insert. I'm not sure why saving there didn't work for you, it should, I've done similar things. If you provide the full exception message and stack trace, maybe I can help figure it out. Note that by default the sql content entity storage catches the thrown exception and re-throws a different one and our exception handling can't handle that. You need to print out the original exception stack trace where that happens, with `print $e->getTraceAsString()`.
> 2 votes

# Answer
* alter your contenty form, using hook\_form\_alter.
* print(form); there.
* you will be able to find the title, like form\['title'\] .
* you can set your title there.
> -1 votes

---
Tags: nodes, hooks, 8
---


# Question
Title: How can I create multiple chatrooms using the Drupalchat module?
I want to create multiple chat rooms in DrupalChat module.

Anyone can help me to complete this requirement?

# Answer
This question is pretty similar to the (still active) issue about Multiple public chat rooms - role controlled, here is a partial quote from that issue:

> Any chance you can allow the administrator to create more global chat rooms? I would like to create a chat room for Children so Adults cannot gain access and adult rooms where teens and children cannot access.

Comment nr 4 (from the module owner of the DrupalChat module) states the following: **this option only exists in "iFlyChat Servers" polling method**.

Here are some more details about iFlyChat (= quote from https://iflychat.com/):

> With iFlyChat, websites need not worry about setting chat server of their own. iFlyChat server will take care of the hosting part and will provide a hassle free setup of chat system. We use latest onCloud technology which gives a faster chatting experience to all users of your website.
> 2 votes

---
Tags: 7
---


title: TinyMCE textarea not editable

text:
# Question
Title: TinyMCE textarea not editable
I have integrated tinymce in my form, inside a modal.

```
$form['myid_templates_editor']['text-modal'] = array(
    '#type' => 'text_format',
    '#format' => 'full_html',
    '#prefix' => <div id="first_modal">
    '#suffix' => </div>
)};

```

The JavaScript code I am using is the following.

```
jQuery('#first_modal').dialog('open');

```

It was working well, but when I open again another modal while the first modal is still open, the tinymce text area was somewhat disabled and not editable. Why?

```
jQuery('#second_modal').dialog('open');

```

What shall I do to fix it?

# Answer
> 0 votes
```
<script type="text/javascript">
    $('.the-modal').bind('shown', function() {
        tinyMCE.execCommand('mceAddControl', false, 'mce-<?=$reply["id"]?>');
    });

    $('.the-modal').bind('hide', function() {
        tinyMCE.execCommand('mceRemoveControl', false, 'mce-<?=$reply["id"]?>');
    });
</script>

```

It was a bug and I found a solution here.

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


# Question
Title: Remove VAT based on company field and country
How can I remove tax based on the company field and based on the country. For example:

**In the Netherlands:**

A customer from a company in The Netherlands - He must pay VAT

A customer private in The Netherlands - He must pay VAT

**Outside the Netherlands**

A customer from a company outside the Netherlands - He must pay ***no*** VAT.

A customer private outside the Netherlands - He must pay VAT.

What I have so far is this: If the company field has a value, they don't need to pay VAT. But the problem is now, if they are living in the Netherlands and they place a order from a company they don't have to pay VAT, but people in this country (The Netherlands) need to pay VAT.

# Answer
I got the right settings now, but I have one problem. I want to show my product prices always with VAT. But with my current settings in rules the price is showing without VAT until I make a country selection on the checkoutpage.

In the view I selected: Display the calculated sell price for the current user.

Is there a way to fix this? Thanks!
> 1 votes

---
Tags: commerce, rules
---


title: How to add an image to nodes?

text:
# Question
Title: How to add an image to nodes?
I created a new content type (*Image*), which has an image upload field set. Now I can upload images and they are now nodes. But what do I need to do to add them to other existing content types?

My guess was to turn the image content type into a block. Is this correct?

# Answer
> 4 votes
> My guess was to turn the image content type into a block, and if so, whats the best module to do that?

# Bean

> Bean is an acronym that stands for Block Entities Aren't Nodes.
>
> This is a great introductory article about what the bean module.
>
> What is Bean? Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.
>
> Beans were driven by the API first. This means that you can create block types (bean types) all in a plugin class turning off the UI. The entire configuration in code. No worry about feature reverts.

Here is a video tutorial

**Basically it lets you add fields to blocks.** This module comes with Drupal 8 core by default.

# Answer
> 1 votes
You don't need to have an image content type to upload images and use them in your other content types.

Simply add an image field to your content type and you are good to go. Basically, at uploading an image, its url will appear, and you can then use that url in an in the body of your node.

*But there is another way.*

You can also use the modules imce,plupload,imce\_plupload combined with ckeditor or wysiwyw editor. After correct configuration you will be able to upload images and to manage them with the imce file browser. Doing so, your content type doesn't need image field anymore, as part of its structure.

I advise you to carefully read the README files if going that second method, because making all of those work correctly need the correct setup, explained in the documentation. It's not click enable and go.

# Answer
> 1 votes
I guess that what you need is Entity reference

> Provides a field type that can reference arbitrary entities

By (1) adding an entityreference field to your webform content type you will be able to attach-link your "Photo" nodes to webform nodes. (2) From the "Manage display" you may adjust the field's position and set its format as "Rendered entity".

Hope that helps!

# Answer
> 1 votes
Existing answers are misleading. What you need is exactly File Entity module, which enables to add fields to file fields.

> File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters. File entity integrates with a number of modules, exposing files to Views, Entity API, Token and more.

---
Tags: 7, media
---


# Question
Title: Print node URL in a custom block template
I have a custom block that loads multiple nodes from the database and passes it to the twig template. Inside the template I loop the list printing some node details, but I need to create a link on the node title, possibly its clean (alias) URL. The problem is that with node.url I get a security error:

> Twig\_Sandbox\_SecurityError: "Calling "url" method on a "Drupal\node\Entity\Node" object is not allowed

I tried with `{{ link(item.label, item.url.value) }}` but I get the same error.

What is the correct way to create a link in twig using the node URL?

# Answer
> 2 votes
Ok, it seems I have solved the problem using twig/drupal path() function, building the linked title in this way:

```
<a href="{{ path('entity.node.canonical', {'node': item.id}) }}">{{ item.label }}</a>

```

where "item" is the node object inside the list loop.

---
Tags: theming, 8, uri, navigation
---


# Question
Title: How to show more than two fields in a Openlayers popup on a views_geojson layer?
I have finally gotten my OpenLayers working, and I'm trying to show 7 fields about my points in a popup. By default, Views\_geojsononly allows you to define a title and description fields for tooltips. I am assuming that this applies to the popups as well. Only being able to show two fields kind of limits the utility of the feature. So, I'm wondering how I can show more of my fields in the popups? I'm using the Dev version of OpenLayers 7.x-3 and all the stable dependecies.

# Answer
So, if anyone else runs into this a simple rewriting of the fields in views will get you to where you want. You can add your html there to format the fields.
> 1 votes

---
Tags: views, 8, javascript
---


# Question
Title: Which is the correct "code/word" for Language Neutral?
I read an article from Gábor Hojtsy where he says:

> Language neutral uses the language code **'und'**, which means **undefined** and is specified to be used for such cases by the ISO 639 standard.

But when you go to read the ISO 639 you can find:

> **und**, for **"undetermined"**;

And you can find inside Drupal the **"Language Neutral"**

I ask the question because I'm writing a module where I need to have a word to identify the nodes that don't have a defined language. So, which is the word to use, Neutral, Undefined or Undetermined?

# Answer
From Drupal constant LANGUAGE\_NONE api documentation `Und` stands for *undetermined* and in Drupal 8 it is called LANGCODE\_NOT\_SPECIFIED
> 2 votes

# Answer
They are generally referred to as "language neutral nodes" to the user. So that is how your module should call them too. They are called "und(efined)" by developers only.
> 1 votes

---
Tags: i18n-l10n
---


title: add image to form

text:
# Question
Title: add image to form
How do you add something like `<img src="" alt="">` to a form?

```
$form['image1'] = array(
  '#type' => 'img',
  '#name' => 'image1',
  '#id' => 'image1',
  '#prefix' => '<div class="existing-images">
                    <div class="existing-image">
                        <a href="" class="delete">X</a>',
  '#suffix' => '</div>',
);

```

or

```
'#type'=>'image',

```

doesn't work.

# Answer
> 2 votes
In Drupal 7, *img* or *image* is not a type of form element. Since you seem to associate an action to that image, you probably are looking for #image\_button, which formats a form submit button with an image.

Otherwise, you can use the following code.

```
$form['image1'] = array(
  '#markup' => theme('image', array('path' => $your_image_path, 'attributes' => array()))
  '#name' => 'image1',
  '#id' => 'image1',
  '#prefix' => '<div class="existing-images"><div class="existing-image"><a href="" class="delete">X</a>',
  '#suffix' => '</div>',
);

```

In Drupal 8, you can still use *image\_button* as #type, but you can also use *responsive\_image* when the Responsive image module is enabled.

---
Tags: media
---


# Question
Title: Request::create is not working in EventSubscriber service class
Drupal 8 doesn't allows changing the current page in hook\_init as we could do it in drupal 7 using following way :

```
$_GET['q'] = '/my-url';

```

But according to documentation we can do it using following way :

```
$request = \Drupal::service('request_stack');
$current_request = $request->getCurrentRequest();
Request::create('/my-url', 'GET', $current_request->query->all(), $current_request->cookies->all(), array(), $current_request->server->all());

```

But it still doesn't work.

Note: I have successfully converted the `hook_init` to `EventSubscriber` and other code is working fine.

# Answer
You forgot to assign the value returned from `Request::create()` to a variable, and the rest of the code. The code shown in that documentation page, merged with the code shown in one of its comments is the following.

```
$request = \Drupal::service('request_stack');
$current_request = $request->getCurrentRequest();
$sub_request = Request::create('/my-url', 'GET', $current_request->query->all(), $current_request->cookies->all(), array(), $current_request->server->all());
return Drupal::service('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);

```

Since you want to write code to redirect users to a different page, the equivalent of what you would write in Drupal 7 `hook_init()`, check also hook\_init() removed; it contains example code for that case.

```
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {
  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

```

See also the `LocalRedirectResponse` class.

The event subscriber for the example is described with the following, in mymodule.services.yaml.

```
services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Is there a module/hook for permissions for list values?
Say I have a text list field attached to a node with the following values:

* Apples
* Oranges
* Grapes
* Kiwi
* Strawberries
* Pears
* Bananas

But I want to give some options only to some roles, for example:

* Only **Administrators** can select Strawberries.
* Only **Anonymous** can select Kiwi.
* Only **Role C** can select Pears.

Is there a module for this? Or, if I was going to code it myself, is there a hook to start from?

This is for Drupal 8 but if there was a solution only for 7, that would be interesting to look at too.

# Answer
# This is Drupal 7 solution

Using `hook_form_alter`, you can unset some of the options based on the user role. For example look at this list of `article` content type (`field_list`)

It is the result of `kpr()` on its form

simply use this code

```
function THEME_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == "article_node_form"){
        //kpr($form);
        if(in_array('SOME_ROLE', $user->roles))
            unset($form['field_list']['und']['#options'][2]);
   }
}

```

This is the result
> 1 votes

---
Tags: 7, users, forms
---


# Question
Title: Programmatically log in user not working correctly
Here's what I am doing:

```
global $user;

if (!user_is_logged_in()) {
  $user = user_load(31);
  user_login_finalize();
  echo $user->uid;
}

```

When a user is not logged in - we have to log in him as user with id 31. I have placed this code at top of `page.tpl.php`.

I am noticing some strange behavior. If I visit the homepage (http://ggames.kz/), at the top I can see the id 31, that's correct. However, if I visit the user page (http://ggames.kz/user), it shows that I am not logged in. If I refresh the browser or visit another pages, I am logged in. I can't figure out why it won't authenticate user from the first page load?

# Answer
Template files are not the proper place for your code, since at this level the headers are (probably) already sent. That's why the session cannot be saved on the client browser.

You'd better implement `hook_init()` in a custom module

```
function YOURMODULE_init() {
  if (!user_is_logged_in()) {
    global $user;
    $user = user_load(31);
    user_login_finalize();
  }
}

```

> If I refresh the browser or visit another pages, I am logged in.

You are seeing the correct user ID on your debug output, just because you are printing the user id which you have loaded just 2 lines before. It doesn't mean that the user is successfully logged in.
> 2 votes

# Answer
The correct code to impersonate another user is the following.

```
global $user;
drupal_save_session(FALSE);
$user = user_load(31);

```

As said in Safely Impersonating Another User, this code is also safer, since the session will not be saved.

If you need to change back the user after doing something, then the code should be the following one.

```
global $user;
$original_user = $user;
$old_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(31);

// Your code here

$user = $original_user;
drupal_save_session($old_state);

```

As side note, changing the user account for the current user should not be something done in a template file. This type of code is expected to be executed in a module, in one of the hooks Drupal makes available, such as `hook_init()`.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How do I link Drush to my Drupal site on Pantheon?
A friend of mine got me into Drupal and did the initial setup for me. At first, I was using localhost to play with Drupal and Drush to download and enable modules.

Now I have my own Pantheon hosting site that lets me install Drupal on their side, but how do I link my Drush command prompt to my online site? Before on localhost, it was just a matter of changing directories, but how do I connect it for a site online?

Edit: This is for Drupal 7.

# Answer
> 6 votes
Start off by installing Terminus. Terminus now supports machine tokens; once you set these, up you can authenticate automatically without a password simply by running `terminus auth login <email address>`.

Once you are authenticated with Terminus, `terminus sites aliases` will download Drush aliases for all of your Pantheon sites. Since this list can change over time (e.g. when you add or delete sites on Pantheon), you will want to periodically re-run this command. You might even want to have Terminus log in and update your aliases in your shell startup script (e.g. .bashrc).

Once your aliases are up-to-date, you can use a remote site via:

```
drush @pantheon.mysitename.dev status

```

---
Tags: 7, drush
---


# Question
Title: Remove 'Switch to plain text editor' in CKEdtior
Where do I disable the switch to plain text editor link from the CKEditor. I checked the settings and I don't find anything that support this.

I tried to disable it with display:none; through CSS but it wont respond to it. Here is the code

```
<a id="switch_edit-body-und-0-value" class="ckeditor_links" onclick="javascript:Drupal.ckeditorToggle(['edit-body-und-0-value','edit-body-und-0-summary'],'Switch to plain text editor','Switch to rich text editor');" href="javascript:void(0);" style="">Switch to plain text editor</a>

```

I both tried with the id tag and the class to disable it but it dosen't work.

```
.ckeditor_links a {
display: none;
}

```

does not work :(

Any suggestions?

# Answer
You do not need to use CSS. There is an option within the CKEditor profile.

Go to Configuration \> Content Authoring \> CKEditor then select edit next to the profile you want to effect. This way you can also limit this too certain users.

Then select editor appearance and scroll down to "Show the disable/enable rich text editor toggle" then select hide and save the profile.
> 1 votes

# Answer
It is a hardcoded style. A quick solution is the frowned upon use of !important. This will work.

a.ckeditor\_links{ display: none !important; }
> 0 votes

# Answer
You can do it programmatically.

Include this code into the hook\_form\_alter function of your module:

```
drupal_add_js(
  'jQuery().ready(
    function() {
      jQuery(".ckeditor_links").hide();
    }
  );',
  'inline'
);

```

Greetings
> -2 votes

---
Tags: theming, wysiwyg
---


title: Restoring views to their default state

text:
# Question
Title: Restoring views to their default state
Views module comes with a few default views. I have enabled and modified the frontpage view, but I'd like to go back to its default state that originally came with the module on a fresh install (without my changes). Is this possible?

Thanks

# Answer
Yes you can do that.

1. Go to the views listing page (admin/structure/views).
2. In the **Operations** column of the view you want to reset, click the **Revert** operation.
3. Confirm by clicking the **Revert** button.
> 3 votes

---
Tags: views
---


title: How to remove old revisions product?

text:
# Question
Title: How to remove old revisions product?
How to remove old revisions product? I have a lot of old revisions of products. They must be removed. How?

# Answer
> 3 votes
Drupal Commerce does not provide a UI nor function for this actually. However, we can look at how the Node module does it and run the same function, just adjusted.

From `node.pages.inc`, there is a function to delete a specific Node revision.

But that is only for a specific revision ID. Here's an adjusted function that loads a products revisions and purges them.

```
/**
 * Deletes a node revision.
 *
 * @param $revision_id
 *   The revision ID to delete.
 *
 * @return bool
 *   True on success, false if not.
 */
function commerce_product_revision_delete($revision_id) {
  if ($revision = entity_load('commerce_product', NULL, array('revision_id' => $revision_id))) {
    $revision = reset($revision);
    // Prevent deleting the current revision.
    $commerce_product = commerce_product_load($revision->product_id);
    if ($revision_id == $commerce_product->revision_id) {
      return FALSE;
    }

    db_delete('commerce_product_revision')
      ->condition('product_id', $revision->product_id)
      ->condition('revision_id', $revision->revision_id)
      ->execute();
    field_attach_delete_revision('commerce_product', $revision);
    return TRUE;
  }
  return FALSE;
}

```

Basically the trick is ensuring you load the revision and then delete it's record and invoke `field_attach_delete_revision` so the old field data gets purged.

I created an issue in the queue for this: https://www.drupal.org/node/2660056

# Answer
> 0 votes
If you're wanting to remove any entity revision, the entity module provides a helper function:

```
entity_revision_delete($entity_type, $revision_id);

```

Which you can call like this:

```
entity_revision_delete('commerce_product', 6);

```

Where `6` is the revision ID of the product you want to delete.

Views Bulk Operations includes a revision delete option, which you could use to create a view that looks at product revisions and allows you to delete them in bulk.

---
Tags: commerce
---


# Question
Title: how to update order status in shopping cart to checkout
Here is my code for updating order status in shopping cart to Checkout: Checkout. After running no error but it does not show order status as Checkout: Checkout.

```
function commerce_services_order_checkout_update($order_id,$data, $flatten_fields) {
    $status; $message;

    $status = $data['status'];

    $order = commerce_order_load($order_id);
    $order = commerce_order_status_update($order, "Checkout: Checkout");
    if($order != null){
        $status = 1;
        $message = "Order status set to checkout successfully.";
    }else{
        $status = 0;
        $message = "Order status can not set to checkout.";
    }

   $reply= (array('status' => $status,'message' => $message, "order status ". $order));

    return $reply;
}

```

Any suggestion is greatly appreciated!

Thanks

# Answer
> 5 votes
This is your problem:

```
$order = commerce_order_status_update($order, "Checkout: Checkout");

```

You should be passing the machine name for the status

```
$order = commerce_order_status_update($order, 'checkout_checkout');

```

See this API doc page on drupalcontrib.org: http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!order!commerce\_order.module/function/commerce\_order\_status\_update/7

# Answer
> 0 votes
You can change the order status using Rules module.

1. Event -\> Choose after adding products to the cart
2. Action -\> Update the status

---
Tags: commerce
---


# Question
Title: Creating filter seems to work but doesn't "stick"
So I want to create a view filter programatically using hook\_update in the .install file. I feel like I have it going, but the changes will not show up in the UI. Here is what I am doing, and the results:

This view already contains 2 filters. I used this code to view those filters:

```
$filters = $view->display_handler->get_option('filters');
var_dump($filters);

```

and it was clear that they were there. Then I went into the UI and created the new filter using the GUI tools there. Then I ran the above code again, and it showed me all 3 filters (the 2 previous ones, plus my new one). So far so good.

So now I backtracked the database to the initial state, so I only had 2 filters again. Then inside my install file I ran this code:

```
$name = "soccer_scores";
$view_display = 'default';
$view = views_get_view($name);
$view->init_display($view_display);
$view->preview = TRUE;
$view->is_cacheable = FALSE;

$filters = $view->display_handler->get_option('filters');

$filters['field_is_livescore_value'] = array(
'id' => 'field_is_livescore_value',
'table' => 'field_data_field_is_livescore',
... a bunch of other array data

$view->pre_execute();
$output = $view->display_handler->preview();
$view->execute();
$view->post_execute();
var_dump($filters);

```

So after the install file runs, when that last var\_dump runs, it prints out the $filters array and it looks exactly like when I created the new filter using the GUI. However, when I reload the admin area for that view, no new filter appears, it just shows the existing 2 filters, but not the new one.

So I feel there is some step I am missing to make the change "stick". I can find so few docs on this, can anyone help?

# Answer
> 0 votes
To modify the value of a view programatically you don't need to actually render the view like you do with this part:

```
$view->pre_execute();
$output = $view->display_handler->preview();
$view->execute();
$view->post_execute();

```

They are only functions involved in rendering the view output.

The part you are missing is saving the view.

You are adding things to it but because you don't save it they don't end up in the database.

You will need to use the view::save() function like this:

```
// Load the view.
$view = views_get_view('VIEW_NAME');
// Modify the view here.
...
// Save the view.
$view->save();

```

**\[EDIT\]**

As for actually adding the filter. I recommend using the view::add\_item() function instead of just manually adding to the view object because it does some extra work with the handler that isn't being done by your current code.

Some examples of using add\_item() are https://drupal.stackexchange.com/a/134872/10729 and https://drupal.stackexchange.com/a/70649/10729

---
Tags: views
---


title: Two different design in Drupal website

text:
# Question
Title: Two different design in Drupal website
My website has two designs and I not sure which one is better. I am thinking upload both of them.

Here is my question: Is drupal able to let 50% of the user see design A and the rest is able to view design B. After one month later, I am able to see a report which one is better.

# Answer
> 2 votes
ThemeKey

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

# Answer
> 2 votes
The closest thing I know is:

## Switchtheme

> Adds a block to allow users to switch between enabled themes.
>
> Themes can be given 'user friendly' names and access can be controlled by user role.
>
> Switchtheme provides optional support for Browscap module to switch themes based on the browser of a visitor.

---
Tags: 7
---


# Question
Title: User tabular data entry to build a budget worksheet?
I am trying to build a budget worksheet where users can enter their budget information and save that until the next time they need to update it. Each user will only have access to their budget sheet.

I spent approximately 16 hours on trying to get Sheetnode and PHPExcel to work, but that is really buggy in my humble opinion (may also be my lack of knowledge).

I'm not really looking for a "how-to" but rather someone point me in another direction where I could possibly find success. I don't really know what keywords to search in google for what I need to do, but I keep stumbling upon webform, which is a nice module, but does not do what I need at all.

# Answer
> 2 votes
You could try https://drupal.org/project/tablefield or https://drupal.org/project/slickgrid

From module page:

> The Slickgrid module is an implementation of Michael Leibman's jquery slickgrid plugin, a lightening fast JavaScript grid/spreadsheet.
>
> It defines a slickgrid view style, so all data can be output as an editable grid.
>
> This module will only work with Slickgrid 2.1.

These do not provide spreadsheet functionality, but you would probably implement the summation or whatever calculation is necessary.

# Answer
> 1 votes
This is the closest module (Ledger) I have found for creating budgets in drupal. However the module is still under development. If this does not meet your requirement, you might have to write a custom module for what you want.

# Answer
> 1 votes
A NOT commonly known/used solution that might help to answer this question is the fairly new Math Field module (for D7). Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

---
Tags: forms
---


title: Equivalent query of "Select All"

text:
# Question
Title: Equivalent query of "Select All"
I have this query:

```
SELECT * pg_type;

```

What is its equivalent query in Drupal 7?

My code throws an error.

```
$query = db_select('pg_type', 't1', array('target' => 'import'));
$result = $query->execute();

```

# Answer
```
SELECT * pg_type

```

isn't a valid SQL query; presumably you meant:

```
SELECT * FROM pg_type;

```

which in Drupal-ese is:

```
$query = db_select('pg_type', 't')->fields('t');

```

Output of the above:

```
SELECT t.*
FROM {pg_type} t

```
> 2 votes

---
Tags: 7, database
---


title: Which method has better performance

text:
# Question
Title: Which method has better performance
I want to update some term id on some node (let suppose 1000 node),My changes is convert all `news node with category(term_id) = 3040 to category(term_id)=5)`.

I know I can do it with several methods( use views bulk operation, write batch running etc, .... ) but my question is about performance of below approaches

1. Approach based on old method ( node\_save)

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'news')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_category', 'tid', array('3040'));
$result = $query->execute();
$nids= array_keys($result['node']);
//ym($nids);

$nodes= node_load_multiple($nids);
foreach ($nodes as $node){
    foreach($node->field_category['und'] as $i=>$item){
       if($item['tid']==3040){
            $node->field_category['und'][$i]['tid']=5;
            node_save($node);
        }
    }

}

```
2. Approach based on entity wrapper method

```
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'news')
            ->propertyCondition('status', 1)
            ->fieldCondition('field_category', 'tid', array('3040'));
    $result = $query->execute();
foreach($result['node'] as $nid => $stub_node) {
  // Load the full node and wrap it with entity_metadata_wrapper().
  $node = node_load($nid);
  $wrapped_node = entity_metadata_wrapper("node", $node);
  if ($wrapped_node->field_category->value()->tid == 3040) {
    $wrapped_node->field_category->tid->set(5);
    $wrapped_node->save();
  }

```

in first approach we have one `node_load` and one `node_save` but in second approach we have one `node_load` one creating entity metawrapper creation and one entity wrapper save. **I want to know which method has better performance?**
*let suppose we have the same situation for both 2 method, I just want somebody tell me ( take a benchmark on one node and in bulk ( multi node) mode and tell me the performance of both that which one of this method is faster in the same situation.*
please provide your answer with facts or benchmark testing result

# Answer
> -1 votes
After some research and some benchmark I get below results

**In equal and regular situation** using Entity Meta Wrapper for change the node fileds has better performance.

> Loading the entity object just for passing into EMW. Unless you already have the pre-populated entity, it's more efficient to just pass the entity id to entity\_metadata\_wrapper(); EMW will lazy load the field and property data that it needs, hoorah! So much magic.

(if we have $node it is better use it but if we don't have it **Don't use node\_load to load it before pass it to entity\_metadata\_wrapper and just pass nid to it has better performance rather first load node then pass it to EMW**

```
// Unnecessary node load... $node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node); // More efficient
(if the object isn't handed to you)...
$wrapper = entity_metadata_wrapper('node', $nid)

```

Saving the entity with node\_save(), taxonomy\_term\_save(), etc. instead of the EMW save() method. Fun fact: both EMW and standard entity controllers include save() methods, so you can call e.g. $node-\>save() on properly instantiated entity objects and wrappers.

```
// If you don't already have the node object, don't bother loading it just to save...
$wrapper->field_foobar = 'new value';
$node = $wrapper->value();
node_save($node); // Easier and prettier...
$wrapper->field_foobar = 'new value';
$wrapper->save();

```

Reference: Death to Field Arrays

# Answer
> 6 votes
This is essentially impossible to answer. You have one part of your question, wrong

* Your first method uses a single `node_load_multiple()` with multiple `node_save`
* Your second answer uses multiple `node_load()` with multiple Entity API calls

My *gut* tells me the first will be quicker, as a single `node_load_multiple()` is typically more performant than multiple `node_load()` calls, given the same set of nodes. You also aren't creating the the metadata wrapper objects.

However, you need to do the benchmarking on your system. There may be a difference, but it may be small enough to not make a real imapact. Some things that make cross-system benchmarks unreliable

* entitycache can have a tremendous impact on a system, especially if you use a non-SQL backend for it
* the number of fields on your node can effect how long the wrapper creation process takes, and also how long the `node_save()` takes
* APC and/or OpCache usage and configuration
* PHP version
* MySQL configuration (or whatever database backend you are using), including some of the Drupal-specific tricks that can improve performance
* The number of `hook_node_update()` instances that fire for each save

# Answer
> 3 votes
Given that performance is an issue you may alter the code of your first approach (1) like this :

```
$field_name = 'field_category';
$tid = '3040';
$nids = db_query("SELECT nid FROM {node} n, field_data_{$field_name} c WHERE n.nid = c.entity_id AND c.bundle = 'blog_post' AND c.{$field_name}_tid = :tid", array(':tid' => $tid))->fetchCol();
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  if ($node->{$field_name}[LANGUAGE_NONE][0]['tid'] == 3040) {
    $node->{$field_name}[LANGUAGE_NONE][0]['tid'] = 5;
    field_attach_update('node', $node); // Instead of node_load
  }
}

```

What I did was to (1) change the use of EntityFieldQuery() with db\_query() by the time it is much faster. Moreover (2) I changed the node\_save with the field\_attach\_update since there is no need to save the whole node (ref).

From drupal.org: Static queries vs Dynamic queries

I hope that helps!

---
Tags: nodes, entities, performance
---


# Question
Title: How do I limit or require the number of tags in a taxonomy reference field?
Similarly to how StackExchange requires tags on a question, how can I ensure the user uses at least four tags but no more than 8?

# Answer
The module field\_validation has an option for Number of selections which could be what you need without custom coding. For 7, there's a full release and for 8, there's an alpha.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How can I change the title of the site on Google search?
I have changed the site name to *HoNESt*, but when I search for the website on Google, the site name results *HoNESt: Front Page*.

>

How can I change this?

# Answer
# Meta Tag

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about a website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of a site in search engine results.

**Basically it allows you to format your title and description that gets indexed by search engines.**

Once you install it, you need to override the Global: Front Page and remove the \[site:name\] token.

Here is a Video Tutorial

**PS**: You will need to wait until Google crawls your site again to see changes.
> 2 votes

---
Tags: 7
---


# Question
Title: Custom line item fields in Create an Order page
I have successfully added the custom line item fields in the cart through Views and modified the new total using a hook, but how do I do the same thing in Create an Order page (admin/commerce/orders/add)?

* The custom line item field was added in admin/commerce/config/line-items/product/fields
* I'm using inline entity form and I can see the custom field, but the custom field is not visible in line items table.

# Answer
Sounds like you just need to alter the `commerce_line_item_table` View. Edit this view and add your fields so that they show up when it is embedded when the line item reference field formatter is used.

You'll want to take some extra steps, however, to save your customizations since that view is provided by the module. I would clone that view and update your field formatter's to use that view (it's customizable from the display options!)

Or, implement `hook_views_default_views_alter` and completely override the view with your own export.

EDIT: Some info on the line item manager widget

In order to get fields to show up in the line item manager widget table, you're going to need to override the widget's theme function. See `commerce_line_item_field_widget_form` and `theme_commerce_line_item_manager`.

Essentially you may need to invoke `hook_field_widget_form_alter` to added your field's value, and then override `theme_commerce_line_item_manager` to place it properly.

Snippet of a theme override that could be used, to add `length`

```
// Add each line item to the table.
foreach (element_children($form['line_items']) as $line_item_id) {
  $row = array(
    drupal_render($form['line_items'][$line_item_id]['remove']),
    drupal_render($form['line_items'][$line_item_id]['title']),
    drupal_render($form['line_items'][$line_item_id]['length']),
    drupal_render($form['line_items'][$line_item_id]['line_item_label']),
    drupal_render($form['line_items'][$line_item_id]['commerce_unit_price']),
    drupal_render($form['line_items'][$line_item_id]['quantity']),
    drupal_render($form['line_items'][$line_item_id]['commerce_total']),
  );

  $rows[] = $row;
}

```
> 1 votes

---
Tags: commerce, entities
---


# Question
Title: Archive old content data in different database
How can i make archive my old content and save in different db with my cron job.

I want to store in different DB because i want to increase my site performance.

In drupal 7 what's the best way to do it ?

# Answer
Here's what you can do:

* Add your archive database to your settings.php below your default database.

```
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

```
* In your cron script, load all nodes you want to archive. In this example I retrieve all nodes older than a month and no more than 50 at a time.

```
$nodes_to_archive = array();

$query = db_select('node', 'n')
  ->fields('node')
  ->condition('type', 'your_content_type')
  ->condition('created', REQUEST_TIME - (86400 * 30), '<')
  ->range(0, 50);
$result = $query->execute();

while($record = $result->fetchAssoc()) {
  $nodes_to_archive[] = $record;
}

```
* In the same script, switch from database and add the nodes to the archive (make sure the second database has the same structure as the existing one)

```
db_set_active('my_other_db');

foreach ($nodes_to_archive as $node) {
  db_insert('node')
    ->fields($node)
    ->execute();
}

```
* Still in the same script, switch back to the default database and remove the archived nodes.

```
db_set_active();

$nids = array();
foreach ($nodes_to_archive as $node) {
  $nids[] = $node->nid;
}

node_delete_multiple($nids);

```

I haven't tested any of this so you might need to improve it here and there. If anything's unclear, please ask.

Here is a list of helpfull resources:
> 4 votes

---
Tags: 7, performance, backups
---


# Question
Title: What replacement token to use for counting a specific content-type
I have a content type of 'partners', and I wanted to create a body text like 'Currently we are working with X partners'. I have token-filter working, but I cannot find a token that allows me to choose the content-type.

`[content-type:node-count]` Doesn't do anything.

`[node:content-type:node-count]` Returns the amount of the current type (basic page, not partner).

Is there some token that allows me to choose the content-type to work with? eg. something like `[content-type:?:node-count]` where I can enter my content-type of partner on the `?` ?

# Answer
I ended up creating a custom module for this to calculate the specific amount of items. Now I can use a token like `[partner:partners]`.

```
/**
 * Implements hook_token_info().
 */
function partner_token_token_info() {
  $types['partner'] = array(
    'name' => t("Partner Tokens"),
    'description' => t("Tokens for partners."),
  );

  $partner['partners'] = array(
    'name' => t("Partners"),
    'description' => t("The count of partners."),
  );

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

/**
 * Implements hook_tokens().
 */
function partner_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'partner') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'partners':

          $query = db_select('node', 'n')
            ->condition('type', 'partner');
          $num_rows = $query->countQuery()->execute()->fetchField();

          $replacements[$original] = $num_rows;
          break;
      }
    }
  }

  return $replacements;
}

```
> 1 votes

---
Tags: tokens
---


title: Redirect page to existing field value

text:
# Question
Title: Redirect page to existing field value
I am redirecting most of the pages of my old website to a new subdomain of the same domain, from http://www.domain.com/www-page\_url to http://new.domain.com/new-page\_url/with-different-slug. This new URL value exist in (almost) every page of the old website.

How would I proceed to create a general rule that permits the redirection from the page itself to new.domain.com/page\_url existing field value?

# Answer
You should be able to get this to work using the Rules module, using the "**Drupal is initializing**" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. I'm not sure (actually I really doubt ...) if using Rules event " *Content is viewed* " (not " *Node is viewed* " ...) will work (typically that's 'too late'). Refer to "How to specify a Rules event like "Content is 'going to be' viewed"?" for more details on that.

**If** you can think of something to use a (new) URL like `http://new.domain.com/new-page_url?newslug=with-different-slug` (instead of `http://new.domain.com/new-page_url/with-different-slug`), **then** you can make the value of the URL argument (= the value of the `newslug` argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

**PS**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.
> 3 votes

# Answer
Create `node.tpl.php` file, and at the top of this file, you can retrieve the field value and redirect the user to new url

---

# update

In template.php of your theme folder create function

```
function theme_preprocess_node(&$variables){
     $node = $variables['node'];
     $wrapper = entity_metadata_wrapper('node',$variables['node']);
     $variables['new_website_url'] =  $wrapper->field_new_website_url->value();
}

```

Now in node.tpl.php (Copy the source of this file,under *View Source*, if you don't have it or you didn't theme your nodes) the `$new_website_url` variable is available.

You can simply use drupal\_goto function to redirect to new url.

**Hint**: Entity module is needed to use `entity_metadata_wrapper`

**Hint**: If there are more than a content type and one of them need to be redirected, you can check for `$node->type` and also set `THEME_HOOK_SUGGESTION` to redirect the page only for a certain content type.
> 1 votes

---
Tags: uri, redirection
---


# Question
Title: How can I override the menu toggle on AdaptiveTheme?
The menu renders:

```
<h2 class="block-title at-menu-toggle-button"><a href="#menu-toggle" class="at-menu-toggle-button-link">Menu</a></h2>

```

which is hidden when in a viewport bigger than tablets. I would like to replace the "Menu" part with a `<span>` element with an icon instead, How can I override this?

# Answer
> 0 votes
Oddly enough I haven't really seen this issue addressed anywhere else. I found that the most straightforward solution is to put this in your theme's **template.php** and then style the span tag:

```
function your_theme_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-system-main-menu") {
   $variables['title'] = "<span id='menu-toggle-button-icon'></span>";
  }
}

```

Cheers

---
Tags: blocks, routes, theming
---


# Question
Title: How to hide nodes in a VIEW where the user is not referenced?
This is a follow-up to How to show nodes where the user is (not) in the reference field with Views?

I have a node with multiple user references and need a node VIEW that **hides** all nodes where the current user is NOT referenced. So, if the current user is not referenced, the node should not show up. The problem I just can't solve is that the node still shows up when other user are referenced (using exclude, it only excludes the current user from display, but it still displays the nodes for each other user that is referenced). I have unsuccessfully tried views\_distinct module and VIEWs own "distinct" query settings.

If the user is referenced, the node should show up (this works from the above mentioned question)

**CLARIFICATION:**

Basically, it’s for a simple pay-per-view site. I need 1 (or 2, whatever works) VIEWS that shows the videos where the user has purchased access to (where he is referenced) and where the user has not purchased access to (where he is not referenced). After 48 hours the references are removed using rules scheduler.

Ideally in one VIEW, when the user is referenced, the link should be „watch“, where the user is not referenced, it should read „buy“ using VIEWS conditional and rules link. But two separate VIEWS are also ok.

Right now I have a content view (also tried it with a user view unsuccessfully, but this might be a saner approach?!). All of that works well with the notable exception of showing the nodes with multiple user references.

**UPDATE:**

Added a screenshot using the views argument substitutions.

**UPDATE 2:**

I tried it with regExpressions and views substitutions. The UID of the currently logged in user is passed as ***!1***, but what is the correct regEx syntax to show only the nodes, where this user is not referenced?

This does not work as value of the operator on the useraccess field filter:

```
^***!1***

```

**SOLUTION**

Oh boy, this was a ride. Finally figured out a solution. Posting it if someone needs it. **Basically, I added the username in the url and do a contains text comparison using views conditional.** ID from the logged in user did not work as contains also shows user ID "13" or "14" when the user "1" is logged in. Simply excluding did not work in those cases where other users are referenced as well.

# Answer
You have to add a filter under Filter Criteria Section which is, if a 'yourfield-name'is 'is not empty (NOT NULL)' from the select list.

This filter only shows results which have the value for this particular field. Otherwise it will not show you any result for that node.

I hope it will work.
> 0 votes

# Answer
* Add your user reference field has a Contextual Filter
* In your contextual filter settings go to *When the filter value is NOT available* and check *Provide default value* and select User ID from logged in user. Then under "More" tab, check "Exclude".

This might give you only those Articles where current logged in user is NOT referenced
> 0 votes

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


# Question
Title: Drupal View Filter Criteria "Contains Taxonomy"
I need to filter based on taxonomy term in my view, I have set up this filter however I would like to return nodes that 'contain', not "Is one of". See screenshot below:

Is there a module or a way I can achieve this? If I put 'vod' instead of 'vodafone' it does not return anthing:

The end goal is to filter nodes from the URL e.g. localhost/numbers?field\_company=vod will return nodes for vodafone and vodafoneblahblah.

# Answer
> 2 votes
* Add a Relationship of type "Terms in node"
* Add a filter "Taxonomy term: Name"

Now you can set "Contains" has an option for your filter

---
Tags: views
---


# Question
Title: Restricted nodes don't show up in search results
On this Belgium version of the side users has to have the right permission to view specific nodes. I did this with Content Access module.

But now when you as anonymous user search any content the restricted nodes don't show up?

How do i manage the teasers show up always? But when you want to see full content it's restricted?

# Answer
The default Drupal search respects the Drupal permission system, so if the user performing a search doesn't have permission to see a node, it won't appear in search results at all. To get around this, you'll need something that circumvents the permission system, either by altering the search function, or replacing it entirely.

You could take a look at the Custom Search module. It modifies Drupal's search, and gives you control over the default search options. However, I can't recall if it includes an option to show content you wouldn't otherwise have permission to see.

The other way you could do it is to create a custom view, add a filter for the field you want to search on, then under advanced, select "query options", and tick the "disable query rewriting" option. This will prevent the permissions from being applied to the view, so will allow users to see nodes they don't have access to. However, I'm not aware of any way of making a view search multiple fields from a single exposed filter, making it less than ideal for an alternative search box.
> 1 votes

---
Tags: 7, users, search
---


# Question
Title: How to get the first non-empty field value of a referenced entity in views?
The website has two content types: **Magazine** and **issue**.

I'm using the Entity Reference module to create a magazine archive website.

I have a views that list all magazines. Each magazine is with an image of issue that related to this magazine. There is a relationship (entity reference: referencing entity) and the aggregation setting is active (use aggregation).

Everything is OK but there is a problem I couldn't solve.

The image for each magazine is the image of the first issue of this magazine. But not every "first issue" has an image and it shows the default image.

## What I want to do is to show the first issue's image that's image field is non-empty or show any related issue's image on this views. How can I do that?

*Note: Some magazine's any issues doesn't have any image and if I filter out these issues, then the related magazine will not be shown. I think what I want to do is if any of the issue has an image show it or show the default image.*

# Answer
From *Everything is OK but there is a problem I couldn't solve* I supposed you successfully create a view of issues and their related magazine and I focus on the problem.

There are two cases,

1. at least one of the issues has an image
2. non of them has an image

In order to create a view for *case 1*, you need to modify your existing view to have sort criteria on `image_field:fid` (*Issue* image field, using relationships you can have this)

***and sort it descending***

and set the Pager to:

**Use pager: Display a specified number of items| 1 item**

in this way, if there is any issue with an image, the first one that has image is displayed.

Lets handle the case where there is no issue with image. The image field is displayed in here, it can be in a `<div views-field views-field-field-image></div>`, but it is empty. We have to insert a default image in it. Simply add css like this to your theme

```
.views-field-field-image{
       width: ...px;// you standard display of width
       height: ...px;// you standard display of height
       display: inline-block;
       background-image: url('');

```

Now if there is an image, the `<div views-field views-field-field-image></div>` layer will go behind the image and it will not be shown and if there is no image, we have set the `<div>` dimension and also an image for it to be displayed.
> 2 votes

---
Tags: 7, views, entities
---


title: Where are permissions stored in DB?

text:
# Question
Title: Where are permissions stored in DB?
I'm looking at the DB but can't find where the permissions are stored.

On the Admin page the permissions can be saved at `/admin/user/permissions`

But where this data is saved in the DB?

# Answer
Permissions are stored in the `permission` table.

The table stores a comma-separated list of permissions that are enabled for each role, by role ID, which links back to the `role` table.

The `users_roles` table makes the final link between users and the roles assigned to them.
> 7 votes

---
Tags: 6, users
---


title: PDOException: SQLSTATE[42S02]

text:
# Question
Title: PDOException: SQLSTATE[42S02]
After I clicked to create a new content type, I got this message.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'bis301.cache' doesn't exist: DELETE FROM {cache} WHERE (cid LIKE :db\_condition\_placeholder\_0 ESCAPE '\\') ; Array ( \[:db\_condition\_placeholder\_0\] =\> entity\_info:% ) in cache\_clear\_all() (line 168 of C:\xampp\htdocs\bis301\includes\cache.inc).

How can I fix this problem? Help me please.....

# Answer
Seems that's the problem with the cache table. If you're running localhost. Just drop the existing cache table and recreate it. Following is the query to create 'cache' table for drupal 7

```
CREATE TABLE `cache` (
 `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
 `data` longblob COMMENT 'A collection of data to cache.',
 `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
 `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
 `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
 PRIMARY KEY (`cid`),
 KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...'

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Changing date format in monthly archive in Views
I created a view which summarise the nodes and displays them in a year + month block. The result looks like this:

```
március 2015 (26)
február 2015 (12)
január 2015 (18)

```

I'd like to change the date format according to Hungarian standards:

```
2015 március (26)
2015 február (12)
2015 január (18)

```

I tried to find the appropriate settings in date/time settings (`admin/config/regional/date-time`) without any success.

# Answer
> 0 votes
For changing the date format in summary of months, I had to create a custom template of views-view-summary-unformatted.tpl.php, lets call it **views-view-summary-unformatted--post-by-date--block-1.tpl.php** and place it in the templates folder of my theme. In this template we can find `$row->link` variable which is need to be replaced with the correct value. For this sake I processed the `$row->created_year_month` varible as follows:

```
<?php
    $archive_year = substr($row->created_year_month, 0, 4);
    $archive_month = substr($row->created_year_month, 4, 2);
    $archive_timestamp = mktime(0, 0, 0, $archive_month, 1, $archive_year);
    $archive_date = format_date($archive_timestamp, 'custom', 'Y. F');
?>

```

Finally I replaced the `$row->link` with `$archive_date`.

# Answer
> 1 votes
Create a template file of your view **Display output:** **views-view--view-post-by-date--block.tpl.php**

**Make some slight changes where row is printing in your tempalate file:**

```
         <?php if ($rows): ?>
        <div class="view-content">
         <?php
   $output = '';
 for($i=0;$i<5;$i++){
$filter_link = date("Ym",strtotime("-$i months"));
$filter_display = date("Y F",strtotime("-$i months"));
$link = $GLOBALS['base_url'].'/post-by-date/'.$filter_link;
 $output .= '<a href="'.$link.'">'.$filter_display.'</a>('.count($filter_display).')<br>';

  }
print $output;
// print $rows; ?>

 </div>

```

# Answer
> 0 votes
You can create your own date formats at `admin/config/regional/date-time/formats`.

If you have the locale module enabled, you can localize your formats at `admin/config/regional/date-time/locale`.

Once you've created your own date format, you can tell views which format should be used to render a date.

# Answer
> 0 votes
To change the date from "***március 2015***" to "***2015 március***", you can follow the following steps:

* Go to path "**admin/config/regional/date-time/formats**"
* Click on "Add Format"
* In "Format string" field, add "***Y F***"
* Now go to path "**admin/config/regional/date-time**" and change the format for your date-type.

Please try this, it will solve your problem.

---
Tags: 7, views
---


title: Static resource URL in Drupal 8 theme

text:
# Question
Title: Static resource URL in Drupal 8 theme
I'm trying to place an image using a local resource in theme. Using the site url like

```
drupal.localhost/themes/customtheme/images/image.png

```

does give me access denied error. I understand that Drupal should generate a public url for the image, but how to ask Drupal to do so from the theme while still using relative URLs in `src` tag of `img` ?

edit: Changed question, made more clear

# Answer
Check out file\_create\_url() function:

Example of usage in a preprocess hook:

```
$variables['image'] = file_create_url($variables['directory'] . '/images/image.png');

```

Example of usage in a twig template:

```
 <img src="{{ file_url(directory ~ '/images/image.png') }}"/>

```
> 4 votes

---
Tags: theming, 8, uri
---


# Question
Title: How to use feeds module to import multi-value fields?
I want to import a csv file using the feed module. This feed corresponds to an article content type, but the problem is the image field in the article content type contains multiple images. If I want to use the feed module to import, I can only import one image, if I paste multiple image urls, this causes errors.

# Answer
> 9 votes
Feeds and Feeds Tamper worked for me too. To get one row for each multi-value field I used the `GROUP_CONCAT()` function from MySQL. I used this in conjunction with the Feeds\_SQL module.

# Answer
> 2 votes
I just don't think Feeds supports multi value feeds that way.

I briefly considered Feeds Tamper, that is capable of making various manipulations to the indata, but I don't see how it could solve this particular problem.

I think your best bet, short of a big patch to feeds, is to override the Feeds Processor. I have an answer with an example of that here: Using feeds module to import to user reference fields.

# Answer
> 2 votes
I had the same problem and installed the Feeds Tamper module. I then mapped my multi-value field in my custom importer and added a `Explode` plugin through the `Feeds Tamper UI`. The plugin will turn a comma separated list into an array.

Here's one row from my csv file:

```
GUID, title, image
1, "sample product", "images/image1.jpg, images/image2.jpg, images/image3.jpg"

```

This solved the problem and made it possible to connect more than one image to my multi-value field.

# Answer
> 1 votes
Feeds Tamper solves this easily with the Explode plugin.

# Answer
> 1 votes
At first Explode didn't work for me. After trying several thing I tried to add a different string separator for the multi list. So, instead of a comma (,) I used a pipe (|) and the multi list came in on import for my nodes. I was using taxonomy and a term reference field.

# Answer
> 0 votes
I have written a blog post on how to import data from a multi row csv file into a CCK multigroup in Drupal. It involves the Feeds and Feeds Tamper module and a bit of VBA code. It could maybe give you some pointers.

# Answer
> 0 votes
This Blogpost did the trick for me: enter link description here http://thejibe.com/blog/12/09/feeds-importing-multiple-values-one-multi-value-field

Maping multiple csv sources to one target field:

Source\_01 \> Target\_Field
Source\_02 \> Target\_Field
Source\_03 \> Target\_Field

Then using Feeds Tamper to rewrite the Source\_03:

Use REWRITE and as REPLACEMENT PATERN do:

Source\_01, Source\_03, Source\_03

Then use a second plugin: EXPLODE. Make sure that the string separator is the same as the one you have used in the Rewrite plugin (,)

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


title: SOAP with custom form select

text:
# Question
Title: SOAP with custom form select
I'm getting results from a SOAP call, but cannot display the values in a select list on my custom module. This is a part of my code:

```
foreach($sxml2->NewDataSet->DepCity as $item) {
    $fromName = $item->Name;
    echo '<li>' . $fromName . '</li>'; //It displays correctly

    $form['from'] = array(
        '#type' => 'select',
        '#title' => t('From'),
        '#options' => $fromName,
    );
}

```

$sxml2 is a simplexml load string result and it's display correctly. When I echo the result from the loop ($fromName), I'm getting all the strings properly, but If I try to put that variable in a custom form select, it doesn't display any data.

How can I get the results in a Drupal form select?

EDIT:

I've tried with this, but it still doesn't display anything in that select.

```
echo '<pre>';
print_r($sxml2); //The whole simpleXML object with arrays is displaying properly
echo '</pre>';

$options = array();
foreach($sxml2->NewDataSet->DepCity as $item) {
  $options[$item->Name] = $item->Name;
  echo '<li>' . $item->Name . '</li>'; //It displays correctly

}

$form['from'] = array(
  '#type' => 'select',
  '#title' => t('From'),
  '#options' => $options, //It doesn't display the data
);

```

# Answer
The `#options` property should be an array of key value pairs (the *key* is the `<option>`'s `value` attribute, the *value* is the content of that tag), so:

```
$options = array();
foreach($sxml2->NewDataSet->DepCity as $item) {
  $options[$item->Name] = $item->Name;
}

$form['from'] = array(
  '#type' => 'select',
  '#title' => t('From'),
  '#options' => $options,
);

```

That's just for demonstration, you may wish to use something other than a name for the option key - it's the sort of thing that would clash easily.
> 0 votes

---
Tags: forms
---


# Question
Title: Show products based on the location (country) of the visiting user
I need to display products based on the country of the visiting user, the countries have the same language (Spanish), but different systems of currency, I installed the module smart ip to identify the country of the visiting user and the countries module for creating the product can select the country or countries where the product will be available, my goal now is to make filter in the view to show only the products available in the country of the visiting user.

# Answer
According to the countries module page:

> **Views Integration**
>
> The 2.x branch supports View operations. The views filter is supported via 'select list' in the following way:
>
> 1. Create a Relationship (under 'Advanced') to 'Field: Country (field-country)' ('Country' being the field label, 'field\_country' the field name).
>
> The field is shown twice in the list
>
> Field: Country
>
> Field: Country (field-country)
>
> The first one is not working. This broken relationship has been removed in the latest dev version.
>
> 2. Add a Field/Filter/Sort of type 'Countries: xyz' with the new relationship.

Also, you might consider Nick's answer for hiding the product "Add to cart" based on country.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Add another item button goes missing with unlimited, repeating dates
Unlimited + repeating date fields seem to not work together. I would like to be able to add unlimited date fields that may or may not have repeating functionality.

I currently have both unlimited and repeating options enabled on a date field:

But the "Add another item" button is missing when utilizing the field on node creation:

It should be more like this except with the repeat functionality as well:

Is this possible? Has anyone seen this issue before?

Thanks!

# Answer
> 1 votes
This is not an issue. According to documentation found here - https://www.drupal.org/node/295239

> If the Date Repeat API is enabled, you will see 'repeating' as an alternative to allowing 'unlimited' multiple values.

---
Tags: 7, datetime
---


# Question
Title: How to select a particular user role which could be flagged
There are two Roles:

* Authenticated
* Artist

I have created a flag with flag type "USER".
The flag is used so that the Authenticated Users can follow the Artists.

As the flag is type of user, an authenticated user can even follow another authenticated user.

How do I restrict the *flagging* to be applied only to the Artist? i.e the authenticated user can only follow an Artist and no user of any other role.

# Answer
You can achieve your requirement by following below steps.

1. Create a view of type **User**.
2. Add a relationship to Flag.
3. Now add **Flags: Flag link** field + extra field you want to display
4. Finally add a FILTER CRITERIA i.e. **User: Roles** and select Artist user role.
> 5 votes

---
Tags: 7, flags
---


# Question
Title: Only show menu level 2 from active trail (with option Show as expanded)
I'm trying to do something pretty basic in my perspective, but I keep failing at this simple task.

My website has a main menu that is displayed on top of the page that is 2 levels deep (hence the Show as expanded). On the left toolbar it has another display of main menu, starting from `level 2`.

I have a main menu that looks like the following:

```
-link 1 (has option show as expanded)
--link 1.1
--link 1.2
-link 2 (has option show as expanded)
--link 2.1
--link 2.2

```

Problem now is that in the left toolbar all my level 2 links are always displayed, probably because I expand them. But I only want to view the children from my active trail.

Is this possible at all with the current setup? When I deselect Show as expanded, my top menu doesn't show the second level (except when I click the first level `first = active` trail).

Another problem with this new (menu) block system is that I use a template to render my main menu: `menu--main.html.twig` but both my top and left menu use this template. Is there any best practice to separate the templates?

# Answer
> 1 votes
I also discovered that if "Show as expanded" is checked, the menu is displayed at sublevels where it should not appear. This patch fix this behavior:

https://www.drupal.org/node/2631468#comment-10792980

---
Tags: routes, 8
---


# Question
Title: What order should configuration import and module updates be run?
Since the schema version of modules is stored in the key-value storage, it is unique to each site and is not synced through configuration management. That makes sense, since updates may need to make adjustments that are not encapsulated in config (such as database updates), but there are other changes that may also be included in config (e.g. adding a new config value).

* Are there any risks to running config import and database updates in either order?
* What is the preferred order for running those operations?
* Do update hooks need to make any special accommodations for config items that may have already been imported?
* Are there any other operations that may be required to fully update the production environment?

# Answer
**Updates must be run before configuration is imported**

A pending issue against core will ensure that the code and schema versions match before allowing configuration to be imported.

---

*Problems with config import before updates*

* An update hook relying on a configuration value could end in a different result than if it were run on the pre-import value.
* An update could potentially fail if it tried to create configuration entities that already exist.

*Concerns for config import after updates*

* If an update that introduces a new configuration entity is run first, it will create a new configuration item that will have a differing UUID than the one that is in config. However, once the config is imported the entity should be replaced with the config version.

There could be a potential problem here if replacing the entity would affect associated content. For example, if an update migrates content from one field to another, on config import the field would be completely replaced and the content potentially lost. In this instance the deployment process may need to be adjusted to run the updates on the target environment and export the resulting configuration.
> 13 votes

---
Tags: 8, updating, configuration
---


# Question
Title: Trying to create a link in a custom module
I have the following code \` class PopularContentParselyBlock extends BlockBase {

```
 /**
  * {@inheritdoc}
  */

 public function build() {
 $client = new \GuzzleHttp\Client();
 $res = $client->request('GET', 'http://www.APIURL.com');
 $decoded = json_decode($res->getBody(),TRUE);
 foreach($decoded['data'] as $article) {
    $url = Url::fromUri( $article['url']);
    $endpoint = Link::fromTextAndUrl($article['title'], $url);

    }
  return $endpoint->toRenderable();
  }
}

```

\`

When it prints out though all I get us Object. What am I doing wrong?

# Answer
`#markup` is used for content that has already been rendered. As the caller seems to be expecting a render array, you can just return it directly:

```
return $endpoint->toRenderable();

```
> 1 votes

# Answer
You have to put the links in some kind of a render array, for example:

```
$build['links'] = array(
  '#theme' => 'links',
  '#links' => $links,
);
return $build;

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to use the Time ago view formatter when you have an end date collected in your date field?
I have a date field in a content type with a collected "**end date**" and I want to show the end date in a view with the **Time ago** view formatter.

The problem is that I don't find where to select the **end date** only display, like in the **date and time** formatter. Because when I select the **Time ago** formatter, I don't see the options for select the **end date**. So when I go to see the view output the **Time ago** always use the "**start date**".

# Answer
> 2 votes
Have a look at the issue about "Date field's interval formatter always uses start date". It seems pretty close to what you're struggling with.

Comment # 9 in that issue also contains a patch ...

# Answer
> 3 votes
This not will solve the "realy" problem with the bug, but is a way:

If you are in a early stage of your project and you don't want use the patch you can delete the field and create two separated fields:

* initial\_date
* final\_date

I test it and this works fine.

If you want, you can read this: When should I use collect an end date for a field, instead of using 2 separated date fields?

I will add an explanation in the question about this bug.

---
Tags: 7, views, datetime
---


# Question
Title: Can't access links in block_view_alter hook
I have a two-language site with the standard language switcher block. I want to remove the link that points to the current page language (I only want the user to see one link to switch to the language they're not seeing).

I've tried this:

```
function mymodule_block_view_language_block_alter(&$build, $block) {
  $build['links'] = []; //for now for debugging purposes, remove all links
}

```

It doesn't work (though it runs the code). The `$build` array doesn't have a `links` key, or anything it's supposed to according to the `build` method in `core/modules/language/src/Plugin/Block/LanguageBlock.php`. Why might this happen? How can I alter what I'm seeing there?

BTW I also tried the `block_build_alter` hook. Similar situation.

# Answer
Those hooks are unfortunately not very useful; I don't really know why they work like that. The actual block view didn't happen yet; that's in a preprocess. You'd need to add another preprocess that runs later.

However, for your specific use case, why not use the hook that's designed exactly for this? `hook_language_switch_links_alter()`?
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: What replaced the ContentFormControllerSubscriber class?
In the past, there was a `ContentFormControllerSubscriber` class in Drupal, but there is no track of it anymore; the change records don't report anything about that class too.

The reason I am looking for that class replacement is that I noticed the Chaos tools module using a similar class to alter the requests passed to Drupal, and I was wondering if the priority (29) used in the `getSubscribedEvents()` method of those classes is still sufficient to alter the request before it is too late, and not doing it too early.
I guess the Chaos tools module used that value because it was used from Drupal core too; I am assuming there was a good reason to do so.

# Answer
It was renamed once or twice, but https://www.drupal.org/node/2613034 moved the actual code from an event subscriber to a route enhancer. See `\Drupal\Core\Routing\Enhancer\FormRouteEnhancer` for the current approach.

Good event subscribers will document how they determined what priority to use, it could have been random or very carefully picked.

See CTools' `\Drupal\ctools\EventSubscriber\WizardControllerSubscriber` which still uses 29.
> 2 votes

---
Tags: 8, event-subscribers
---


# Question
Title: Programatically render field in specific language while leveraging core content language detection
I'm working on a contrib module port to D8 and can't seem to find appropriate Entity API documentation to figure out how to get a rendered field in a specific language. I have a controller that needs to generate some custom XML based on field data, and I would like to be able to use core's language detection to get an appropriately translated field that can be used to generate this XML.

(As an aside -- I realize that core services could be leveraged to get field data in a RESTful way, but the XML schema needed here is quite custom and warrents its own REST endpoint and controller.)

Consider a route for a REST endpoint, that simply accepts the entity and field specifics needed, via the path like:

```
mymodule.xml_field:
  path: '/mymodule/xml/field/{entityType}/{entityId}/{fieldName}/{displayName}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleXmlControllerField::xmlController'
  requirements:
    _access: 'TRUE'

```

And a matching controller method like:

```
class MymoduleXmlControllerField implements ContainerInjectionInterface {

  // ... Entity manager and other services are injected ...

  public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity = $this->entityManager->getStorage($entityType)->load($entityId);
    $field = $entity->{$fieldName}->view($displayName);

    // ... Extract needed data from $field, generate XML and return it in new Response() object ...
  }
}

```

This works great until I try to leverage content translations. If I use default URL language detection and then request the XML via a language specific path (with a prefix, like: `/es/mymodule/xml/field/...`) the default lanaguage is always still used in the $field output instead of the spanish (es) translation (which I've confirmed is available on the entity).

My initial expectation was that the entity load call, or the field view call, would internally trigger language detection (as in D7), but I see that it's now up to my controller to manually specify and set a langcode somehow as the loaded entity object seems to be language neutral. I'm just wondering how I do this given that the high-level entity/field interfaces I'm using don't take a langcode paramater, and (at the time of writing) the entity API docs don't seem to address this.

I'm assuming that I need to use a setter method somewhere on the entity or fieldlist object to declare a langcode before calling the view method. It looks like I can get the detected language easily via an injected language manager:

```
$langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

```

But I'm not sure where to go from there.

# Answer
You need get Translation of entity. function entity load just load default language, not load current language. Try this:

```
public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity = $this->entityManager->getStorage($entityType)->load($entityId);

    $entity_es = $entity->getTranslation('es');

    $field = $entity->{$fieldName}->view($displayName);
    new Response() object ...
  }

```

and you need detect language to auto. Code above just example.
> 1 votes

# Answer
The answer from MrD very effectively outlines where the "language awareness" happens (on the entity) but it does not reveal how to cleanly leverage core's language detection for the example case.

Calling ContentEntityBase::getTranslation() will produce a translated clone of the base entity but it does not verify if the translation is available and provide any fallback version if not. As a result one could manually detect the language (with LanguageManagerInterface::getCurrentLanguage()) and then manually check if a translations for it exists, etc., before calling getTranslation(). However it looks like there is a single method that does all this in one call:

EntityRepository::getTranslationFromContext()

So the solution for the XML example generation case could likely be handled with one additional line:

```
class MymoduleXmlControllerField implements ContainerInjectionInterface {

  // ... Entity Type Manager and Entity Repository services are injected ...

  public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity_base = $this->entityTypeManager->getStorage($entityType)->load($entityId);
    // Get proper translation, with appropriate fallback, via core auto-detection.
    $entity_trans = $this->entityRepository->getTranslationFromContext($entity_base);
    $field = $entity_trans->{$fieldName}->view($displayName);

    // ... Extract needed data from $field, generate XML and return it in new Response() object ...
  }
}

```

As far as I know this would be a fairly universal programmatic recipe that's compatible with multilingual and non-multilingual setups.
> 0 votes

---
Tags: entities, 8, page-controller
---


title: User points category = taxonomy term

text:
# Question
Title: User points category = taxonomy term
Im using user points (module) to reward users whenever they create content on my site. Now, I\`d like to start rewarding thise points within categories (Points categories).

The categories I want in my points system are to be the terms that is available in a specific vocabulary on my site.

Exampple: User X creates a "node Y" and classifies it with "term A". In this case Id like to award user x 5 points in the "term A" category.

Anyone know how to do this?

Thanks,

# Answer
Ditch user points and download and install Rules instead.

Make sure you enable Rules UI.

Go to user fields and add a field of type **Integer**. Example: Lets name it `Term A Points`.

**React on**: (under node) **After saving new content**

**Restrict by type: None**

Add condition \>\> (under node) Content is of type \>\> select your content type (If you want multiple, hold the Ctrl button on your keyboard to highlight the content types you want)

Lets assume your term reference field is called `hello world`

Add Condition \>\> Data Comparison \>\> node:field-hello-world \>\> (type the term name here)

Add Action \>\> Set a Data Value \>\> node:author:field-term-a-points \>\> (click on switch to data selection) \>\> Data Selector: node:author:field-term-a-points \>\> Click on OFFSET and put the points you want to award, ex: `5`

You can then use the Field Permissions module if you want to hide the Term A Points field from users so they cant see it and/or edit it.

---

Then you can create another rule when Content is **deleted**, do the same except OFFSET `-5`

---

If you want to diplay a message:

Add Action \>\> (under system) Display a message on the site \>\> Type your message here. Ex: \[user:name\] you have been awarded 5 points.
> 0 votes

---
Tags: taxonomy-terms, userpoints
---


# Question
Title: How to translate metatag token into text?
I'm trying to get the data from meta tag using node\_load and for some reason when is using the default field, which is Token it gives me this ugly array.

Instead of **title** and **description** that contain the strings.

Do you know how I can translate the Token into the actual text?

# Answer
> 1 votes
I was running a very out-dated Metatag version. Once I update to the latest version I was able to run `metatags_get_entity_metatags` and get all the meta tag the way it supposes too.

---
Tags: nodes, tokens, meta-tags
---


# Question
Title: How to generate custom template for views page
I have **created a view** for content type xyz and **added fields** like title, body,image,designation, etc.

**I want to enclosed every single field of view in html structure,** so that I can see **all titles** in **red color**, **all body fields** in **blue color**, same for other fields.

what's the best approach to do this?

Edit:

**Is it possible to render fields in a way like shown :**

```
<div class = 'field1'><?php print render($view['field1']); ?></div>
<div class = 'field2'><?php print render($view['field2']); ?></div>
<div class = 'field3'><?php print render($view['field3']); ?></div>
<div class = 'field4'><?php print render($view['field4']); ?></div>

```

**in view custom template file??**

# Answer
> 1 votes
In your view, click on your field, then click on **STYLE SETTINGS**

* Checkmark Customize Field HTML, select DIV.
* Give it a class name, Ex: cool
* Uncheck Add default classes, that's just extra markup that you don't need.

**Then in your theme's .css file add**

If your title field is a link put

```
.cool a{ color: red; }

```

If your title field is NOT link (you have link this field to the original piece of content unchecked) put

```
.cool { color: red; }

```

# Answer
> 0 votes
Open your view and open the group "advanced". Now you should click on "Theme: Information".

You will see a couple of template files, that are used by your view. The templates are grouped by the view style and sorted from the most general template to most specific template.

Now you choose the desired template and copy it into to your template folder and make your modifications.

---
Tags: views, theming
---


# Question
Title: Migrating from Drupal 7: source database does not contain a recognizable Drupal version
After looking at this issue, it appears to be my schema\_version. How and what do I need to change about the table to get it recognizable as a Drupal version?

# Answer
> 1 votes
I was able to solve this after putting in the correct prefix. This issue on drupal.org was very helpful: https://www.drupal.org/node/2637870

The correct prefix for anyone with a similar problem is shown here: http://i.imgur.com/MKf6CuG.png

---
Tags: database, 8, migrations
---


# Question
Title: How do I change the date format depending on Start and End date in Drupal 7
I have a content type called 'Events' including the fields:

* Title
* Thumbnail
* Date (Can be a start, or both a start and end date)

I have created a view that takes this content type and outputs it as follows:

* Exhibition
* Thumbnail
* 17 December 2015 or 17 December 2015 - 23 December 2015

My question is how can I can change the output of the field if the 'Date' field has a start date and an end date.

I am using the Event Calendar Module to create my events.

Can you offer a solution? Thanks in advance.

# Answer
Enable the **Date Views** module

In views, click on your field and change Date Format to Custom

For Custom Date Format: you can put something like this `m/d/y` or `M d, Y`

You can format it however you want by using the format characters from the PHP manual
> 2 votes

---
Tags: views, entities, datetime
---


# Question
Title: Fields attached to Workflows do not get saved
Using Drupal 7.41 and workflow 7.x-2.8, when you attach fields to a Workflow, the fields do not get saved with the workflow field.

It's easy to replicate: Create a workflow, add a field to that workflow in admin/config/workflow/workflow/manage/workflowname/fields (ex: field\_confirm), attach a workflow field to a node type (ex: article, I'm using workflowfield here), create an article and set a workflow state & comment. Upon saving the article, the workflow state and comment get saved (see workflow tab) but no field\_confirm data gets saved or displayed. The data is not in the database either - the table field\_data\_field\_confirm / field\_revision\_field\_confirm remains empty.

Is that feature not ready yet? Or am I missing something? I tried with workflownode and it didn't seem to work either.

# Answer
Please find a full configuration steps tutorial for workflow https://www.drupal.org/node/1027546.

I also used this for my site.
> 0 votes

# Answer
Answering my own question... This is still Work in progress: see https://www.drupal.org/node/1559680
> 0 votes

---
Tags: entities, workflows
---


# Question
Title: View is rendered as "empty" even though the query returns results
I've got a Drupal View that I expect to return some results, but when I look at it (logged in as user 1), the empty result message is displayed. I turned on the setting which tells Views to output SQL in the preview. When I run the query directly against the database I get the expected result.

The View uses CiviCRM fields. I checked watchdog and the CiviCRM log for errors and found none.

The query looks like this:

```
SELECT DISTINCT <long list>
FROM {civicrm_contact} civicrm_contact
LEFT JOIN {civicrm_address} civicrm_address
  ON civicrm_contact.id = civicrm_address.contact_id
LEFT JOIN {civicrm_phone} civicrm_phone
  ON civicrm_contact.id = civicrm_phone.contact_id
LEFT JOIN {civicrm_value_agency_details_5} civicrm_value_agency_details_5
  ON civicrm_contact.id = civicrm_value_agency_details_5.entity_id
LEFT JOIN {civicrm_phone} civicrm_phone2
  ON civicrm_contact.id = civicrm_phone2.contact_id
WHERE ((
  (civicrm_contact.contact_sub_type IN  ('Agency'))
  AND (civicrm_address.city LIKE '%Brooklyn%' ESCAPE '\\')
  AND (civicrm_phone.is_primary <> '0')
  AND (civicrm_address.is_primary = '0')
  AND (civicrm_contact.is_deleted = '0')
  AND (civicrm_value_agency_details_5.accepts_food_donations_144 <> '0')
))
GROUP BY id

```

I am a little surprised it works at all; the `id` in the `GROUP BY` clause seems ambiguous.

Has anyone run into anything like this before? I am not too familiar with the Views codebase. Can anyone recommend where to throw in some debugging code to get a better sense of what's going on? Does Views do any post-query processing -- could it decide not to output what the query returns?

# Answer
This might work:

* Goto Query Settings under Advanced options and disable SQL rewriting.

---

## OR

* Try providing the view a default value for the contextual filter under "When filter value is not available option."
> 0 votes

---
Tags: 7, views, civicrm
---


title: OAuth expires_in time

text:
# Question
Title: OAuth expires_in time
I want to add the expires\_in time to the database when a user authorizes linkedin to store the token. https://www.drupal.org/project/linkedin

I have added token\_expires

```
$sql = array(
    'uid' => $account->uid,
    'token_key' => $oauth['oauth_token'],
    'token_secret' => $oauth['oauth_token_secret'],
    'type' => 'access',
    **'token_expires' => $oauth['oauth_token_expires'],**

```

and have modified the query, but it does not store the record.

```
$uid = db_query("SELECT uid FROM {linkedin_token} WHERE token_key = :token_key AND token_secret = :token_secret AND type = :type ", array(':token_key' => $oauth['oauth_token'], ':token_secret' => $oauth['oauth_token_secret'], ':type' => 'access', ':token_expires' => $oauth['oauth_expires_in']))->fetchField();

```

I would like to store the expiration time to the database that is returned from OAuth

# Answer
It appears to me that you are directly editing the sources of the linkedin module. This is considered bad practise, as any module update will remove your changes and subsequently lead to unexpected errors in your Drupal.

The reason why the queries do not work is that the corresponding database fields are missing.

You have to do several steps:

Create your own custom module. (I use MYMODULE as name in the following examples; alter that to your module's name.)

Add the linkedin module as dependency to your custom module's .info file, to make sure your changes will be removed before the linkedin module will be uninstalled:

```
dependencies[] = linkedin

```

Implement hook\_install() within your module's .install file to add the field to the database:

```
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Add additional field to table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && !db_field_exists('linkedin_token', 'token_expires')) {
    db_add_field(
      'linkedin_token',
      'token_expires',
      array(
        'type' => 'int', // I suppose, you will save a unix timestamp.
        'description' => 'Token expiry date/time',
      )
    );
  }
}

```

Implement hook\_uninstall() within your module's .install file to remove the field from the database when your module will be uninstalled:

```
/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  // Remove additional field from table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && db_field_exists('linkedin_token', 'token_expires')) {
    db_drop_field(
      'linkedin_token',
      'token_expires'
    );
  }
}

```

Implement hook\_schema\_alter() within your .module file to publish your changes to Drupals database schema information:

```
/**
 * Implements hook_schema_alter().
 */
function MYMODULE_schema_alter(&$schema) {
  $schema['linkedin_token']['fields']['token_expires'] = array(
    'type' => 'int',
    'description' => 'Token expiry date/time',
  );
}

```

Copy over the altered functions / code snippets from the linkedin module to your module, and rename the functions to MYMODULE\_your\_function\_name. Afterwards restore the original module's source code.

Implement hook\_menu\_alter() to alter the menu callbacks of the linkedin module to point to your customized functions. (Refer to function linkedin\_menu() to identify the items of question.)

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['the path of the menu callback to alter'])) {
    $items['the path of the menu callback to alter']['page callback'] => 'MYMODULE_your_function_name';
  }
  // Repeat the above step for every menu callback you like to change.
}

```

An additional note: Try rewriting as less as possible code from the original module's functions and check whether you can utilize hooks or do a call to the original function as well to make sure the application won't break once the original module is updated.
> 0 votes

---
Tags: users, authentication-authorization
---