title: Inline images that can be enlarged

text:
# Question
Title: Inline images that can be enlarged
I'm re-implementing an old Drupal 4 site with Drupal 8 and I'm stuck with what I thought was a simple task.

I want to insert some images into an article inline and be able to click on them to see a larger version. Preferably the image is shown in some kind of popover/overlay like Lightbox but even loading a new page or just the image in its original size would be OK.

With Drupal 4, I had Gallery 2 integration and this was piece of cake: just enter a placeholder like `[G2:1963]` in the body text (with 1963 being a Gallery 2 image identifier) and that's it: the image is now shown as thumbnail and when I click on it, the corresponding Gallery 2 page is opened.

I don't need Gallery 2/3 integration (and AFAIK there is none for Drupal anyway as Gallery is going the way of the Dodo). Drupal 8 has support for adding images to an article. But there doesn't seem to be a simple way of adding them *inline*.

In the CKEditor, I can add an image inline. But there's no way have it shown as a thumbnail and get the large version when clicking on it.

Then there's the image field: it allows me to add images, but they are all shown in some kind of gallery and the end (or wherever you place the field). Not what I want.

The workaround I've come up with is to hide the image field and then add the necessary HTML myself, like:

```
<a href="/path/to/image">
    <img src="/path/to/image" width="200" height="200">
</a>

```

But this is very cumbersome and feels so very wrong. So, how can I solve this in Drupal 8?

# Answer
> 2 votes
So @NoSssweat's suggestion of using *Paragraphs* seems to be the best solution to me right now. There seems to be few documentation about this, unfortunately. It took me several hours to figure everything out, that's why I wrote this looong step-by-step guide:

* Download and install the *Colorbox* plugin.
* Download and install the *Entity Reference Revisions* plugin. This is a requirement for *Paragraphs*.
* Download and install the *Paragraphs* plugin.
* Go to *Management* \> *Structure* \> *Paragraphs types*
    + First, we need to add a paragraph type. Click the *"Add a Paragraphs type"* button.
    + Give it a name and press *"Save"*. I named mine *"Text with image (left)"*.
    + You're back at the *"Paragraphs types"* node. You can now see your new paragraph in the table. There's a column *"MACHINE NAME"*, this is going to be important later on when we're theming the paragraph!
    + We now need to configure the paragraph, so click the *"Edit"* button next to your new entry.
    + Click on *"Manage fields"*.
    + We're going to add two fields. These are the values that you set for your paragraph when you're adding it your content later on. Press *"Add field"*.
        - In the *"Add a new field"* drop-down box, select *"Image"* (in the *"Reference"* group) and give it a name (for example… *"Image"*). Press *Save and continue*.
        - Now the editor for the *"Image"* field is shown, with the *"Field settings"* tab being selected. The default values were fine for me, especially the *"Allowed number of values"* being 1. So I pressed *"Save field settings"*.
        - You should still be in the editor for the *"Image"* field, but now the *"Edit"* tab is selected. Here you can configure a few things about the image itself, like it's minimum and maximum sizes, which file types to allow and so on. The *"Required field"* checkbox is notable, it tells whether you must set an image when you're using the paragraph. I'd say yes, so enable this checkbox. Press *"Save settings"* one you're done.
    + You're back in the *"Manage fields"* node. Press *"Add field"* again.
        - Now select a text field type, like *"Text (formatted, long)"* and give it a name (for example, *"Body"*). Press *"Save and continue"*.
        - In the *"Field settings"* tab, there's not much to do. We only want *"Allowed number of values"* to be 1. Press *"Save field settings"*.
        - In the *"Edit"* tab, also enable the *"Required field"* checkbox. Press *"Save settings"*.
    + We're back on the *"Manage fields"* page of the paragraph. In the *"Manage form display"* tab you can configure how the UI to add content to your paragraph will look like. I just changed the size of thumbnail here, the rest was OK for me.
    + Go to the *"Manage display"* tab.
        - I set the labels for both fields to *"-Hidden-"* as I don't want them to be shown when the paragraph is rendered.
        - For the *"Image"* field, set the format to *"Colorbox"* and press the gear symbol on the right to configure how the image is going to be rendered. Specifically, set the *"Content image style"* to a suitable thumbnail size, for example *"Medium (220x220)"*. I don't know yet where you define your own, but the *Medium* selection suited my need anyway. Press the *"Update"* button when you're done.
* We're now done with the paragraph. Next, we need to add a suitable content type or modify an existing one. Let's set up a new one:
    + Go to *"Manage"* \> *"Structure"* \> *"Content types"*.
    + Press *"Add content type"*.
        - We need to give it a name, for example *"Paragraphs page"*. All the other values were fine for me, so I just pressed *"Save and manage fields"*.
        - You're now on the *"Manage fields"* tab. By default, there's one entry in the table named *"Body"* of type *"Text (formatted, long, with summary)"*. We don't want it, so click on the down facing triangle next to *"Edit"* and select *"Delete"*. You're asked whether you want to do so, confirm by pressing *"Delete"*.
        - Back on the *"Manage fields"* tab, press *"Add field"*.
        - In the *"Add a new field"* drop-down box, select *"Paragraph"* (in the *"Reference revisions"* group) and give it a name (I named it *"Paragraph"*…).
        - Press *"Save and continue"*.
        - You should now be on the *"Field settings"* tab of your paragraph field. For *"Type of item to reference"*, make sure *"Paragraph"* is selected and you probably want the *"Allowed number of values"* to be unlimited. Press *"Save field settings"*.
        - You're now on the *"Edit"* tab of your paragraph field. **Do *not* enable the *"Required field"* checkbox here** as this triggers a bug that prevents you from saving when you add new content (you can't save and get the message *"This value should not be null."* due to this bug). Just press *"Save settings"*.
        - In the *"Manage form display"* tab you can again refine how the UI for adding content will look like. The defaults are fine.
        - Go to the *"Manage display"* tab, it allows you to tweak how the content is rendered. I don't want labels so I set the label for the paragraph field to *"-Hidden-"*. Press *"Save"*.
* Now we're able to actually create content, although it won't look the way we want it yet. Let's try it anyway:
    + Go to *"Manage"* \> *"Content"* and press *"Add content"*.
    + Select your new content type, in my example it was *"Paragraphs page"*.
    + Enter a title.
    + You'll see a message *"No Paragraphs have been added yet. Select a Paragraph type and press the button below to add one."* Below that message is a button that starts with *"Add"* followed by a paragraph name. In my example, it's named *"Add Text with image (left)"*. Press it.
    + You can now select an image (you may need to set the *"Alt"* field as well) and enter some text for the body. Do so and press *"Save and publish"*.
        - You can add multiple paragraph per page. Just press the *"Add …"* button above the *"Save and publish"* button to add another paragraph.
    + If everything is alright, you will now see your image and your text. Depending on how you arranged the fields in the *"Manage display"* tab of your paragraph type, either the image or the text is on top. But we wanted the image to be next to the text. To do that, we need to theme the paragraph.
* So the final step is to theme the paragraph. This is under-documented part, IMHO. Here's how to do it:

+ This needs to be done on the server's filesystem, either by shell or some file transfer software. It depends on your setup.
    + I'll call the top-level Drupal directory `DRUPAL_ROOT`. That's the directory with `core`, `modules`, `sites`, … subdirectories.
    + The Paragraphs module comes with basic template for theming. It's located at `DRUPAL_ROOT/modules/paragraphs/templates/paragraph.html.twig`.
    + You'll need to copy that file to the current theme's directory with a special filename.
        - There might be a better way to do this, please let me know if there is. It feels hack-ish…
        - Find the theme's template directory: there's some directory that contains `*.html.twig` files. You need to locate that. I was using the *Bootstrap* theme, the correct directory for that theme is `DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/`. For *Bartik*, it's `DRUPAL_ROOT/core/themes/bartik/templates/`.
    + You also need the *machine name* of your paragraph. I mentioned it above, you can find it by going to *"Manage"* \> *"Structure"* \> *"Paragraphs type"*. Look at the *"MACHINE NAME"* column.
        - For my paragraph, that name is `text_with_image_left_`.
    + Now, copy the `paragraph.html.twig` file into your theme's template directory and rename it to `paragraph--<machine_name>.html.twig`.
        - My file thus is named `paragraph--text_with_image_left_.html.twig`. Since I was using the *Bootstrap* theme, the path thus was `DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/paragraph--text_with_image_left_.html.twig`.
    + Edit the file. I don't know what the stuff between `{%` and `%}` is for, I didn't need to tweak it. Just edit the HTML to look like this:

    ```
    <div{{ attributes.addClass(classes) }}>
        <div style="float: left; margin-right: 1em;">{{ content.field_image }}</div>
        {{ content.field_body }}
    </div>

    ```

    - The `content.field_image` and `content.field_body` correspond to your paragraph's field names. You can see those in the *"MACHINE NAME"* column of your paragraph's field list (*"Manage"* \> *"Structure"* \> *"Paragraphs type"*, press the arrow next to the *"Edit"* button and select *"Manage fields"*).
    + Save. Now you need to clear Drupal's cache: *"Manage"* \> *"Configuration"* \> *"Performance"* \> *"Clear all caches"*.
    + We're done! Reload the test page you've created before and the text should now flow around the image. Clicking the image should open the large version.

# Answer
> 1 votes
> Yes, I want to display images inline. Like, there's a paragraph and next to it is an image.

Then I recommend you use:

### Paragraphs

> Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.

Check out this video demo

---

For enlarging images you could use:

### Colorbox

> is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.

OR

Use something like Lightbox2 with Image URL Formatter which will require you to do some custom work with the paragraphs template file to get the lightbox to work.

---
Tags: 8, media
---


# Question
Title: Deleting a field from a content type deletes the view where that field has been included
Have started to play with Drupal8 recently by trying to jump from D6 to D8, skipping D7 part. While playing, have tried to re-create a simple slideshow view, using a separate "slideshow" content type and an existed image field.

Since an upload via old image field hadn't worked, decided to delete and re-create that field **after** slideshow view was created.

But, it seems, that Drupal has deleted not only an image field from a content type, but a View, where that field were included.

Has anyone seen something like this, or is there anything wrong with my configuration?

# Answer
Yes, that's what currently happens. Drupal informs you on the delete confirmation page that will be deleted.

https://www.drupal.org/node/2468045 is an issue that tries to improve it so that the view updates itself instead.
> 1 votes

---
Tags: views, 8
---


title: Breadcrumbs from menu URL

text:
# Question
Title: Breadcrumbs from menu URL
I have implemented breadcrumbs in Drupal 7, using the following code in mytheme.inc file. It is working fine for all the custom pages but for a particular content type lets say CT1, I have url alias setup as homepage/page2/page3/\[node:title\] so the breadcrumb trail display as homepage \> page2 \> page3 \> title of content but it is only displaying as homepage \> title of content. Please advise what I am missing here to make it work the way I want.

```
function mytheme_breadcrumb($variables)
{
    $breadcrumb = $variables['breadcrumb'];
    $crumbs = null;
    if (!empty($breadcrumb)) {
        $array_size = count($breadcrumb);
        $i = 0;
        while ($i < $array_size) {
            $crumbs .= '<li>' . $breadcrumb[$i] . '</li>';
            $i++;
        }
        $crumbs .= '<li class="active">' . menu_get_item()['title'] . '</li>';
        return $crumbs;
    } else {
        return '<li class="active">Homepage</li>';
    }
}

```

# Answer
You might want to try a community solution for this like breadcrumbs by path

Your custom function isn't doing anything with the url path itself, it's just using the breadcrumb variable. You can get the path with:

```
$_SERVER['HTTP_HOST'] . request_uri();

```

Then you could split by '/' and use drupal\_set\_breadcrumb to set it.
> 0 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Can I have both Language and Country path prefixes?
On our site, paths are all prefixed by language and country. For example:

http://example.com/en/us/about

In Drupal 7, a previous vendor implemented this by using the Persistent URL module, which rewrites all on-page URLs to include the prefix of your choice. PURL was used to add add the country as a prefix to each path. However, it fails when URL Prefix language negotiation is turned on, requiring a core hack to locale.inc to make both work together to avoid the language negotiation from stomping over our prefix:

```
@@ -462,7 +462,7@@ -462,7 +462,7 @@ function locale_language_url_rewrite_url(&$path, &$options) {

       case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
         if (!empty($options['language']->prefix)) {
-          $options['prefix'] = $options['language']->prefix . '/';
+          $options['prefix'] = $options['language']->prefix . '/' . $options['prefix'];
         }
         break;
     }

```

We are rebuilding the site in Drupal 8, and this is one of the things we need to figure out. Obviously, we'd like to avoid having to reinstate some kind of core hack, but by the same token, we can't change the URL structure due to client requirements.

Is there any way we can pass and preserve both language and country information via path prefixes?

# Answer
you can either use pathauto patterns or pathologic which is still -dev .. to adapt your paths.
> 0 votes

---
Tags: 8, i18n-l10n
---


title: Does Views cache row entity?

text:
# Question
Title: Does Views cache row entity?
I have a Views of users.

Does user\_load($row-\>id); will load a user from cache?

# Answer
Yes and no.

`user_load()` leverages a per-request cache. This is implemented as a static cache in the entity controller (see the `DrupalDefaultEntityController` class). So, if the same user is loaded multiple times during the same request, the subsequent loads will come from the static cache.

In a base install, entities are not cached between requests. But, fields attached to entities are cached in the `cache_field` bin.

Data for views may or may not be cached, depending on your global Views settings and overrides for a particular view.

If you have the Entity Cache module installed, then entities are cached between requests in whatever backend you have defined. There are almost no reasons to not have this module installed on a site. It provides huge performance improvements, especially with non-SQL cache backends.
> 3 votes

# Answer
It should load from the cache, if the object is set there.

As defined in the API:

```
user_load($uid, $reset = FALSE)

```

$reset will by default force loading from the cache.

https://api.drupal.org/api/drupal/modules!user!user.module/function/user\_load/7

Hope this helps!
> 0 votes

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


# Question
Title: How do I get the property of a node object?
I am trying to get the *moderation\_state* property from a node object in Drupal8 (see attached image); however, I cannot work out how to do this. In Drupal7 it was pretty straight forward `$node->moderation_state`.

How can I get this value in Drupal8 where $node is an instance of Drupal\node\Entity\Node?

I have tried: $node-\>moderation\_state $node-\>moderation\_state-\>value

# Answer
> 17 votes
Firstly, some background.

When you type `$node->something` you're getting a FieldItemListInterface. How do you know what values you can use for `something`? Well you can ask the entity. `$node->getFieldDefinitions()`

Now you have a `FieldItemListInterface` you can iterate over its values, or in the case of single-value field, just its first one. So even if you're using `$node->title`, title is a `FieldItemListInterface` even though you'd only expect one item in the list.

So lets get the first value in the list. `$node->something->get(0)`. This gives you a FieldItemInterface. From here you can access the properties of the field item. E.g. `$node->title->get(0)->get('value')`. Each of these is an instance of TypedDataInterface. But how do you know what you can use for `value`. E.g. For an entity reference field `$node->some_er_field->target_id` is valid but `$node->some_er_field->value` is not. Well you can ask the `FieldItemInterface` like so `$node->title->get(0)->getProperties()`. Or alternatively, you can know the data-type of the field and inspect its `propertyDefinitions` method. E.g. in the case of moderation\_state field, it uses an Entity Reference field to track the reference to the moderation state config entity. So that means each `FieldItemInterface` is actually an EntityReferenceItem and you can check its ::propertyDefinitions() method to see what properties it defines.

So now you have a `TypedDataInterface` object, how do you get it's value? Well you use its `::getValue()` method.

But wait why does `$node->title->value` work - I don't have to write `$node->title->get(0)->get('value')->getValue()` \- well thats because we're using PHP magic methods on `FieldItemListInterface` and `FieldItemInterface` such that `$node->title->value` calls `$node->title->get(0)->get('value')->getValue()` for you.

So in summary:

* `$node->moderation_state->get(0)->get('target_id')->getValue()` will give you the moderation state config entity's ID.
* `$node->moderation_state->get(0)->get('entity')->getValue()` will give you the ModerationState config entity, so you can use its methods direct - like `::isPublished()` and `::label()`.
* `$node->moderation_state->target_id` and `$node->moderation_state->entity` would achieve the same thing respectively.

I did a lightning talk for my colleagues on this, if you're interested the slides are here unfortunately the recording didn't work.

# Answer
> 1 votes
This is a protected value. You won't be able to access it with kint() or toArray(). The node object protects this, because it wants you to use the node interface to read the status:

```
$node->isPublished()

```

This strict handling of protected values in drupal 8 will make your code survive longer, hopefully in drupal 9 and beyond. Because now there are changes inside the node object possible, without reflecting the interface to the outside.

Edit: Looked in core for `moderation_state`, it's not there, probably contrib. You have to look in available methods, which public function will give you the information similar to `$node->isPublished()`, which is for `status`.

---
Tags: 8, nodes
---


# Question
Title: Using RNG with a seminar with multiple optional sessions
I just installed the RNG module and have been playing around with it a bit - but I'm still unsure as to the best way to set it up for my situation.

I help to organize several seminar events a year that run for about three time blocks a day, and each time block has up to 10 different, optional sessions to sign up for.

Each registrant can only register for one session each time block, and each session needs to have a variable maximum number of registrants allowed as they're all held in different rooms of varying sizes.

I think I've sussed out that each session will need it's own event, so that I can define a maximum number. But I'm not sure how to tag certain `events/sessions` as belonging to a specific time block, and then how to ensure each user can only sign up for one session in each block and that once a session has reached max it will be `disabled/greyed out/removed` as an option.

Thanks for your time, and thanks for the great module!

# Answer
What you have so far sounds good, and you're on the right path by setting each seminar to be an RNG event. Unfortunately there is no "conference track" support built in, so you will have to write some code to prevent new registrations based on predefined constraints.

What I would do is add a date field on each session, then another field indicating which track each session is on.

RNG uses the entity reference plugin system to determine if a user is eligible for each event. What you can do is create a `hook_query_alter` implementation in a custom module. In that hook, you can determine which event the query is for. Then with partial assistance from the RNG API, determine if there are any events the user is registered with the same constraints as the queried event. If you want to allow the user then you do no modifications to the query. If you want to prevent the user from registering, you can add on a condition hack which never evaluates such as `$query->condition('uid', NULL, 'IS NULL');`

I understand this solution may be complex, especially if you are not a coder or familiar with Drupal 8 API's. Check out `UserRNGSelection.php` for some inspiration.

**Side note**: I am maintainer of RNG.
> 0 votes

---
Tags: rng
---


# Question
Title: How can I set the value of a taxonomy term reference to multiple terms using PHP?
This question describes how to set the value of a term reference field using PHP. But what do I do if I want to set the value of a term reference field in the user profile to multiple terms?

I am trying to set the value to term IDs 27 and 28. Here is my code so far:

```
$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
user_save($user);

```

# Answer
Assuming the field is set up to accept multiple records...

```
$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][1]['tid'] = 28;
// etc

```

Or you can just keep appending to the array (without knowing the next available index) like this:

```
$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 28;

```
> 7 votes

# Answer
You can assign to a list value that contains entity metadata wrapper. For example:

```
<?php
  $wrapper = entity_metadata_wrapper('user', $user);
  foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
    // $term_wrapper may now be accessed as a taxonomy term wrapper.
    $label = $term_wrapper->name->value();
    $tid = $term_wrapper->tid->value();
    // you can also set the values
    $term_wrapper->name = 'New label';
    $term_wrapper->tid = array(123, 1234); // or ...
    $term_wrapper->tid->set($tids_to_set);
  }
  $wrapper->save();
?>

```
> 1 votes

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


# Question
Title: How to hook "/system/ajax" with javascript in Drupal 7
When a field accepts multiple values, the admin form adds a button "Add another item". Mousedown submits a POST to /system/ajax to get another field (i'm using multifield here).

I'd like to hook into the javascript completed event to do some custom handling on those additional fields.

How can I most easily hook these ajax calls for javascript callback and reference to the block being added? Is it possible without PHP?

# Answer
> -1 votes
You can use `hook_menu_alter` and define your own custom callback function like below.

```
function demo_pane_menu_alter(&$items) {
  $items['system/ajax']['page callback'] = 'demo_pane_taxonomy_autocomplete';
}

```

---
Tags: 7, javascript, ajax
---


# Question
Title: Show table header in views (Bootstrap table)
I need to show header table in a view (bootstrap table) like: title, image, descripton, etc. But i can't find the option. I compare this view to an old one and everything seems normal. Any idea? Thanks!

# Answer
You can check if your label of the row is enabled or checkbox is checked which shows `Show Label`. Go to fields in view, and click on any field, you can see that option.
> 1 votes

---
Tags: views
---


# Question
Title: Importing pre-built content into the site
There are frequent installs of Drupal 7 that I do. All of them are almost the same, except, some need to have additional content types and modules on top of the default setup. I'd like to ask if there is a way to modularize the deployment to save time on manually creating content types and installing modules.

Example:

1. (Required) I download and install Drupal 7 (possibly Drupal 8 in the future) with minimal profile
2. (Optional) I import a "magic package" (prebuilt) that would import all the custom content types I made, menu items, views and extra modules into the site created in step 1.
3. (Optional) I import a second "magic package" (also prebuilt) that would give site more capabilities with additional modules, menu items, views and content types.

some of the imported stuff is linked to Drupal users via Entity Reference fields.

What is the best way to accomplish something like this? Is there a module that can help me build these "Magic Packages"?

Thank you.

# Answer
> 1 votes
Creating a feature could be what you need. Have a look at its project page. https://www.drupal.org/project/features

# Answer
> 0 votes
I would recommend looking into drush make and .make files and custom installation profiles. You can set up a pretty solid base sites this way.

---
Tags: importing-exporting
---


# Question
Title: How to create a confirm popup when delete item with field collection?
I have configured a field collection field (unlimited items) for a content type and I want create a confirm popup when user delete an item. For this, i found that i can directly go and modify 2 functions in the `field_collection.pages.inc` file. They are:

**1. field\_collection\_item\_delete\_confirm**

**2. field\_collection\_item\_delete\_confirm\_submit**

I'm a newbie in drupal so I don't know how to use these function from the field\_collection.pages.inc file, I tried to hook these function in `template.tpl` file but it's didn't work. Can someone help me ? Sorry about my English.

# Answer
Here is what i did, to handle the deletion of a field collection item for a node:

* Created a hook of type `hook_node_view()` in my custom module and overridden the delete link for the field collection items, so that they point to a custom path, that is declared in my custom modules `hook_menu()`.
* Now the custom path is mapped to a template file (passing the field collection item id).
* The logic inside the tpl file processes the deletion of field collection item (passed by id) using `entity_delete_multiple()` and sets a custom message to be displayed back to the node view page.

more details
> 0 votes

---
Tags: 7, entities
---


title: 500 server error on clear cache

text:
# Question
Title: 500 server error on clear cache
I am facing a pretty strange problem. I have installed Drupal 7 on my site. Whenever I install a module and tries to access the module's configure page after enabling the module, it leads me to simply /admin/config page without showing the option for that particular module configuration.

sometimes when I do a clear cache the problem gets resolved and then I can access the module's config page. but sometime after installing a module, clear cache gives Internal Server Error 500 .. also I tried to flush the cache manually by making a php file into / directory with the following code:

```
<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_flush_all_caches();
?>

```

but this also gives Error 500.

When I disable the installed module, clear cache works as usual... please help me.

# Answer
As directed by aerozeppelin I got the following error:

> Fatal error: Allowed memory size of 50331648 bytes exhausted (tried to allocate 4096 bytes) in /home/htdocs/includes/database/query.inc on line 1857

So increasing the PHP memory limit is the cure; this link is useful for that.
> 1 votes

# Answer
In a file type

```
<?php
phpinfo();
?>

```

to know your php configuration. Here you can know the path of php error\_log or type

```
<?php
print_r(error_get_last());
?>

```

to get the last error that occurred.
> 0 votes

# Answer
May be this is a late answer.But it will help for new people.

1. Try to add this in .htaccess file.

**php\_value memory\_limit 64M**

I hope this will help you to solve the Internal Server Error in Drupal 7
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How can I see multiple terms on a single view?
I have a content type called "Listing". This listing has a taxonomy reference called "Amenities". A single listing can have several or no amenities and each term has a field on it called "icon".

I want to create a view that shows:

* TITLE
* Amenity 1, Amenity 2, Amenity 3

Instead of text, I want to show icons.

I was able to figure out that you can use "relationships" to get to the icon field on the term. However, it only shows ONE term from the list. There doesn't seem to be any aggregation or grouping by happening. Which means it shows the same listing over and over, for each term. Instead of showing the listing once, and all the term images below that.

What am I missing?

# Answer
Grouping can be enabled in Format section of your View \[Format \> Settings\]. Select title field for grouping and then exclude it from display to avoid rendering it twice. Aggregation in this case will not give you the result that you're looking for.
> 1 votes

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


# Question
Title: Second Product variant image in fb share is not coming
I am using \[node:field-product:0:field\_images\] metatag image. With which I am getting top level variant image always. How can I get my second product variant image in facebook share, when I select second product variant from the variant selection dropdown on product display page.

# Answer
```
[node:field-product:1:field_images]

```

You'd add that in your metatag image field together with the first token that you mentioned, separated by comma.

If fb is still not picking it up, after your fetch new scrape info, try adding `:file:url` to your tokens.

```
[node:field-product:0:field_images:file:url],[node:field-product:1:field_images:file:url]

```
> 2 votes

---
Tags: commerce, tokens, meta-tags
---


# Question
Title: RSS Feed does not validate using Views RSS module
Drupal version: 7.14

Views RSS version: 7.x-2.0-rc3

I am trying to validate an RSS feed in feedburner for a drupal blog. When I try to validate de xml file at feedvalidator.org I get this error

`line 3, column 0: XML parsing error: <unknown>:3:0: XML or text declaration not at start of entity`

The xml file is well written (I compared it against another one which validated) and the error I found is that that xml file generated by Views RSS puts three blank lines at the beginning and therefore I think the file does not validate.

I've looked for answers in the oficial Views RSS module issue track but unsuccessfully. I've also created many feed views using Views RSS module, but all of them provide the same error at feedvalidator.org.

I'd like to correct this through the source code of the module, but I do not know where to start or which file I should edit to correct that mistake, just if only through code I could solve this validation.

# Answer
> 1 votes
In some cases this error will be caused by space in one of your modules. Best way to find the issue is to edit module.inc file in includes folder and add this after the drupal\_load function in the module\_load\_all function:

```
print $module.'|';

```

you will probably get a huge list but one that starts on line 3 will be the issue.

# Answer
> 1 votes
The cause of the problem is a 'SPACE' at the beginning of a unknown module script.

1. Find the script causing this problem:

grep -n -o -R \ \\\<\\?php * |grep :1:
2. Delete 'SPACE' at the beginning of the found script
3. Delete Cache

# Answer
> 0 votes
Try changing the file Steven mentioned in the comments (views\_rss/theme/views-view-views-rss.tpl.php) from this

```
<?php
/**
 * @file views-view-views-rss.tpl.php
 * Default template for feed displays that use the RSS Fields style.
 */
?>
<?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<?php print $rss_feed; ?>

```

to this

```
<?php
/**
 * @file views-view-views-rss.tpl.php
 * Default template for feed displays that use the RSS Fields style.
 */
?><?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<?php print $rss_feed; ?>

```

If that does work, I'm sure the views\_rss maintainers would be very grateful if you'd submit a patch :)

# Answer
> 0 votes
I'd like to add more insight about @pgrujic solution. We use Services to generate custom RSS feeds and we faced the exact same problem with blank spaces at the beginning of the XML document. Once you added the following line of code to the file -

```
print $module.'|';

```
* It printed out a line with the name of modules separated by a pipeline. You'll have to find a blank space before of a name of any module.

For example, if you find something like this:

```
ckeditor| color|comment|

```

It means the color module has a blank space. Remove it and happy feed!

Sorry, couldn't reply in the same treat because the low reputation

# Answer
> 0 votes
It mostly due to spaces at start before `<?php` tag in module or no ending tag in tpl file.

Mostly it is module file so...

```
grep -R -H '^  <?php' modules/**/*.module

```

This will check all module files withing your module folder ( i am a step back in my sites/all folder in my linux terminal to find culprit.) If you find two spaces leave two space between ^ and

If you just get the filename you can find its path via

```
locate -br 'culprit.module'

```

After correcting clear cache. :)

---
Tags: views, feeds, forms
---


title: Show referenced entity

text:
# Question
Title: Show referenced entity
I have 2 content types. For example UserGroup and User. UserGroup has Entity reference field and there are unlimited of Users. I would like to show in views something like this:

* User group name

+ User 1
    + User n
* User group name

+ User 1
    + User n

and for the User their fields (contact, birthday etc.)

Now I set relationships field\_users (which is set in UserGroup) and Format -\> Show -\> Fields. There are Name (UserGroup), Name (User via relationship) but I see:

* UserGroup1
    + User1
* UserGroup1
    + User2

and etc.

Please tell me how can I fix it. Thank you.

# Answer
> 0 votes
Select the group level in Views here:

and then here

---
Tags: views, 8
---


# Question
Title: Theme specific drupal commerce product form
I want to create a .tpl file for each specific product type form. I get that I can create a custom product template and add this code on my theme's template.php:

```
'commerce_product_ui_product_form' => array(
               'arguments' => array(
                    'form' => NULL,
                    ),
               'template' => 'templates/products form/node--add--product', // set the path here if not in root theme directory
               'render element' => 'form',
            )

```

The problem is this changes all the product type's form. How can I find the Form ID for each specific product type form?

# Answer
It's the same form ID for every type, but you can find context in the form state, e.g.

```
function MYMODULE_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['commerce_product'];
  $product_type = commerce_product_type_load($product->type);

  if ($product_type->name == 'foo') {
    // ...
  }
}

```
> 0 votes

---
Tags: theming, forms, commerce
---


title: text input in datepicker

text:
# Question
Title: text input in datepicker
how can i add some default text in my datepicker ? I want to add text in the box.

# Answer
Edit you field in Manage fields section of your content type and set default value for that date field.
> 0 votes

# Answer
I've solved my problem. I added this code screen.js

jQuery('#datepicker\_id').attr("placeholder", "text");
> 0 votes

---
Tags: datetime
---


title: Let the user choose the field type

text:
# Question
Title: Let the user choose the field type
I'm working on a drupal project and part of it is a sort of "tile overview" page. Its a 3x? grid, with a variable length.
|--|--|--|
|--|--|--|
|--|--|--|
|--|--|--|
.. .. ..
Sort of like that, I hope you can tell what I'm trying to describe.
Each row of 3 is a field\_collection. Now, each field can be either an image field or a text field. I want the user to be able to choose. How would I implement such a feature?
My solution as of now is to have 6 fields per row: one image field and one text field per each single field. Then the user would be told to only fill in one. If he fills in both, one of them gets ignored (php: isset() priority). Obviously this is far from optimal. What I'm looking for is like a radio button functionality so that when the user has a value set for one of the two possible field types, the other one gets disabled. Or just let the user decide first which he wants and then only display that one.
Help would be much appreciated.

# Answer
> 0 votes
Check this module:

Conditional Fields

This module lets you to set things such a visibility, depending on other form elements.

It works based on Drupal's States API ( which you could also use in your custom module to achieve what you want )

---
Tags: entities
---


title: Drupal 8 alter existing field setting

text:
# Question
Title: Drupal 8 alter existing field setting
How to alter existing field type instead of creating new one to add new options with custom processing for insert and display of the field.

**Use case** : upgrade hijri taarikh project that extends the default date field types allows to use Hijri calendar for both select list and popup letting the user add Hijri dates and display Hijri dates.

# Answer
To alter how to insert content into the field, define your own field widget and then apply the new widget for the existing field in "manage form display" of the content type.

Field Widget

To alter how the field is displayed, define you own field formatter and apply it in "manage display" in the same way:

Field Formatter

When you start with a field widget or field formatter, the fastest way is to copy an existing one out of core and modify it or use drupal console to generate the scaffolding.

If you only want to modifiy an existing widget/formatter, then extend it, not write a complete new one. This is a good explanation, how to do this:

http://www.sitepoint.com/creating-custom-field-formatters-drupal-8/
> 2 votes

---
Tags: 8, datetime, entities
---


title: Add javascript to form by module

text:
# Question
Title: Add javascript to form by module
i am writing a module in drupal 8. I wish to add a javascript when loading that form.

```
function ajax_example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#attached']['library'][] = array('ajax_example', 'ajax_example.sync_script');
}

```

and i have defined the following at the module library yml file

```
sync_script:
  version: 1.x
  js:
    js/test.js: {}

```

but seems the js is not embedded. And i have put the js in a folder called js at the root directory of the module.

What is the way for drupal 8 to embed a javascript at the form?

# Answer
> 27 votes
**Update Feb. 2023**: Hey friends! I am not writing Drupal modules for years. Please keep in mind I am not well up-to-date. This answer could not function as expected at this point in time, so edits are always welcome.

---

I don't know what you're aiming to build.

Because I think it's not good to use your JavaScript in `hook_form_alter()`, following that way, any form you try to see will invoke that JavaScript code.

However... Back to your issue. I think the `hook_form_alter()` function should be used in `module_name.module` file under the root of your module folder: `modules/custom/module_name/module_name.module` alongside the routing, info, etc.

After building the `.module` file, you need to build the `module_name.libraries.yml` file (if it's not already built), and there you write your routing requirements, for example:

```
<library_name>:
  version: 1.x
  js:
    js/<your_javascript_file>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

Back to the `.module` file, you implement the `hook_form_alter`, so your code goes like this:

```
/**
 * Implements hook_form_alter().
 */
function <module_name>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    $form['#attached']['library'][] = '<module_name>/<library_name>';
    $form['#attached']['drupalSettings']['<module_name>']['<library_name>']['variable'] = 'value';
}

```

To make sure, `console.log` your PHP variable in **your\_javascript\_file** to see it. For example:

```
(function($){
    console.log(drupalSettings.<module_name>.<library_name>.variable); // value
})(jQuery);

```

Hope this helps!

---
Tags: 8, javascript, forms
---


title: Contextual menu link

text:
# Question
Title: Contextual menu link
I'd like to know if it is possible to create a link only if a certain condition is respected. Example with my current menu:

```
function mymodule_menu() {
  $items = array();
  $items['mycontent/%my_object/my_place'] = array(
     ---(code)---
  );
  return $items;
}

```

The link created by this menu should not be available for each instance of my\_object. This menu should only be used by objects that have for example $my\_object-\>flag set to TRUE.

In my page callback I could check the object and exit the form if the flag is not set, however the link would be still displayed and people could click on it.

Do you have any idea ? Thank you.

# Answer
> 0 votes
You can use an access callback for that sort of thing:

```
function mymodule_menu() {
  $items = array();
  $items['mycontent/%my_object/my_place'] = array(
    'access callback' => 'mymodule_foo_access',
    'access arguments' => array(1),
    ...

  );
  return $items;
}

function mymodule_foo_access($object) {
  // Contrived example, use something better
  return $object->flag === TRUE;
}

```

---
Tags: 7, routes
---


# Question
Title: How can I create a View that shows nodes without a relation?
On my site, all the nodes of content type **ABC** are supposed to have a relation (from the Relation module) to a user.

However, although the relations are usually created in Rules, somehow this didn't happen for some nodes, and to make it worse, it happened randomly (non-sequentially).

So, I would like to make a view that shows the nodes which do not have any relation-- but I can't figure out how to configure the view to do that.

If I add a **Relationship** of *Has relation Node -\> User*, I can get all the nodes that DO have a relation, but how do I get all the nodes that DO NOT have a relation?

# Answer
You can just create a new filter criteria using your user reference field, and choose "Is empty (NULL)" as operator.

That will show all nodes that don't have any value in the user reference field.
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to access current langcode in theme?
I use Integrity theme and want to make the slider images i18n aware.

I want to get the current langcode in the

```
function _integrity_get_home_block_contents

```

Previously it worked like this:

```
   global $language;
   $lang_id = $language->language;

```

What do I do now?

# Answer
Here's how to do the same in Drupal 8:

```
$language = \Drupal::languageManager()->getCurrentLanguage();
// Will return "en".
$shortcode = $language->getId());
// Will return "English".
$language_name = $language->getName();

```

Read more here.
> 1 votes

---
Tags: i18n-l10n
---


title: Display regions in user-profile.tpl.php

text:
# Question
Title: Display regions in user-profile.tpl.php
I created a region into `mytheme.info`

```
regions[list_user_poke] = List User Poke

```

I put a block in it. Then I want to print this region `user-profile.tpl.php`. I wrote this chode :

```
<div class="list-user">
   <?php print render($page['list_user_poke']); ?>
  </div>

```

But it does not appear.

Thanks for your help !

# Answer
> 1 votes
For anyone wondering about this, here's how to do it (code goes in your theme's `template.php` file):

```
function YOUR_THEME_preprocess_user_profile(&$variables) {
  $variables['YOUR_NODE_REGION'] = block_get_blocks_by_region('YOUR_NODE_REGION');
}

```

And then in your `user-profile.tpl.php` template:

```
<?php if ($YOUR_NODE_REGION): ?>
  <div class="custom-region">
    <?php print render($YOUR_NODE_REGION); ?>
  </div>
<?php endif; ?>

```

---
Tags: blocks, users, theming
---


# Question
Title: Check if referenced field exists in commerce product display
I have to render different types of product (with different fields combinations) in a generic product display `tpl` file. I created an array with all possible field names (they all are referenced `product:field_name`) which passes through a

```
if ($content[$my_field]){
  //some code
}

```

that is supposed to check if the field exists and then do things...

The problem is that it actually checks the existence of the field but shouts out a `notice: undefined index` warning for every field that is not present.

Is there a way to execute this check in a cleaner way?

Thanks!

# Answer
> 1 votes
If I understood your question correctly, you should check if that element exists; here's how:

```
if (isset($content[$my_field])) {
  //
}

```

This way if the field is not set, you won't get the `undefined index` error.

---
Tags: theming, commerce
---


# Question
Title: Feed import save empty value in multilingual site
I have a multilingual site and I am using the feed module to import content. My site has two languages:

English and Arabic.

When my excel files have English content, it imports properly.

But if excel file having Arabic content, it imports and shows in view page but in edit page it not displaying.

# Answer
> 2 votes
Feeds: Entity Translation

> This module adds support for importing data through Feeds into translatable fields handled by Entity Translation.
>
> The module exposes fields that are translatable into all enabled languages, enabling the creation of translations of entities when importing.

Another fantastic Solution

Import from two xml files (on for each language), my empiric solution :

* I created two feed imports.
* I forced the language field for each one.
* Two separated nodes were created for each content (one in each language) but it didn't links the translations.
* So I used a SQL query to finish the job, it's based on the feeds uuid

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


title: Language switcher doesn't appear

text:
# Question
Title: Language switcher doesn't appear
I have enabled the "locale" and "content translation" modules. Also I have two languages in my Drupal, Spanish and English, after that I have configured the detention method by URL.

I have finished my English page and I just need to translate the website to Spanish. When I set the language switcher to the website (the header or a columns) of my Structure I don't see anything. I can click on "translate" button of the blocks of my web, I see the "spanish" option, I click in "translate", but I get this message:

> This string uses the Full HTML text format. Strings with this format are not allowed for translation.

Ok, I change the format to Plain Text but I lost my HTML format, styles... I can't translate and I can't see the switcher to change to Spanish or English.

Drupal version 7.4.

# Answer
> 1 votes
To translate custom block text you need to do the following:

1. Download the Internationalisation module (i18n)
2. Enable String translation module (i18n\_string)
3. Go to Configuration \> Regional & Language \> Multilingual Settings \> Strings (admin/config/regional/i18n/strings)
4. Enable Full HTML in Translatable text formats
5. Save

---
Tags: theming, i18n-l10n
---


title: Selecting one result from database

text:
# Question
Title: Selecting one result from database
I am storing some data into the database

```
try {
      $fields = array(
        'uid' => \Drupal::currentUser()->id(),
        'value' => $form_state->getValue('blood_sugar'),
        'created' => time(),
      );
      Database::getConnection()->insert('blood_sugar_monitor')->fields($fields)->execute();
}

```

Later on I would like to check the latest inserted row to check if it was inserted within the last hour.

Could someone provide an example of fetching one item from the database?

# Answer
> 1 votes
You can follow the Database Abstraction API documentation. Although most of that documentation points to using the deprecated methods. You may find the current classes and methods, by clicking into each function that you need (such as db\_select), and reading the deprecated messages.

This is very similar to what you have done for inserts (using Dynamic Query).

```
$id = Database::getConnection()->select('blood_sugar_monitor')
  ->fields('blood_sugar_monitor', ['my_primary_key'])
  ->range(0, 1)
  ->orderBy('my_primary_key', 'DESC')
  ->execute()
  ->fetchField(0);

```

---
Tags: database, 8
---


# Question
Title: Which version of Drush should I install?
Drush 6 works great of corse on a Drupal 6 website, but will I have all of the Drush 6 features when working on a Drupal 7 website? Should I use Drush 7 when working on a drupal 7 website?

I found this post that says you can switch between the two version easily, is this correct?

switch to drush6 command: composer global require drush/drush:6.\*

switch to drush7 command: composer global require drush/drush:dev-master

# Answer
> 9 votes
Always, always read the docs. Right at the bottom of the first page you'll find this:

Which removes any ambiguity.

---
Tags: drush
---


title: Hosting advanced cron for Aegir 3

text:
# Question
Title: Hosting advanced cron for Aegir 3
There was one very useful contributed module named Hosting Advanced Cron. It allowed me to set cron interval per site, instead of set just global for all (and you can even disable cron on specific sites). hosting advanced cron

For Aegir 3, there is no such release and development seemed to be stopped. There is a fork on Github by omega8cc, but it is not functional (doesn't work, has error and notice, has debug statements left on), so does anyone have a solution or a replacement for such a useful feature for Aegir 3?

# Answer
> 0 votes
After discussion with omega8cc, and a bit of testing, the answer is that advanced\_cron is not any more compatible with Aegir 3. It is also merged into BOA (by omega8cc) in their core, and it is not back compatible with stand alone Aegir.

There are two options:

* port it to work with standalone Aegir 3
* use crontab and wget / curl to trigger cron on site

---
Tags: cron, aegir
---


title: How to extend link field type in D8?

text:
# Question
Title: How to extend link field type in D8?
It's good to see the Link field type in D8. It takes a URL and (optionally) link text.

I'm adding a multiple links field to a content type and would like users to be able to provide some styling clues as well: e.g. this link is the primary one, this one needs a download icon. Basically let the user add CSS classes to each of the links in the same way they can add urls, text to each link they enter.

Is there a way to adding a new part to the field type?

(EDIT: I've put the answer into a custom module)

# Answer
> 3 votes
If you check \Drupal\link\Plugin\Field\FieldType\LinkItem, you see that it supports an array of options.

LinkFormatter then passes those to the URL.

So the only thing that you need is a custom widget that allows you to select/configure classes within the options somehow.

---
Tags: entities, 8, navigation
---


title: Drupal Commerce Paypal WPS

text:
# Question
Title: Drupal Commerce Paypal WPS
I have a Drupal 7 site running the latest Drupal Commerce and Paypal WPS as a payment method. Everything is working correctly. When a customer is checking out and can pick between Paypal and credit card, the radio button for the area that lists the credit card does not show up.

Screen shot attached.

I've checked and re-checked every possible setting. Is there a way to disable the Paypal only button and enable the credit card and paypal option? Or just get the radio button to show up so users can pick.

I've inspected elements and the input tag is not present in the html.

Any help or guidance is appreciated.

# Answer
> 2 votes
PayPal WPS submodule of Commerce PayPal provides only one payment option, which redirects the user to PayPal for payment. Credit card icons are there to let users know that at PayPal's end they will be able to make the payment via PayPal balance or using listed credit cards.

You see only one radio button for PayPal WPS payment method because it is expected behavior. If you wish to allow your users to pay via credit card without leaving your website - enable PayPal WPP submodule.

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: Failed attempt at moving Drupal 8 to a clean installation of my OS.
Okay, so ive reinstalled my ubuntu OS, reinstalled the LAMP stack, ive restored the database and connected to it just fine. Ive checked which php modules drupal 8 requires and installed them, my version of php is above the 5.6 lower limit - i have not installed ALL of the php5-\* modules in apt-cache though but i dont think thats an issue(?), ive set the chmod 777 . But now my /user/login kind of routes dont work, it just gives a 404. Have anyone experience anything like this, and how to solve?

I have looked at the clean\_urls in my .htaccess, but drupal 8 clean urls should just work out of the box.

# Answer
> 1 votes
Okay so i went inside of /etc/apache2.conf and changed

```
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride none
    Require all granted
</Directory>

```

to

```
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
    </Directory>

```

that worked :)

# Answer
> 0 votes
Did you check whether you have activated the `mod_rewrite` Apache module? According to the INSTALL.txt file for Drupal 8,

> If you want to use Drupal's "Clean URLs" feature on an Apache web server, you will need the mod\_rewrite module and the ability to use local .htaccess files.

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


# Question
Title: How to show dynamic text on node/add form with Panels (using AJAX)?
I am using Panels. There is an entity reference field (project) on a content type. It shows the title of nodes where the user is the creator using the viewreference module.

On the node/add form, is there a way to show a field (body) from the node when the user selects a specific project? I am ok with contexts in panels and views, some some general thoughts might help already quite a lot.

Thanks for any tipps.

# Answer
> 0 votes
you do not need to use panels, just add an ajax callback on that form select field, where you add a node's body in the postfix of the field.

---
Tags: 7, ajax, panels, entities
---


# Question
Title: Multiple Price for same product in commerce kickstart?
I have installed Commerce kickstart. I have add the products. Now my client asked Same product have two different prices. User will choose the price and pay it.

I am trying Commerce Donate module also.This module price for every product.

I need to change the price value for every product.

# Answer
> 1 votes
Might as well jump all in using Commerce Customizable Products and use this screencast to walk yourself through adding a line item type and a field to set the price.

---
Tags: commerce
---


# Question
Title: Adjust search system - return all nodes, but exclude a specific node type if a field is less than current date
I am hoping to adjust the search system results. It works great, but i have an issue with some of the results. When a user searches "Training" I pull up all node's that have "Training" in their titles, bodies, tags, etc.

I want to continue to pull up all node types. But if one of the node types (calendar\_item) pops up, I got to check one of it's fields for a value, if it has a particular value then we exclude it. I found the best way of checking if the field has a value is by going to a different table (`field_data_field_date`) for a value in it's field (`field_date_value2`). To join that table to our current query we check `entity_id` field (in `field_data_field_date`) and compare it to the `node.nid`. Below is an example, the only issue is it actually excludes all other node types, so the only thing I bring up is calendar\_items. Anyone know How to still bring up all nodes, but if it's this particular node type do the conditional check?

Please and thank you!

```
function mymodule_query_search_node_alter(QueryAlterableInterface &$query) {
 $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id'); // No idea what the field is called, assuming 'search.date'.
 $query->fields('fd', array('field_date_value2'));
 $query->condition("{fd}.field_date_value2", '2016-03-08T21:30:00', '>=');

```

}

EDIT #1: I have now adjusted the code to the following:

```
function mymodule_query_search_node_alter(QueryAlterableInterface &$query) {
    $u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
    $query->fields('fd', array('field_date_value2'));
    // OR clause. The default is AND. To use or, you need to use:
    $db_or = db_or();
    // Add the conditions for the OR clause
    $db_or->condition("{$u_alias}.field_date_value2", '2016-03-08T21:30:00', '>=');
    $db_or->isNull("{$u_alias}.field_date_value2");
    // Pass the Or clause to the query object.
    $query->condition($db_or);

```

}

If I replace

```
$u_alias = $query->join('field_data_field_date', 'fd', 'n.nid = fd.entity_id');

```

with

```
$u_alias = $query->leftJoin('field_data_field_date', 'fd', 'n.nid = fd.entity_id');

```

I get no results! But just a simple join gives me only `calendar_item`s.

# Answer
> 2 votes
I think you need a different kind of SQL Join there, your (inner) join will produce a result set of only nodes that have an respective entry in the field\_data\_field\_date table.

I would try a left outer join and add an OR condition for field\_date\_value2 being NULL. An example:

```
$u_alias = $query->leftJoin('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
$query->fields('fd', array('field_date_value2'));
$db_or = db_or();
$db_or->condition("{fd}.field_date_value2", '2016-03-08T21:30:00', '>=');
$db_or->isNull("{fd}.field_date_value2");
$query->condition($db_or);

```

Cheers!

# Answer
> 0 votes
Stefanos Petrakis really helped here. He got me on the right track, but as I mentioned I was still dealing with issues. After reading this post I found the best solution was not creating a new `db_or()` and passing it through the `$query`'s `condition` method, but instead:

```
$query->addJoin('LEFT','field_data_field_date', 'fd', 'n.nid = fd.entity_id');
$query->condition(
    db_or()->isNull("{fd}.field_date_value2")
    ->condition("{fd}.field_date_value2", '2016-05-20T08:00:00', '>=')
    );

```

---
Tags: search, database
---


# Question
Title: Is there an easy way to prepopulate webform field default values from profile2 field values?
We are working on major project where client wants webform fields to be prepopulated from profile2 fields. Webform version 3.17

Is there any way to create tokens or similar from profile2 fields to be used on webform default values?

# Answer
> 1 votes
hook\_form\_alter(){ //and set default values form profile2\_load\_by\_user(); }

# Answer
> 0 votes
In version 4.x webforms has token support and you can add fields from profile2.

For example, if you have a profile called chef and a field called (field\_check\_age), you should use this token: \[current-user:profile-chef:field-chef-age\]

---
Tags: webforms, tokens, users
---


title: Hide Title for Rendered Entity views

text:
# Question
Title: Hide Title for Rendered Entity views
In display modes I set to hidden all Title fields, but Views still gives h2 title.

# Answer
Every page should contain a heading.

You should always maintain a structured hierarchy of headings within any web page. You should never have a blank heading or even hide it with display:none;. Hiding any content which isn’t viewable by your visitors but is by search engines is against Google’s guidelines as your intention is to only manipulate search engine results by including it. Restyle a heading tag so it fits into your design is the best option.

If you still have to hide it then a better option would be to either create a template for that node, content type or page and simply not print the heading.

> Or if you want to use CSS then use **position:absolute** so the heading doesn’t use any space where it is located in the page and **text-indent:-9999px;** so the text is moved off the screen and no longer visible but at least can be read by screen readers and search engines.
> 0 votes

# Answer
Providing a specific display without a title using the Display Suite module may be a quick way to address this. Not does it only allow you to hide the title, if you do want to display a title, you can change the heading from the default `<h2>` to `<h3>` for instance…

I've done this before with success.
> 2 votes

# Answer
Views renders the node entity using the default view mode (machine name 'full'). Drupal uses the node.tpl.php template to output the node. That template contains a condition to check for the $page variable. If that is false than it prints the title of the node as a link.

The are various solutions (such as using a different view mode or tinkering with node.tpl.php) but you can also clear the title using hook\_node\_view.

You can check if the node is the same as the one returned by menu\_get\_object. If that is not the case than the node is somehow embedded in another node or in a view (as is your case).

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  $page_node = menu_get_object();
  if ($node->nid != $page_node->nid) {
    $node->title = NULL;
  }
}

```

I havent experienced any bad side effects, yet.

See drupal.org for more info.
> 1 votes

# Answer
You can copy node.tpl.php to your local theme and check based on whether there is a view name or based on a particular view name. The following example removes the link from a specific view.

```
<?php
$view = views_get_page_view();
$view_name = '';
if (!empty($view)) {
  $view_name = $view->name;
}
?>
<article id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
 <?php if ((!$page && !empty($title)) || !empty($title_prefix) || !empty($title_suffix) || $display_submitted): ?>
<header>
  <?php print render($title_prefix); ?>
  <?php if (!$page && !empty($title) && $view_name == 'photographer_of_the_year'): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?></h2>
  <?php elseif (!$page && !empty($title)): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
...

```
> 0 votes

# Answer
If you have the **entity-module** installed, you can do the following: Copy the file

*sites/all/modules/entity/**entity.tpl.php***

into your theme-folder.

Duplicate the file and rename it to the machine-name of your entity, for example

*"commerce-product.tpl.php"*

or, to be more specific just for the teaser:

*"commerce-product--product--node-teaser.tpl.php"*

In the file you can delete (or just change) the following part:

```
<?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <?php if ($url): ?>
        <a href="<?php print $url; ?>"><?php print $title; ?></a>
      <?php else: ?>
        <?php print $title; ?>
      <?php endif; ?>
    </h2>
  <?php endif; ?></code>

```

To find the correct template-name use the **submodule "theme developer"** of the "devel"-module.
> 0 votes

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


# Question
Title: Insert data in table using drupal form alter submit
I am currently work with a drupal's inbuilt form which is coming from it's system function. Now I added a extra field with value in the form with Drupal's custommodule\_form\_deal\_node\_form\_alter(). It is working perfectly. But my problem is How to insert the value in the database with the default form's value. As the form's has its own default submit function. I know it may be done using custommodule\_form\_deal\_node\_form\_alter\_submit($form,$form\_state) But dont know how to merge my value with the default form's submit function. Please help me.

# Answer
In your alter hook you can create custom submit handlers.
Ex.

```
function custommodule_form_deal_node_form_alter() {
    if (isset($form['actions']['submit'])) {
        $form['actions']['submit']['#submit'][] = 'custom_form_submit';
      }
    }

```

then you implement the custom submit handlers.

```
function custom_form_submit(&$form, &$form_state) {
 // $form_state will have the form value which you can insert into database.
}

```
> 2 votes

# Answer
For a node form you'll want to hook into the submit button, which is in the actions container:

```
$form['actions']['submit']['#submit'][] = 'mymodule_foo_submit';

```
> 0 votes

---
Tags: forms
---


title: Restws authentication

text:
# Question
Title: Restws authentication
How can I login to my Drupal in API way and use the rest ws module with API calls?

For example, I have a user with name **test**. I want to login with test user then use API calls with something like a token or identity (I don't know what) and make Drupal recognize user in :

```
global $user;

```

How is it possible?

I tried to post username and password to */user/login path* and get token from */restws/session/token*

It returns something like this :

```
emGevPKZl9aLe90tOJ1ZK9rnp--6BMeNV3RP27aqcsY

```

but when I use it in header parameters with name **X-CSRF-Token** it does nothing.

# Answer
> 2 votes
You would probably have an easier time using the services module it's better supported and used far more than the restws module. It supports several types of web service calls including RESTful.

**SERVICES:**

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

# Answer
> 1 votes
# Username

Unless specified in your settings.php as a regex string.. ($conf\['restws\_basic\_auth\_user\_regex'\] = '/^ws\_.\*/';) restws requires your username to start with restws, so restws\_test or something.

# Auth

Referencing the conversation https://www.drupal.org/node/1664352

> A Drupal site uses it's own authentication - and therefore does not issue an 'HTTP AUTH needed here' type header.
>
> Tools like Poster and wget do not send the HTTP AUTH credentials you've supplied unless the site asks for them - and Drupal doesn't. So because the credentials are not sent the restws\_auth\_basic module does not have them to use to login in to the Drupal site.
>
> So - for wget - add the '--auth-no-challenge' switch to get wget to sent the credentials anyway. I.e.

```
$ wget --user=ws_user1 --password=xxxxx --header="Accept: application/xml" --auth-no-challenge -O - http://www.example.com/node/1

```

> Also, curl seems to send the credentials without an extra switch being added - i.e.

```
$ curl --user ws_user1:xxxxxx --header "Accept: application/xml" http://kbailey.icmsv4.dev3/node/1

```

# Additionally

If your using postman.. I suggest you enable interceptor... this basically means for testing you can log in to your site as usual and this will be stored in session cookies, which interceptor enables accces to. When already logged in, youll find you can post to restws/session/token happily and get the csrf token in response.

---
Tags: 8, users
---


title: Cannot acquire lock for source node / 0

text:
# Question
Title: Cannot acquire lock for source node / 0
This error showing when I tried to import a CSV file on my live site. Same file I tried in local site working fine.

> Cannot acquire lock for source node / 0.

The modules I am using are the following:

* Feeds
* Feed Excel
* Libraries (PHP Excel)

I examine the issue and found that the error occurred when I tried to import an image. Have anyone faced this issue?

# Answer
> 1 votes
Image path was not correct so the error was showing.

# Answer
> 2 votes
To release the lock, remove it from `semaphore` table, e.g.:

```
drush sqlq "DELETE FROM semaphore WHERE name LIKE 'feeds_source_%'"

```

---

If you got different error like:

> The feed is currently importing.

then you need to clear out `state` and `fetcher_result` data from `feeds_source` table, e.g.:

```
drush sqlq "UPDATE feeds_source SET state = NULL, fetcher_result = NULL WHERE id = 'FEEDS_MACHINE_NAME' AND feed_nid = 'NID'"

```

Note: Change `FEEDS_MACHINE_NAME` and `NID` into appropriate values.

---
Tags: 7, feeds
---


# Question
Title: What's the proper way to use EntityFieldQuery?
In Drupal 7, the API documentation for `node_load_multiple()` says that using the `$conditions` parameter has been deprecated in favor of using `EntityFieldQuery`.

In which way should `EntityFieldQuery` be used to get a list of node IDs to use with `node_load_multiple()`?

# Answer
EntityFieldQuery uses a set of hooks to interface with field storage modules, such as Field SQL Storage, in order to work for fields as well as other node properties. Long term, EntityFieldQuery is a much more reliable way to query any type of entity, and in some situations it can perform cross entity queries (see field\_has\_data or \_list\_values\_in\_use() for an example.

Here's a simple example of using EntityFieldQuery to get a list of all nodes published before a specific timestamp:

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('created', '1294694496', '<');

$result = $query->execute();

```

$results from that query would look something like this:

```
Array
(
    [node] => Array
        (
            [1] => stdClass Object
                (
                    [nid] => 1
                    [vid] => 49
                    [type] => article
                )

            [2] => stdClass Object
                (
                    [nid] => 2
                    [vid] => 2
                    [type] => page
                )

        )

)

```

You could then use that array as input to node\_load\_multiple:

```
$nodes = node_load_multiple(array_keys($result['node']));

```
> 36 votes

# Answer
I found an issue on Drupal about adding examples for `EntityFieldQuery`. I've been using it for examples as well as to voice my opinion on the call for more examples.

"Do we need an EntityFieldQuery example?"

The comment #11 shows usage of `node_load_multiple()` as seen below:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'event')
                        ->propertyCondition('status', 1)
                        ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
                        ->fieldOrderBy('field_date', 'value', 'ASC')
                        ->execute();

$nodes = entity_load('node', array_keys($entities['node']));
return node_view_multiple($nodes, 'teaser');

```
> 14 votes

# Answer
Here is an example from one of the test modules:

http://api.drupal.org/api/drupal/modules--node--tests--node\_access\_test.module/function/node\_access\_entity\_test\_page/7

This selects nodes whose body field starts with "A". See also EntityFieldQuery::execute() on how to use the returned result.

There are many use cases, the typical example is querying entities for specific field value like the body field as shown in the first example.

The advantage is that it works whatever field\_storage you are using. For example, you can have your fields in MongoDB and EntityQuery will still work while querying field\_data\_body manually wouldn't.
> 8 votes

# Answer
You can use EntityFieldQuery class to query the database and fetch the results in form of list similar to `node_load_multiple()`.

This can be achieved by creating a class, applying the conditions and executing the query, for example:

```
<?php
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'TYPE') // E.g. node, entityform, taxonomy_term
  ->entityCondition('bundle', 'BUNDLE')
  ->fieldCondition('field_foo', 'value', 'STRING')
  ->range(0,10);
$result = $query->execute();
?>

```

This will generate the array such like:

```
array (
  'TYPE' =>
  array (
    123 =>
    stdClass::__set_state(array(
       'nid' => '123', // Can be also tid when loading terms.
       'key' => 'value',
    )),
    456 =>
    stdClass::__set_state(array(
       'nid' => '456',
       'key' => 'value',
    )),
  ),
)

```

To fetch the ID from the result array, you can use: `current(current($result))->tid`.

Here is more advanced example:

```
<?php
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $news_items = entity_load('node', $news_items_nids);
}
?>

```

See: How to use EntityFieldQuery at Drupal.org for more explanation.
> 1 votes

---
Tags: 7, database
---


title: Searching content by taxonomy term

text:
# Question
Title: Searching content by taxonomy term
I would like to search content depending on select menu. Something like the search box here: http://www.doyleia.com/anazitisi-ergasias How can I do that with drupal 8?

# Answer
> 1 votes
You can achieve that with filters in Views.

Just create a view, add filters and make them "exposed", so that visitors can choose filters themselves. Filters can be taxonomy terms, list options or open-ended fields (e.g. text field) where users can write what they are searching for.

See the Chosen module for providing a more user-friendly interface for `<select>` elements that accept multiple choices.

---
Tags: 8, search
---


# Question
Title: Why is my Forena report parameter not displaying as a textbox?
I created a Forena report using a data block that has one parameter in it, i.e. "`:year`".

When creating the report, the parameter is detected and added to the report definition. When previewing the report a textbox is shown to let me enter a value and test the report. However after saving the report no text box displays to allow data entry for this parameter. I have checked the settings for the parameter and the "Input Control Type" is set to Textbox. I have tried both Yes and No settings for the "require" setting.

# Answer
Have a look at the tutorial about Forena report parameters. In the end, they are technically stored (saved) as part of the so called ***.frx*** files (which contains all of your report specification details). Here is a (partial) example of such frx-file:

```
<head id="frxsrc">
  <title>My Report Title</title>
  <frx:parameters>
    <frx:parm id="state" label="State" require="1"
      desc="Select a state from the list."
      data_source="sampledb/states" data_field="" type="select">
      WA
    </frx:parm>
  </frx:parameters>
</head>

```

So when you're creating ("*writing*") a report specification (eg using the WYSIWYG report writer), part of what you actually do is saving a special kind of "content" in XHTML format. And that's where the typical "text formats" get involved (just like any kind of content you'd save in Drupal).

However, because of the way Forena does certain things to process these XHTML files (report specifications that Forena massages in reports/charts that match your specifications), it's important that as part of the Forena installation/configuration, you "***Prepare a text format to be used by Forena***", as explained in the Forena Setup Guide. Here is the crucial part of it:

> Regardless as to which Input Format you choose to use with forena, make sure these entries are turned of for the chosen text format :
>
> * Limit allowed HTML tags.
> * Display any HTML as plain text.
> * Convert line breaks into HTML.
> * Correct faulty and chopped off HTML.

Anybody who starts using Forena without completing (or knowing about) this crucial configuration step, will typically run in this first-time configuration error ... Same happened to me when I first tried to use Forena some years ago.
> 2 votes

# Answer
The issue turned out to be the Forena setting for Input format.

At admin/settings/forena I set the input format to "Unfiltered" and gave a role permission to use that format.
> 0 votes

---
Tags: 7, log-messages, forena
---


title: Ajax post with one parameter

text:
# Question
Title: Ajax post with one parameter
How can you pass */* as part of a parameter in an Ajax call?

The address is http://studiga.delta-xray.co.uk/delete\_favourites/%3Cspan%20class%3D%22remove-favourite%22%3E%26nbsp%3B%3C%2Fspan%3E%3Ca%20class%3D%22title%22%20href%3D%22http%3A%2F%2Fstudiga.delta-xray.co.uk%2Fproperties%2Fliverpool-property%22%3ELiverpool%20property%20Address%20line%201%3C%2Fa%3E%3Cspan%20class%3D%22address%22%3E%20Address%20line%202%20Town%20L2%206RE%3C%2Fspan%3E and I wanted just one parameter, but it is treating *%2F* as */*.

```
function delete_favourites_permission() {
  return array(
    'access favourites content' => array(
      'title' => t('delete favourites via ajax'),
    )
  );
}

function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function delete_favourites_page($line) {
    echo $line;

    $result = "vvvv";
    drupal_json_output($result);
    exit();
}

```

`echo $line;` prints `<span class="remove-favourite"> `.

How can I get it to work?

# Answer
> 0 votes
What I think you are trying to do is delete a record from the database, someones 'favorite', like a bookmark on content, perhaps.

Anyway, what you need is an argument in the URL, the best being an ID - even better if it is an entity id that could be provided as a loaded argument for you (like node/%node - the %node argument provides the loaded node instead of just node id).

Assuming the argument is simply an integer of a database record, you could do:

```
function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites/%'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'delivery callback' => 'ajax_deliver',
  );

  return $items;
}

function delete_favourites_page($favorite_id) {
    // code to delete the favorite_id record
    $commands = array();
    $commands[] = ajax_command_alert('Favorite has been deleted.');
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

However, your access callback should not be TRUE, that means anyone can hit this URL and there is no upfront access checking. I hope you are handling that in your callback, but ideally you should use permissions or a callback to perform more complex checking.

The ID will always be passed to the page callback function now, and you could perform the delete operation there.

The delivery callback has been set as ajax deliver, which tells Drupal the page will return ajax commands. The above code contains a very simple alert, which will fire when the callback is performed.

There is a decent amount more that can go into this when wanting to implement AJAX interactions via menu items and callbacks. But first you need to figure out / fix your URL structure so you can pass arguments and not strings / query strings, and you'll also want to implement access checking so only the user who owns that record (or admin) can delete it.

---
Tags: ajax
---


# Question
Title: Checking if referenced fields are empty in commerce product display node.tpl
I have a list of fields in a product display `node.tpl` that are references from different product types, any one of which has a combination of some of the fields of the list. I pass the list of fields through a check to see if they exist (already answered in Check if referenced field exists in commerce product display ) and then I need to find a solution to check if any of this field is empty to avoid showing it in a dynamic accordion. In that `tpl`file I reach the fields with `$content['product:field_name']`

I'm a little lost here, I've tried using some of `field_*_field()` drupal functions but I can't seem to get to the product.

Is there a way to achieve it?

# Answer
you can render the field in advance, and save the html for your accordion.

the html variable will be empty if the field is empty:

```
$html = render($content['product:field_name']));
if (!empty($html)) {
  // accordion stuff
}

```
> 0 votes

---
Tags: theming, commerce
---


# Question
Title: Bind payments and auto return a certain amount of it with PayPal
I had the idea to create a Drupal site with the feature of bid wars between two users in a certain product.

User A and User B will pay the same amount of money which will be bind in the website. Then both users will have something like a mini game between them and when both users mark the war as finished, both amount of money will moved to one of their PayPal account. Except of a fixed fee percentage.

Example:

* User A and User B pay 50$ each of them.
* After their "fight", user B wins and he gets 100$ - 2% fee= 98$.

Is there any way to do this automatically with the PayPal module or with another indirect solution?

# Answer
> 0 votes
this would get complicated with paypal .. as only a transaction is refundable .., and no 'payouts' are supported in commerce ..

why don't you convert payments to userpoints, and safe the paypal refund fee. and do the payout of the points on request manually or with massrefunds.com ?

---
Tags: payment-gateways
---


# Question
Title: How to change text on Drupal WorldPay button?
I'm using the Drupal WorldPay module (for Commerce 7.x-1.11).

On the checkout page it says "Pay via WorldPay". I want to change this. I've traced it back to a line in the module:

```
function commerce_worldpay_bg_commerce_payment_method_info() {
  $payment_methods = array();

  $payment_methods['commerce_worldpay_bg'] = array(
     'title' => t('Payment via Worldpay'),
     'description' => t('Integration with Worldpay\'s Business Gateway method.'),
     'active' => TRUE,
     'offsite' => TRUE,
     'offsite_autoredirect' => TRUE,
     'callbacks' => array(),
   );

  return $payment_methods;
}
```

Specifically:

```
'title' => t('Payment via Worldpay'),
```

I think I can override this in the theme template.php but have no idea how, and there seems to be very few instructions on how one might go about it.

# Answer
In this specific case, you can implement `hook_commerce_payment_method_info_alter(&$payment_methods)` in a custom module, and alter `$payment_methods['commerce_worldpay_bg']['title']`.

If you see other instances of the strings, which aren't changed, then you can use the String Overrides module, as already suggested, or use the `$conf` global variable in settings.php as follows.

```
$conf['locale_custom_strings_en'][''] = array(
  'Payment via Worldpay' => 'Your string',
);

```

Keep in mind that the latter two methods change the string wherever it is used; they don't provide a context to understand where the string is being used. This could be something you want, or not.
> 4 votes

# Answer
There are of course different ways you can solve your problem (e.g., by overwriting the title value in a preprocess function, in a custom theme or module). It mostly depends on taste and the structure the solution has to be.

However, in situations where you simply need to replace text on a site in an easy way, the String Overrides module comes quite in handy. It allows you to replace anything that is passed through a t() function.
> 3 votes

---
Tags: 7, commerce
---


title: Create custom template for blog

text:
# Question
Title: Create custom template for blog
How do I go about overriding the default template for content of the blog page (the index page that shows the blog teasers)?

Also I would like the original template code for this content so that I can rewrite my content effectively, is the .tpl.php somewhere within drupal core, that I could copy out into my theme?

Thanks for your time!

# Answer
> 5 votes
I don't think there is separate file for Blog content type. Because for Blog default **node.tpl.php** is called. If you want to create tpl file for blog, straight away copy file from node.tpl.php and create a tpl like **node--blog.tpl.php**.

And if you want to create **page tpl** for blog content type then you can create

**page--blog.tpl.php**

And you have to add some PHP code in template.php file in THEMENAME\_preprocess\_page() function

```
if( !empty($vars['node'])){
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }

```

# Answer
> 1 votes
I think, we don't need any php code in template.php file for create blog template file. The files only enough for it ( I mean node--blog.tpl.php and page--blog.tpl.php ) After created the file clear your cache, then your new template will be worked.

# Answer
> 0 votes
The best and fast option is use views, and in the views page url add the blog paths.

With views \+ semantic views \+ display suit you can rebuild the html of your site without change no one \*.tpl.php

Oskar

# Answer
> 0 votes
Creating a node--blog.tpl.php and adding the following to the code worked for me.

```
<h2>
  <?php print render($title_prefix); ?>
  <?php print render($title); ?>
  <?php print render($title_suffix); ?>
</h2>

```

I didn't need to add the preprocess function.

---
Tags: 7, nodes
---


# Question
Title: How to drush rsync and sql-sync on windows with Acquia-Dev?
Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and `SqlBase.php`

First delete **cygdrive/** from `$path = preg_replace('/cygdrive/(\w):/', '/${1}', str_replace('\\', '/', $path));` in line 61 of `filesystem.inc`

and change `drush_shell_exec('gzip -d %s', $input_file)`

instead of

`drush_shell_exec('gunzip %s', $input_file)` in line 144 of `SqlBase.php`

Happy Syncing!

# Answer
> 0 votes
0 down vote favorite

Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and SqlBase.php.

First delete cygdrive/ from $path = preg\_replace('/cygdrive/(\w):/', '/${1}', str\_replace('\\', '/', $path)); in line 61 of filesystem.inc

and change drush\_shell\_exec('gzip -d %s', $input\_file)

instead of

drush\_shell\_exec('gunzip %s', $input\_file) in line 144 of SqlBase.php

Happy Syncing!

---
Tags: acquia-dev-desktop, drush
---


title: How do I get my user picture back?

text:
# Question
Title: How do I get my user picture back?
Apparently if you take the "minimal" installation, it does not create the user picture field. I tried to manually create it, but now the Simple Facebook Connect module is not synching profile images, because it can't find the default user\_picture field.

This is what the facebook module does:

```
// Try to download the profile picture and add it to user fields.
if (user_picture_enabled() && $picture_url) {
  if ($file = $this->downloadProfilePic($picture_url, $fbid)) {
    $fields['user_picture'] = $file->id();
  }
}
$new_user = User::create($fields);
$new_user->save();

```

I can confirm that it is able to get the $file, but the problem has something to do with the fields.

How do I correct recreate the "user\_picture" field?

This is returning false:

```
function user_picture_enabled() {
      $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
      return isset($field_definitions['user_picture']);
}

```

How do I add this field definition again?

I looked in the minimal.install file. I was hoping to find the code that enables user\_picture, but all I could find was:

```
\Drupal::configFactory()->getEditable('system.theme.global')->set('features.node_user_picture', FALSE)->save(TRUE);

```

There is nothing in standard.install. I tried running the following, without any luck.

```
\Drupal::configFactory()->getEditable('system.theme.global')->set('features.node_user_picture', TRUE)->save(TRUE);

```

How do I get my user\_picture field back without adding it manually, since I would end up with field\_user\_picture?

# Answer
> 2 votes
User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

```
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();

```

---
Tags: users
---


# Question
Title: How to turned off the translation on the node reference with entity translation?
I have a multilingual site and I am using the feed module to import content. My site has two languages:

English and Arabic.

During import the node from excel value all the fields value save except node reference field value in Arabic language.

Previously i am having same issue for term reference. But it is solved by disabling `Select taxonomy terms by language` on "`admin/config/regional/i18n/select`". But Node reference issue still there is there any settings present for this.

# Answer
> 0 votes
I got my answer.

There is an option for "Select nodes by language" in "admin/config/regional/i18n/select".

I just unchecked it. my issue has been solved.

---
Tags: 7, feeds, i18n-l10n, nodes
---


# Question
Title: Is the field item delta in the database reliable?
Use case / background:

* A node type "product".
* A taxonomy vocabulary "feature". E.g. "color" and "size". (forgive the name, it has nothing to do with the features module)
* Every product can have up to one value for each feature. E.g. color = green, size = big.

At first, this sounds like I should be using one (single-valued) field per feature, instead of a taxonomy. But this really does not scale, because there are going to be many many features, and new features can be dynamically added.

Another option would be a new entity type or bundle "node feature value". Or a new field type with two database columns, which stores both the tid of the feature, and the value.

But I thought, what if I use a regular text field with a custom widget? I would use the "delta" to store the feature tid, and the text value for the value.

Because, let's face it, the delta would be redundant anyway, if there can be only one value per product x feature.

The only question is, how reliable are the deltas? Can it happen that something will "normalize" the deltas to a regular continuous integer sequence 0..n ?

# Answer
> 1 votes
The answer is definitely "no", but it's a hard "no", not engine-dependent like it might appear. Under normal operation, the 0..n delta reset happens before the data is ever sent for storage.

If field values are saved using the API (`field_attach_submit()` etc), then they're unconditionally run through `_field_filter_items()`:

```
function _field_filter_items($field, $items) {
  $function = $field['module'] . '_field_is_empty';
  foreach ((array) $items as $delta => $item) {
    // Explicitly break if the function is undefined.
    if ($function($item, $field)) {
      unset($items[$delta]);
    }
  }
  return array_values($items);
}

```

As you can see, any indices you might have manually set in the `$items` array will be discarded, and the resulting array will always be indexed 0..n. I don't think Drupal gives you another opportunity to affect that array before the data is persisted.

# Answer
> 0 votes
Turns out the answer is "no":

```
/**
 * Implements hook_field_storage_load().
 */
function field_sql_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  [..]
        // Add the item to the field values for the entity.
        $entities[$row->entity_id]->{$field_name}[$row->language][] = $item;

```

This code from Drupal 7 core, `field_sql_storage.module` shows that at least some parts of Drupal show no respect for the `$delta` when loading the entity.

On the other hand, look at this contrib field storage implementation in mongodb, in `mongodb_field_storage.module`:

```
/**
 * Implements hook_field_storage_load().
 */
function mongodb_field_storage_field_storage_load($entity_type, $entities, $age, $fields, $options) {
  [..]
            $field_values[$language][$delta] = $column_values;

```

So there are storage engines that do respect the field item delta. But with these two examples, we have to assume that support for the `$delta` is very inconsistent, and far from reliable.

So for my original problem, there is no way around a custom field type. Too bad..

EDIT: Relation module might be another possible solution.

---
Tags: 7, entities
---


# Question
Title: How to keep Ajax refresh action when 'Use Ajax' option is disabled?
I have disabled 'Use Ajax' because I don't want AJAX pagination. Unfortunately other Ajax functionality stopped working.

How to ajaxify View programmatically?

# Answer
> 2 votes
@sumit madan's approach then is the best, leave your view ajaxified, and remove the paging, simplest seems to me by overwriting this method of the behavoir in your theme:

```
/**
 * Attach the ajax behavior to each link.
 */
Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
  this.$view.find('ul.pager > li > a, th.views-field a, .attachment .views-summary a')
  .each(jQuery.proxy(this.attachPagerLinkAjax, this));
};

```

just make it an empty function (add this code in your theme behavoir)

```
Drupal.views.ajaxView.prototype.attachPagerAjax = function() {};

```

this function also needs to be overwirtten:

```
Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function() {};

```

---
Tags: 7, views, ajax
---


# Question
Title: Multiple filenames in Entity form notification mail
I have an Entity form with a file upload and need to include multiple filenames in the mail that is sent to the site admin upon form submission.

If I only allow *one* file to be uploaded through the form the replacement pattern \[entity:field-uploadfield:file\] works fine to make rules display the filename in the notification mail. But if I enable the users to upload multiple files the replacement pattern does not work anymore – how can I solve this?

**Edit**: \[entity:field-uppladdarfaltet:0:file\] works, but then I'd have to cap the number of files at like 10 and also this doesn't really seem like a "clean" solution. Can I use the :0 :1 :2... format to support an unlimited amount of files?

# Answer
**\[UPDATED\]** Your Rule will need to have some additional actions preceding the Send Mail action.

1. ***Add variable (Text)***. Let's call it - `[file_list]`
2. ***Add Loop*** that loops over your file field `[entity:field-uppladdarfaltet]` and produces a List Item. Lets call the list item variable `[file_n]`
3. ***Add action Add Variable*** (text). Call it `[file_item]`
4. ***Add action Set a Data Value***. Data to change will be `[file_item]`. Value to set will be \[file-n:file:name\]
5. ***Add action Set a Data Value***. Data to change will be `[file_list]`. Value to set will be `[file-list:value][file-item:value]<br>`. This will add each uploaded file's name to the list with a line break after the name.
6. Print variable `[file_list:value]` in the email body.

Here's screenshot:
> 1 votes

---
Tags: emails, files, entities
---