# Question
Title: How to run a batch process in regular interval
I need to Unpublish the nodes which are all not Updated for more than some specified time.

I'm having the query to fetch nodes and by using a batch process I will Unpublish those nodes one by one.

Now I want to schedule this operation to be run every day. How can I achieve that? using drush or something.

I have cron running at regular intervals. I need to run these scripts apart from the cron job i.e as a separate one.

# Answer
I can achieve it by using a Cron job and Batch/Queue as mentioned by Anoop Joseph with some changes

**Method I - Using Cron and queue**

* Cron will run the query and push the list of nodes to the queue
* queue will pick the items one by one and Unpublish them

**Method - II Using Cron and batch**

* Cron will run the query and push the list of nodes to the Batch process
* Batch process will be launched programmatically using background\_process module

In both methods Cron can be configured in such way that It runs the query once for every day by storing the last run time in a variable
> 2 votes

# Answer
You can use cron to do this, set a cron time in admin/config/system/cron for your site.

there is a hook\_cron() is available in your drupal . using that hook you can configure your batch process to invoke.
> 4 votes

# Answer
The batch api is primary design to work with forms and it depends what is the purpose of your use, but you can create a function that mimic form submission, and then you can use batch together with cron, assume you have function that will be triggered by a rule on cron run, so this function is function1:

```
<?php
function function1 () {
    $form_state = array();
    $form_state['values']['hidden_value'] = 1;
    $form_state['values']['op'] = 'Test';
    $form_state['values']['submit'] = 'Test';
    drupal_form_submit('function1_batch_form',
    $form_state);
}
function function1_batch_form($form, &$form_state) {
  $form['hidden_value'] = array(
    '#type' => 'hidden',
    '#value' => 1,
  );
  return $form;
}
function function1_batch_form_submit($form, &$form_state) {
  if ($form_state['values']['hidden_value'] == 1) {
    $batch = function1_batch_process($date);
    batch_set($batch);
  }
}
?>

```
> 1 votes

# Answer
I know this is an old thread, but if you really need things running at different times I might tackle it like this:

Start by setting up a rule with a custom rules action. You can use any logic you want here (because it's in a module using hook\_action), I would check for a cache of nodes and process up-to X number of them if a cache is found or create a new cache and process up to X number of them if there is no cache.

The next part would be to set up the rule to happen on a specific page load and request that page with cron at whatever interval you want.
> 0 votes

---
Tags: 7, batch-operations
---


title: Create a menu tab of different views

text:
# Question
Title: Create a menu tab of different views
Having 3 different view , I'm going to show them in a page as different tabs. All of these views have exposed filter and are not completely related (one view shows users , one shows content and the last one shows taxonomy terms). I changed the menu types in these views to menu tab and their address to "seek/VIEWNAME".

now trying to browse seek I face 404 error and browsing "seek/users" I only get the "user" view without any tabs to other views.

How can create a tab consisting menus to different views?

# Answer
> 4 votes
Please follow the link about Creating Tabbed Views.

For quick reference, I am copying important steps here from above link.

1. Create a view.
2. Name the path (url) to be what you want the default tab to be, for example, 'document/all'.
3. Configure your view with sorting, filtering, etc.
4. Choose 'Default menu tab' in Menu option and name it.
5. Choose 'Normal menu item' to be the parent, since this tab is linked directly from a menu, i.e. 'document'
6. Finish this first tab.
7. Create another display.
8. Name the path of this one as a tab option, like 'document/homework'.
9. Configure it.
10. Choose 'Menu tab' for this one.
11. Finish this tab.
12. Repeat (8) - (11) for more tabs.

**Note:** If you want three tabs on same page with different/same view result, then please install Quick Tabs module.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content.

# Answer
> 1 votes
1. Create a block
2. Add the following code to the .info

`regions[test] = 'Test'`
3. Create test--block.tpl.php
4. Add html codes to create desired tabs in test.tpl.php
5. Add the following code to display the tab content

```
<?php print views_embed_view('VIEW NAME',"block"); ?>

```
6. Blocks in the Region

**Suggestion:** create tabs using Bootstrap

---
Tags: views, 7
---


# Question
Title: How to have display suite extra show up as layout options when creating blocks?
1. What I do now is create a content item.

Choose a layout.

Create content.

Use Node as Block to show as a block.

Would it be possible to have display suite extra show up for layouts when creating a block? So the block can have layouts?

# Answer
> 1 votes
May I suggest a different setup?

I would go for DS \+ Bean, that would allow you full Display Suite capabilities in your Drupal.
It will effectively give you block types that you can manage like nodes (Fieldable as well as managing their Display View Modes using DS).
Plus, the world of BEAN is wonderful =\> https://www.drupal.org/node/1475632 And it made it into core in D8 for a reason!

Here is two quick screenshots (after 30 seconds of clicking):

---

## Manage display for a block type

---

## Add a new block (using a new Block Type called Standard) via Content\>\>Add Block\>\>Standard.

Hope this helped, even though it deviated from the OP a tiny bit!

---
Tags: display-suite
---


# Question
Title: Is there a common nginx conf for Drupal 7 sites?
I've taken a look at Perusio's drupal-with-nginx repository and while I think it's impressive how extensive it is, it may be a little too advanced for me at the moment, plus I have several Symfony2 based sites live on the server and I don't to start making significant changes until I fully understand the configurations.

So I found this on a blog and figured it might do the job. Are there any common pitfalls with serving drupal 7 over nginx? Also, if the same Drupal installation was to power more than one site, would the configuration be any different?

```
server {
    server_name example.org;
    root /home/me/sites/example.org;

    index index.html index.htm index.php;

    access_log /var/log/nginx/example.org.access.log;
    error_log /var/log/nginx/example.org.error.log;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    # For drush
    location = /backup {
            deny all;
    }

    # Prevent user from accessing settings.php directly
    location ~ ^/sites/[^/]+/settings.php$ {
            deny all;
    }

    ## Replicate the Apache <FilesMatch> directive of Drupal standard
    ## .htaccess. Disable access to any code files. Return a 404 to curtail
    ## information disclosure. Hide also the text files.
    location ~* ^(?:.+\.(?:htaccess|make|txt|log|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
            return 404;
    }

    location ~ \..*/.*\.php$ {
            return 403;
    }

    location / {
            # This is cool because no php is touched for static content
            try_files $uri @rewrite;
    }

    location @rewrite {
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1&$args;
            rewrite ^ /index.php last;
    }

    # Use an SSH tunnel to access those pages. They shouldn't be visible to
    # external peeping eyes.
    location = /install.php {
            allow 127.0.0.1;
            deny all;
    }

    location = /update.php {
            allow 127.0.0.1;
            deny all;
    }

    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_pass unix:/var/run/php5-cgi/php5.sock;
    }

    ## Drupal 7 generated image handling, i.e., imagecache in core. See:
    ## https://drupal.org/node/371374
    location ~* /sites/.*/files/styles/ {
            access_log off;
            expires 30d;
            try_files $uri @rewrite;
    }

    # Fighting with ImageCache? This little gem is amazing.
    location ~ ^/sites/.*/files/imagecache/ {
            try_files $uri @rewrite;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }
}

```

# Answer
The main problem that Drupal 7 has with nginx is that Drupal is designed for Apache, and so many modules assume that Apache is installed (and you will always have a little blue entry on your "Status Report" that tells you that you can't use Upload Progress because mod\_php isn't installed — annoying).

That being said, thanks to perusio and others, many modules have been created that deal more with nginx and tap into its functionality well. So far, I haven't run into any problem with nginx that would have been fixed by Apache, and nginx is far faster and has a much lighter footprint. This is shown by many benchmarks, but it's also my experience. It also has better integration with php5-fpm, which also outperforms mod\_php.

As Drupal develops, it is becoming more backend agnostic. You can see this with 7's database abstraction layer that allows for more database backends, and so I assume that future releases will be designed with other web servers in mind.

So, there are no pitfalls that I've seen at all. You just have to pay a bit more attention to what some of the modules do, or at least what they say they do. If they mention .htaccess files, then make sure that you have corresponding entries in your nginx files that do the same thing. I haven't actually seen a case where nginx fails with a proper configuration.

Perusio's nginx configuration is absolutely amazing, but it takes quite a while to get through it all and understand it. You WILL need to customize it for yourself, and you might run into some problems that you'll need to fix if you use non-standard setups for things like imagecaching or advagg or some others. It also assumes that you're using more than one php-fpm pool. So you'll need to go through and pull out what isn't needed. But it is worth it to take the time to go through it all because you'll learn so much about how nginx works.

I've also ran into several errors with my nginx/drupal sites because I have a tendency to use php-fpm 5.4 or 5.5. The errors have nothing to do with nginx but with Drupal functions themselves as Drupal is just really finishing a transition to requiring php 5.3. If you look around the issue queues, however, you'll find several patches and other solutions to fix modules to work with newer versions of php.

At the end of the day, I would recommend that anyone who is starting with a fresh server use nginx instead of Apache. It's just better.
> 8 votes

# Answer
I've read that Nginx can't do everything, it's limited compared with Apache. "Apache has a module for every task". In my short experience I've been using Nginx for a couple of months with Drupal and everything works fine. If you are using a multisite install for Drupal and Nginx you can set multiple server names on the same server config, but you will not be able to have different logs for each site. I use this config without (almost) any problem: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
> 5 votes

# Answer
I completely agree with you that Perusio's nginx configuration for Drupal is impressive, but perhaps overkill for a local instance of nginx. I have found Mulkave's nginx configuration file on GitHub to be the most practical, lightweight configuration for running Drupal 7 on nginx.
> 3 votes

# Answer
```
server {

    listen *:80;

    access_log /var/log/nginx/test.access.log;
    error_log /var/log/nginx/test.error.log;

    root /srv/test;
    index index.html index.htm index.php;

    # Enable compression, this will help if you have for instance advagg module
    # by serving Gzip versions of the files.
    gzip_static on;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # This matters if you use drush prior to 5.x
    # After 5.x backups are stored outside the Drupal install.
    #location = /backup {
    #        deny all;
    #}

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    # No no for private
    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # This is cool because no php is touched for static content
        try_files $uri @rewrite;
    }

    location @rewrite {
        # You have 2 options here
        # For D7 and above:
        # Clean URLs are handled in drupal_environment_initialize().
        rewrite ^ /index.php last;
        # For Drupal 6 and bwlow:
        # Some modules enforce no slash (/) at the end of the URL
        # Else this rewrite block wouldn't be needed (GlobalRedirect)
        #rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Fighting with Styles? This little gem is amazing.
    # This is for D6
    #location ~ ^/sites/.*/files/imagecache/ {
    # This is for D7 and D8
    location ~* files/styles {
        access_log off;
        expires 30d;
        try_files $uri @rewrite;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_index index.php;
        include fcgi.conf;
        fastcgi_pass unix:/var/run/ajenti-v-php-fcgi-test-php-fcgi-0.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

```
> 1 votes

---
Tags: 7, multi-sites
---


# Question
Title: How to add an image upload field in a custom Field Type
I'm defining a new custom Field Type in Drupal 8, let's say `MyFieldType`, with custom widget and formatter also.

Such Field Type should have these two fields:

* `text`: a simple text value
* `image`: a field where the user that use this Field Type can upload an image, as the built-in image field type.

I created the custom field type with the `text` field with no problems. Now I'm trying to add the `image` field also, but I'm stuck and I don't understand how to proceed.

What is the correct way to add an image upload field in a custom Field Type?

---

## What I tried

Below there are the main parts from the custom Field Type. All files are from the folder `modules\custom\my_field_type\src\Plugin\Field`.

From the file `FieldType\MyFieldType.php`:

```
class MyFieldType extends FieldItemBase {

  //

  public static function propertyDefinitions(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $properties['text'] = DataDefinition::create('string')
        ->setLabel(t('Text Value'));

    // $properties['image'] ... go here?
    // ...

    return $properties;
  }

  //

  public static function schema(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $columns = array(

      'text' => array(
        'type' => 'varchar',
        'length' => 255,
      ),

      // What column for the 'image' field?
      // ...

    );

    $schema = array(
      'columns' => $columns,
    );

    return $schema;
  }

}

```

From the file `FieldWidget\MyFieldTypeWidget.php`:

```
class MyFieldTypeWidget extends WidgetBase {

  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {

    $element['value'] = [
      '#type' => 'textfield',
      '#title' => t('Value'),
      '#default_value' => isset($items[$delta]->value) ?
          $items[$delta]->value : null,
      '#empty_value' => '',
    ];

    $element['image'] = [
      '#type' => 'file',
      '#title' => t('Image'),

      '#default_value' => isset($items[$delta]->image) ?
        $items[$delta]->image : null,

      '#empty_value' => '',
    ];

    return $element;
  }

}

```

I can see the file upload field in the edit form (adding a new field with this custom type), but I don't know how to go on and (eventually) how to handle the uploaded image inside the class `MyFieldType`.

# Answer
What you want to do, is to save a reference to the file which is uploaded.

Since what you are making is an image upload with extra text field, you should consider using either

* `\Drupal\image\Plugin\Field\FieldWidget\ImageWidget`
* `\Drupal\image\Plugin\Field\FieldWidget\FileWidget`

as foundation to your widget. That way you should be able to reuse much of the trick image/file handling and just add custom parts or overrides for your custom widget.

You should also consider using either

* `\Drupal\image\Plugin\Field\FieldType\ImageItem`
* `Drupal\file\Plugin\Field\FieldType\FileItem`

as foundation to your field type, since they also handle a lot of things for you. The image variant adds a lot of stuff, like alt, height, width, which is something you probably want/need at some point, so no reason making all of this yourself.
> 2 votes

---
Tags: entities, 8, media
---


# Question
Title: How to delete blocks and why some you can delete and others you can't?
I'm probably missing something here....

But there is no delete option for blocks, either enabled OR dissabled.

Additionally, some blocks can be deleted, and some don't , they have the same exact settings.

# Answer
J. Reynolds is right. These blocks are generated from code. This means this block is added programmatically through `hook_block_info()`. Some modules use this to define static blocks (like the login block or the "Created with Drupal" block). However some other modules implement this hook in a dynamic way. Views for example uses this to generate a list of all blocks in all (enabled) Views.

So even though you did not create them in code. Some of the modules you use do. Only blocks you have created using the `Add block` link on `admin/structure/block` can be deleted.

In order to remove a Views block from the listing, disable the View (or the block display in the view). I have no idea how to hide a block generated from Node as block. And I suppose there is not a real way to remove these blocks from the listing without writing a custom module.

You could attempt to create a custom module and implement `hook_block_info_alter()`, in which you unset all blocks you don't want. Maybe something like this:

```
function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  // Attempt to disable the login block by status.
  $blocks['user']['login']['status'] = 0;

  // If above doesn't work unset the block.
  // Array is built like $blocks[module][block_name]
  unset($blocks['user']['login']);

  // Disable all Views blocks (also used ones!!)
  unset($blocks['views']);
}

```

But to be honest, I doubt if it is worth the effort and it can lead to confusion in the future if expected blocks do not show up. So I'd advice just to leave it.
> 2 votes

# Answer
As Reynolds pointed out, the blocks created via code (generally provide by modules or core via views or hook\_bock\_info(), hook\_block\_view()) cannot be deleted and the blocks created via structure-\>blocks-\>create new block can be deleted as they reside in database.

If you want to remove the views from showing up, you can just disable them from Block UI as in most of the cases i don't think deleting a block is a necessity. Also if you want to modify a block to suit your needs, you can use hook\_block\_info\_alter() and hook\_block\_views\_alter(). You can find a lot of help and simple examples on how to do it. Hope this helps.
> 0 votes

---
Tags: blocks
---


# Question
Title: Is it possible to use rules to set user profile pictures?
I would like to use the rules module's *Set a data value* action to set a user's profile picture whenever that user uploads an image of an "image" content type that I have created.

However, the user profile picture does not appear as an option in the data selector for *site:current user*. Is there another way to set the user profile picture using rules or am I out of luck?

# Answer
Create a componnent in rule with this ! On the componnent you have 2 parameters. One for the user and another one for the file you want to use ! I use Drupal 7.

```
$uid = $user->uid;
$account = user_load($uid);
$thefile = file_load($file->fid);

$edit['picture'] = $thefile;
user_save($account, $edit);

```

Call the componnent from the rules you want. On my side i'm using a flag to trig the rules. The user mark an image to use it has a profile picture and it work.

I use this link has a starter to create the rule. http://taggartjensen.com/code-snip/drupal-7-set-user-picture-programmatically

Good luck !
> 3 votes

# Answer
Another solution is to use the User Picture Field module. This module allows you add an image field to user, and show it on user register form, after user register an account, this module will use the fid that upload by image field as user picture's fid.

The benefit of this approach is that you can manipulate the new field like other fields (you can't do that with the default "picture" field.)

This new field, which replaces the default field, then appears in most data selector lists that involve nodes.

Easy to use, requires no programming.
> 2 votes

# Answer
You will need to do some programming, enabling the php filter for a php action, get the uploaded file path, load the user, then create a new file, update the user picture file column , assign the picture on file\_usage to the user
> 1 votes

---
Tags: 7, rules
---


# Question
Title: Is it possible to embed a content creation form in views header?
Suppose I am building a twitter-like site, and allow members to form groups with OG. So I have set up a view to list all the posts in a given group. However, I would like to embed a content creation form in the header (similar to how twitter is at the moment) with group audience set automatically to the group (therefore is not shown as an option in the form). Is there a way to do it without writing code (I haven't been doing drupal module development after D6...)?

# Answer
> 1 votes
So based on @Niall Murphy's answer, my solution to the problem is as follows:

1. Instead of embeding the form in a view, I create an **entity form** and make it available as a block with **entity forms block** module. Then the block is shown in all the group content type node.
2. Also, in order to prepopulate the group id in the block, I installed **Organic Groups Entityform Integration** for that purpose.
3. Then I use the **rules module** to capture the form submission event, and then check if it has the fields in the entity form. If the fields exist, then I create a new content. Then the value value of the content is copied from the submitted form. Lastly, the form itself is deleted as they are not needed anymore.

# Answer
> 2 votes
It doesn't have to be in the view header. Just place it block above the view and adjust the css so they sit together.

If you use entity forms and entity form blocks, you can just place a block above the view block (or panel pane).

Rules will allow you to create a new node, set the current OG\_context as the new new node's group and then redirect back to the same page or to the new node.

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


title: Admin Toolbar not working

text:
# Question
Title: Admin Toolbar not working
I downloaded the Admin\_toolbar module, installed and enabled it with Drush (`drush en admin_toolbar -y`).

If I look in admin, it's enabled. But it's not working; it's not hovering.

*Notes:*

* I have a Git workflow. But for now I just installed it locally. I had some issues with the `$config_directories`. For the configuration files. Could this may have to do with this? Now I returned to default settings in settings.php and in `admin/reports/status` I get no errors.
* I installed with Acquia Dev Desktop and have Mac OSX. Shall I trie de-install and install again maybe?

# Answer
> 1 votes
I used `drush cache-rebuild` and now it works!

---
Tags: 8
---


# Question
Title: Removing all 'stable' theme's CSS from a Drupal 8 custom theme
I would like to remove all CSSs automatically included from *stable* theme:

```
/core/themes/stable/css/system/components/*

```

I can remove them one by one inside the `.info.yml` file:

```
stylesheets-remove:
  - 'core/themes/stable/css/system/components/ajax-progress.module.css'
  - 'core/themes/stable/css/system/components/autocomplete-loading.module.css'
  - ...

```

Is there a way to remove all of them at once?

Something like:

```
stylesheets-remove:
  - 'core/themes/stable/css/system/components/*'

```

# Answer
> 18 votes
There's no wildcarding for the `stylesheets-remove` (FYI: there's a FR out there for it). However, you can use `libraries-override` to remove the library associated with the all CSS components you've highlighted:

```
libraries-override:
  system/base: false

```

It won't remove all CSS files in the stable theme, but it will condense removal of libraries that contain many CSS files.

---
Tags: theming, 8
---


# Question
Title: Filter view content by data in text field
I've created a text field on a custom content type. The text field is called "targetUser" on my content type "message".

targetUser is meant to collect the uid of a user that a current app user is sending a message to. **E.g.** If user 1 is sending a message to user 7, the number "7" will post to the targetUser field.

I want to create a view that ONLY displays "messages" with the targetUser number that matches the logged in user's uid, so that they may ONLY see messages meant for them.

**I essentially want my view to say:** "Only display messages with this user's uid in the field targetuser" - is this doable? Hope I explained this well enough.

# Answer
> 1 votes
So this ended up being MUCH easier than anticipated. I simply created a "targetuser" text field underneath of my custom Messages content type.

Then, I created a Content View, and added the following filters:

**CONTEXTUAL FILTER**

***Content:*** targetuser

Then click on the above filter, and:

**WHEN THE FILTER VALUE IS NOT IN THE URL**

Provide Default Value

and select: **User ID from logged in user**

This way, the targetuser id always matches that of the user logged in. Voila, only messages for logged in user appear.

# Answer
> 2 votes
> targetUser is meant to collect the uid of a user that a current app user is sending a message to

IMO the better approach would be to make targetUser an entity reference field.

* Download and install the Entity Reference module

+ In content type Message fields, add a new field with **Entity Reference** and a widget of **Auto complete (tag style)**

For example: I named mine lalala (click picture below to enlarge)

* For Target Type, select **User**
* Number of Values: **Unlimited** (as you could send a message to multiple users)

Then add or edit a message node and start typing user name, you will see the name in the drop down, select it and save.

Use a comma `,` to add other user account.

## In your view

* contextual filter of Logged in User id (uid)
* add a **relationship** of lalala Referenc**ed** Entity

+ If not, try Referenc**ing** entity, but if my memory is correct it's Referenc**ed**

**Result:** you should get a view of all the nodes where the logged in user was referenced.

---

> The autocomplete only allows by username, and not uid. E.g. posting 47 into this field isn't allowed?

Create a new USER view.

1) click on +Add

2) Select Entity Reference

3) Remove user:name and add user:uid

4) click on settings and checkmark uid (if you don't do this step, it won't let you save the view)

Go to your Content Type Messages manage fields and edit your entity reference field.

* At the bottom check mark ✓ Render Views filters as select list
* Change to mode to View and select your view.

> Also, "logged in user id (uid)" isn't an option? Just (author) User: Uid ?

You will need to create a CONTENT view and then add:

* Relationship of Referenced User
* Now since you have a relationship User: Uid becomes available as contextual filter

---
Tags: 7, views
---


# Question
Title: How to I style the Superfish accordion menu to have bars?
I would like to show my super fish menu with bars as shown in the picture (when in mobile responsive mode), but at the moment i can only get the word "Menu". The menu functions perfectly, i just wanted to add the bars. Can anyone advise?

# Answer
> 1 votes
Seeing you are using responsive and that implies that you are size aware. You may find an icon set more elegant rather than a fixed sized background image.

I load the font-awesome set into the site css anyway for use elsewhere. Therefor the icon's css are available sitewide.

If you look at the accordian settings for that sf menu, you'll see that you can edit that menu button (trigger) text. I found that though a text field, it does accept some html.

For example
`Open Menu<i class="fa fa-bars" aria-hidden="true"></i>` gives you those the bars and they re-size as the button text does.

---
Tags: routes, navigation
---


# Question
Title: Session is not getting maintain in settings.php drupal 7
I have Created one php file on root of drupal7 and access it using URL.I have one form in that file which has dropdown values and submit button. Now in settings.php i am getting those value in POST. Based on That post value i want to select DB for drupal. But it Throws error because session is not getting maintain. This is my code in settings.php

```
session_start();
$_SESSION['data'] = $_POST['year'];
if(!empty($_SESSION['data'])) {
  $databases = array (
    'default' =>
       array (
        'default' =>
          array (
            'database' => 'mydbname'.$_SESSION['data'],
            'username' => 'root',
            'password' => '',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
          ),
      ),
  );
}
else {
  header("Location: welcome.php");
}

```

# Answer
You can't start `session_start()` the second time, since Drupal is already started it.

So either remove it, or wrap it into the condition, e.g.:

```
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

```

Parsing input user variables is not a good idea, so it's better if filter it out, e.g.

```
$_SESSION['data'] = filter_input(INPUT_POST, 'year', FILTER_SANITIZE_STRING);

```

or better use `db_escape_table()`.
> 0 votes

# Answer
Session records are stored in the database. Hence, it is simply impossible to select the database connection based on values stored in a session.
> 0 votes

# Answer
Using session it is not possible so I did it using Cookie.

```
    if (!isset($_COOKIE['yr'])|| $_COOKIE['yr'] == '') {
          if (isset($_POST['year'])) {
            setcookie("yr", $_POST['year']);
            $_COOKIE['yr'] = $_POST['year'];
          } else {
            header('Location: welcome.php');exit;
          }
        }
        elseif(isset($_POST['year'])) {
            setcookie("yr", $_POST['year']);
            $_COOKIE['yr'] = $_POST['year'];
        }
        $databases = array (
          'default' =>
          array (
            'default' =>
            array (
              'database' => 'db' . $_COOKIE['yr'],
              'username' => 'root',
              'password' => '',
              'host' => 'localhost',
              'port' => '',
              'driver' => 'mysql',
              'prefix' => '',
            ),
          ),
        )
;

```
> 0 votes

---
Tags: 7, sessions, configuration
---


# Question
Title: How to reorder the date in a view expose filter?
I have created a view with date expose filter. Currently filter is working fine but i need to reorder the day and month.

From **month/day/year**

To **day/month/year**

# Answer
> 0 votes
Got the settings **Home » Administration » Configuration » Regional and language**

# Answer
> 0 votes
You need to use form\_alter to accomplish without any date format change from configuration. The example is below.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
      $form['date_filter']['value']['#date_format'] = 'd-M-Y';
    }
  }
}

```

---
Tags: views, datetime
---


# Question
Title: Migrate d2d – Problem with duplication of thumbnails
In order to be able to copy all files to certain specific subfolders in site/default/files during my migration från D6 to D7 I use the file class MigrateFileUri (as far as I understand MigrateFileFid does not care about destination directories). So, in prepareRow() I fetch the filepath from the legacy db for the main image and likewise for the thumbnail of that same product.

The problem occurs when there is only a main image and no thumbnail in a product node. What happens is that the thumbnail field gets the previuos thumbnail path used. This is my prepareRow():

```
public function prepareRow($row){
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }

    $fid = (isset($row->field_sensorimage) && !empty($row->field_sensorimage[0])) ? $row->field_sensorimage[0]: FALSE;

    if($fid != FALSE){
        $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid))->fetchAssoc();
        $this->addFieldMapping('field_sensorimage_newsite')->defaultValue($filepath);
    }

    $fid2 = (isset($row->field_thumbnail) && !empty($row->field_thumbnail[0])) ? $row->field_thumbnail[0]: FALSE;

    if($fid2 != FALSE){
        $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid2))->fetchAssoc();
        $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);

        dsm($fid2);
        dsm($filepath);
    }

    return TRUE;
    }

```

This happens: if let's say the 100 first nodes has no thumbnail, it works as expected. No thumbnails are copied to the destination directory. But after the first node with a thumbnail all the following nodes that did not have a thumbnail in the D6 legacy site, gets the previous nodes' thumbnail all the same in the new D7 site.

Thanks to the 2 dsm() near the end of the snippet above I can confirm that no thumbnails gets duplicated within that *if statement*. There are about 50 thumbnails mapped. But the end result is that several hundred nodes gets duplicate thumbnails from other nodes.

So once the first thumbnail is migrated, that thumbnail path is inherited by all the following nodes and renamed with a number extension \*_1.jog, \*_2.jpg .... \*_30.jpg as long as there is no thumbnail in the legacy field.

Now, where does this happen and how can I stop it from happening? I have rewritten the prepareRow() many times, but always with this same result. I am really stuck... Please help :-(

# Answer
> 1 votes
Finally found a workaorund… by deliberately giving the destination field an empty value instead of not doing anything when $fid2 is FALSE, I got rid of all the duplications :-)

```
if($fid2 === FALSE){
    $filepath = array();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
} else {
    $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid2))->fetchAssoc();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
}

```

---
Tags: 7, migrations
---


# Question
Title: Force native taxonomy-term pages to only show <H1> and not all content
How do I force taxonomy term pages to show only the `<h1>` part and not all the nodes associated with that term?

I could use a view for that, but I am trying to change the taxonomy term pages without using the Views module.

# Answer
> 2 votes
You can override the default listing with the built-in view, see here https://drupal.stackexchange.com/a/165052/3218

To only show the title you then need to adapt the view:

* go to the view's edit page (admin/structure/views/view/taxonomy\_term/edit)
* change the format-display from rendered entity, to fields
* remove all fields and add the title field as only field

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


# Question
Title: How can create custom twig template for particular page
I want to create custom template for particular pages. Single template for multiple page in drupal 8.

# Answer
> ### Twig Debugging
>
> It’s great that we have the ability to override our template files, but we are still left with the question of how we are to know which template file needs to be overridden in any particular case. After all, template files are nested one inside the other—which one contains the markup that we want to change?
>
> This brings us to the killer feature of Drupal 8 theming—Twig debugging. Getting started is very easy. Inside of the sites/default folder is a file named service.yml. Inside that file you will find a setting for Twig debug. This setting will be set to false by default. Simply change it to true as shown in the image below:
>
> As usual, clear your cache after making this change. When we return to our page and inspect the markup we will find debugging information added in the form of code comments. Here’s an example of what our home page markup will look like when inspected in DevTools:
>
> You can see the debug info provides the path to the new template file we have created. This information is repeated for other template files found on the page, providing a fast and easy way of finding the file you need to override or edit.
>
> Important: Do not edit template files in core! Copy the file to your theme and edit that version instead.
>
> Also included are file name suggestions for overriding the currently active templates. If you’ve ever had to track down the correct template file to override in Drupal 7, then you know what a huge improvement this is.
>
> Author: John Hannah
>
> Source and more great twig info: Drupal 8 Theming Fundamentals, Part 2

**Note:** In the 2nd pic, the `x` shows you the current twig template that is being used. In this example it's page--front.html.twig

To answer your Q, enable twig debug and go to your page and with your browser inspect element. The debug will suggest you all the template names you can use for that page.

**PS:** Don't forget to turn off twig debug before your site goes live.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Applying Patches to Drupal modules - How to deal with error messages?
I am trying to apply patch #110 from here in Drupal 7 - ViewsCalc.

I am following the instructions on this page: Applying patches on Mac OS X

When following the instructions, I get this error message:

```
Perhaps you should have used the -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/theme.inc b/theme.inc
|index 57d61ed..7db435b 100644
|--- a/theme.inc
|+++ b/theme.inc
--------------------------
File to patch:

```

What should I do?

I've tried giving it the path to the `theme.inc` file. When I do this, it displays the following:

```
No such file or directory
Skip this patch? [y]

```

As a work around, I have installed Drush Issue Queue Commands and I have applied the following command in Drush: `drush iq-apply-patch 140665-#110`

When I use this Drush command, I get the following error message:

```
Drush iq-apply-patch 140665-1: downloading patchfile                 [ok]
views_calc_grouping_140665-114.patch for project views_calc
Could not apply the patch with either -Np0 or -Np1; perhaps the patch[error]
was rolled for a different version of the project.

```

What am I doing wrong?

PS. I'm not sure if this is a valid question, as it deals with patching. However, it also deals with topics such as Drush so I believe it is on topic. If it is off topic, please could you direct me to the correct place to post it.

# Answer
> 2 votes
Thanks for all the help. I worked this out!

When I was applying the patch, I placed the patch file in the root module directory. But it actually has to go inside in the directory of the actual module. Whoops!

E.g.

The patch goes inside of `sites>all>modules>views_calc` and not inside of `sites>all>modules`.

---
Tags: 7, drush, version-control
---


# Question
Title: How and where to use/place database queries when a webform is submitted?
Let's say that I already created a **webform** with fields **Customer Name**, **Customer Surname** and **Customer Address**.

When the webform is submitted, I want to insert those values captured in a custom table "**Customer**" created in the database that Drupal is using.

How do I achieve this? Do I have to use a specific module to insert those values?

Is it feasible to do this by using the Rules module? If yes, can you give me a simple example on how to do this?

# Answer
You can use hook\_webform\_submission\_insert to insert data in custom table

ie :

```
function hook_webform_submission_insert($node, $submission) {
  // Insert a record into a 3rd-party module table when a submission is added.
  db_insert('mymodule_table')
    ->fields(array(
    'nid' => $node->nid,
    'sid' => $submission->sid,
    'foo' => 'foo_data',
  ))
    ->execute();
}

```

As mentioned in above example you will find all submitted data in

```
$submission

```

variable.
> 1 votes

---
Tags: 7, database, webforms
---


# Question
Title: How to insert data to webform via HTTP/Drupal REST module?
I have hooked up a simple webform and now I need to insert data via HTTP/Drupal REST module ?

Is is possible to insert this way, else should I insert directly to DB ?

# Answer
I used webform\_service with services module to insert data in webform using REST and its working fine form me.
> 0 votes

---
Tags: webforms
---


# Question
Title: Diff module not working. Compare shows 'no visible changes'
I have installed the diff module on my D7 site. I can see the different revisions on the revisions tab, but clicking 'compare' always shows 'no visible changes'. I think I must have missed something obvious, but am struggling to work out what.

On the admin/structure/types/manage/ page for my content type I have gone to the 'Publishing options and enabled the 'Create new revision' option. On the 'Compare revisions' tab 'Show View changes button on node edit form' and 'Enable the Revisions page for this content type' are checked. 'Standard comparison preview' is set to 'Full content'. I have left the options at 'admin/config/content/diff' and 'admin/config/content/diff/fields' to their defaults. I am logged in as user 1.

My nodes don't have any main body content, only individual fields. Could you please suggest what I need to do to show the diffs.

UPDATE: I have tested in a sandbox server and the diff module works as expected. Therefore it must be a conflict or a bug that is being triggered by my install.

UPDATE: After more investigation I have discovered that the issue exists only with pre-existing fields. So am starting a new question.

# Answer
I had disabled hidden all my fields in the default view which was why the diff wasn't showing.

I fixed this by: On the page admin/structure/types/manage/mynodetype I changed the 'standard comparison preview' from 'Full content' to 'Revision comparison'.

I then went to admin/structure/types/manage/mynodetype/display, opened the collapsed field 'custom display settings' and checked 'Revision comparison'. Then in the revision comparison view that was created I made sure the format for each field was no longer set to 'hidden'. Now the diff module is working as expected.

This issue is also discussed in this drupal answers question
> 0 votes

# Answer
The problem seems to be this:

> On the admin/structure/types/manage/ page for my content type I have gone to the 'Publishing options and enabled the 'Create new revision' option.

Because of the above setting even if you edit a node and save without any change, a new revision is created. The new revision has no possible changes that are visible except for `update date`. I think you should uncheck this setting `Create new revision` and let content writers to create revision if they edited the node.

I tested it locally and was able to reproduce it. Revision was created if you edit and save the node without any changes.

After manually create a revision after change:
> 1 votes

---
Tags: 7
---


# Question
Title: How to redefine / override the default breakpoints in a Bootstrap sub-theme
I have a Drupal 7 subtheme based on the Drupal Bootstrap theme CDN starterkit. I'm trying to change the default breakpoints, which I thought would be a simple, routine task, but I can't find anything that works.

I've read this issue which shows that the theme supports the Breakpoints module. I've installed the Breakpoints module, followed the steps given, got confirmation in Drush and the Breakpoints module UI that my new breakpoints have been read from my `.info` file - but the columns in my Bootstrap subtheme ignore these and carry on using the built-in ones. I've cleared all browser and Drupal caches.

I can only assume that the "Breakpoints module support" means that it allows *other modules* (like Navbar etc) to listen to the custom breakpoints, whereas Bootstrap itself continues getting Bootstrap CSS files according to its built-in defaults.

I've also been through the Drupal Bootstrap documentation and can't find anything about breakpoints at all. I only confirmed what the default Bootstrap breakpoints were through a comment in the above linked issue.

All I can think of is, to compile a version of the Bootstrap CSS with the breakpoints I want, upload it and use it instead of CDN as per "Using own Bootstrap 3 files in Bootstrap Drupal 7 theme". I'm wary of this however because it seems like the theme PHP would expect different breakpoints to those defined in the theme CSS which sounds like a recipe for strange bugs further down the line. I'd prefer to override some setting or, failing that, function in the theme so that it gets the configuration I want from the CDN and isn't expecting a different configuation.

<sub>**\[UPDATE\]** I've tried this and it does seem to work, although at first I thought it hadn't because I'd misread how the Bootstrap compiler used minimum and maximum values. It feels like a very "against the grain" bodge though, and I won't be surprised if it causes problems later, which is why I'm not posting it as an answer.</sub>

---

**How can I customise the pixel values for the xs, sm, md and lg Bootstrap breakpoints in a Drupal 7 Breakpoints based subtheme in a clean way that is consistent between front end and back end?**

# Answer
> 1 votes
There doesn't currently seem to be anything in the Bootstrap theme that supports this directly, and the theme doesn't appear to listen to anything in the Breakpoints module. The bootstrap breakpoints are hard-baked into the JS and CSS.

If you're not using LESS, this means the only realistic option is to override the CSS and JS with custom local files. I had a bit of trouble with this at first but it seems to be fine and doesn't seem to conflict with anything in the server-side theme code.

1. Create a customised version of Bootstrap with your breakpoints and other preferences, from http://getbootstrap.com/customize/
2. Install the module Bootstrap Library
3. Upload the custom bootstrap files to `sites/all/libraries/bootstrap`
4. Disable everything to do with CDN in your theme settings page

---
Tags: 7, theming, bootstrap-theme
---


# Question
Title: Getting User Entered Form Data within a hook function
**Problem**

I need to use the following **hook** function to edit a similarly-named function in a contributed module (PayPal WPP), but I don't understand how to use it.

```
hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) { }

```

When this function is called I need to pass some variables to **PayPal**, based off **user-supplied input in a form**. **By the time this function is called the user has already supplied their input in the form and clicked 'submit'**. The form is now ready to send it's data to PayPal and this hook alters what is being sent.

So I need to figure out how to add additional data. Specifically I want to alter a variable $nvp\['custom'\]. **The main problem is I don't know how to get the values the user entered in the form into this function so I can pass them on.**

I'm told I need to get the user-supplied values using `$form_state['values']` but I have no idea how to get those inside this function, which isn't passed `$form_state` as a parameter. I was hoping to do something like this:

```
$name = $form_state['values']['field_name'];
$organization = $form_state['values']['field_organization'];
$arr = array($name, $organization);
$allthedata = implode('+', $arr);
$nvp['CUSTOM'] = $allthedata;

```

*As it may be obvious I don't even know how to refer correctly to the passed $form\_state values, which is probably a large part of my problem.*

**Question**

How do i get my user-supplied form values into this function so I can use them (and then pass them on to PayPal as part of the $nvp\['custom'\] variable?

# Answer
> 1 votes
You can user this code in which you can add your form data in array and pass it to the Paypal api.

```
function do_custom_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method){
    if ($payment_method['base'] == 'commerce_paypal_wpp' ) { //check payment method

        //save form data
        $name = $form_state['values']['field_name'];
        $organization = $form_state['values']['field_organization'];

        $nvp += array(
        'name' => $name,
        'organization' => $organization,
    );
  }
}

```

Here is the similar solution for your problem in which user has passed order details. Click Here

---
Tags: forms, commerce
---


# Question
Title: Getting fields' Attributes in node template
I'm trying to rendering node's fields directly inside a node template.

This is my node template file `node--homepage.twig.html`:

```
<div{{ attributes }}>

  {{ title_prefix }} {{ title_suffix }}

  <div{{ content_attributes }}>

    <!-- Render field_1 value here -->
    <div{# field_1's HTML attributes here #}>
      {{ node.field_1.value }}
    </div>

    <!-- Render field_2 value here -->
    <div{# field_2's HTML attributes here #}>
      {{ node.field_2.value }}
    </div>

  </div>

</div>

```

Is it possible to get HTML `attributes` for each field inside the node template?

# Answer
> 1 votes
The field values in `node` are the raw data from the database. You should not use them for output. They are great for coding of conditions in twig.

For output use:

```
{{ content.field_1 }}
{{ content.field_2 }}

```

These statements will output the fields using the field formatter as configured in the ui.

**Edit: Adding attributes**

If you need additional attributes add them in the field twig. The methods described in the link you provided in the question are only possible in the same twig your element comes from. If you want to modify the attributes of the node it is the best to do it in the node template. If you want to add attributes to the field use the field template.

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


title: Unsubscribed from Simplenews Newsletter

text:
# Question
Title: Unsubscribed from Simplenews Newsletter
is there a way to find how many users unsubscribed from my Simplenews newsletter at my Drupal-7 website? And, if yes, can I detect from which particular newsletter did the user unsubscribe from?

# Answer
You can click admin/people/simplenews and check on status column. OR you can use following code to get the data

```
  // fetching from the database.
  $query = db_select('simplenews_subscriber', 'ss');
  $query->innerJoin('simplenews_subscription', 'si', 'si.snid = ss.snid');
  $query->fields('ss', array('mail'))
    ->condition('ss.activated', $condition_active)
    ->condition('si.status', $condition_subscribed)
    ->condition('si.newsletter_id', $newsletters)
    ->distinct();
  $data = $query->execute()->fetchAll();

```

where `si.status` is a flag indicating whether the user is **subscribed (1) or unsubscribed (0)**

and `$newsletters is a Array of newsletter ids to filter on`
> 2 votes

---
Tags: users, emails
---


# Question
Title: How do I embed a custom node creation form inside a view
I have these nodes : Company, Cars, Trucks (cars and truck have a taxonomy term to give it's type). Cars and Trucks have a field named Company wich refer to the Company node.

So i can locate the vehicle location on a map. I know how to create a form wich allow the company's administrator to add some cars (with this subject : How do I embed a node creation form inside a view)

But i want to give a field like "Select your vehicule's type" -\> "Car" or "Truck" and it shows the right form to add a new vehicle.

I want too, restrict the selection of vehicules types by user group. Then me as an administrator i want to have the possibility to select all types of vehicle, but an user group like "Motorbike Company" can use only "Motorbikes" or allow "Truck company" to use "Trucks" and Cars".

And finaly, in Campany i've a field "Vehicles" and when the company's administrator add a new vehicle, i want it add too in the "Vehicles" field of the "Company" node.

Can you help me to did that ? I use Views and Display Suite. i'm novice with Drupal and i request your help :)

# Answer
> 0 votes
As you're using plain php (not really bestpractice) you can code it out yourself there, having a select changing a query-parameter for your view (self made contextual filter ..).

A more sophisticated approach would be hooking your view, hook\_views\_pre\_render:

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. Altering the content can be achieved by editing the items of $view-\>result.

Or create a custom page-callback (see hook\_menu), where you embed the view and add the form regarding your query param (or uri param).

You can check permissions with user\_access.

**You won't need to enable php execution with these approaches !**

---
Tags: 7, forms, views
---


title: How to clone an entity?

text:
# Question
Title: How to clone an entity?
I created a custom entity type using `entity_info_hook` and associative hooks. It works fine. Now I want to create a clone of the entity when I press the button `Duplicate`. Is there any method for this? I read `Replicate module` do this finely. But I can't find any sufficient tutorial for the purpose. How can I use `entity_ui_clone_entity()` in my module?

# Answer
> 2 votes
You could call Replicate's `replicate_entity_by_id($entity_type, $id)` method. And maybe hook it's API for custom behavior, see here.

`entity_ui_clone_entity` won't create the new entity, but only prepare your entity for creation, and could be used like this:

```
$my_clone = entity_ui_clone_entity('your_bundle', $my_entity);
entity_save('your_bundle', $my_clone);

```

Or if you created a method for saving your entity, use it direclty:

```
my_entity_save($my_clone);

```

---
Tags: entities
---


# Question
Title: getting URL from Route: breaks in localhost subdirectory
I just had a Drupal 8 site break when moving it from a top-level domain on a server to a subdirectory on my desktop machine: apparently that subdirectory wants to be included in the URL as converted from routes. This threatens to ruin my sandbox environment so I would like to figure out 1) why this is happening and/or 2) what isn't portable about my code fragment below. I've been using

```
Url::fromRouteMatch($route_match)->toString()

```

to get the URL Alias of the current page: e.g., the RouteMatch passed as argument to the breadcrumb service. On the server, this returns a proper pathname relative to the top-level domain, for instance:

```
/dir1/dir2/dir3/myAlias

```

... but running the same code in my sandbox (http://localhost/mySite) includes the subdirectory name, as if Drupal is returning the URL relative my local web server's document root, instead of the root of my Drupal site:

```
/mySite/dir1/dir2/dir3/myAlias

```

I realise there may be better ways to get the current URL Alias (e.g., `\Drupal::service('path.current')->getPath()` and then passing it to `\Drupal::service('path.alias_manager')->getAliasByPath`, but I'd really like to convert the route itself since that's the argument to the breadcrumb builder in Drupal 8.

**p.s., clarification, tentative answer:** it is clear from comments below that the variable `$base_path` is expected to be used here, and that "base path" is how one refers to the name of the site subdirectory (if there is one). Neither of these were known to me when I submitted my question above and I can safely say they're not detailed in the Drupal 8 documentation either. Therefore the question becomes trivial: "How do I strip out that string from the provided URL?" and the answer is a matter of text processing:

```
global $base_path;
$route_url = Url::fromRouteMatch($route_match)->toString();
$alias_url = substr($route_url, strlen($base_path) - 1);

```

**p.p.s., maybe a better answer:** I think I know why comments suggest that finding the URL Alias from the request is the wrong approach, since the `path.current` service factors out any base path beautifully, without the gross string processing as above, and works fine in a breadcrumb builder:

```
$current_path = \Drupal::service('path.current')->getPath();
$alias_from_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

```

Sorry for all the fuss here: from my not knowing about the global variable `$base_path` or about how the Drupal services already deal with subdirectory installations. Looking forward to the answer as expressed by other contributors with an eye on the big picture.

# Answer
Drupal 8 is very smart to detect in which environment it is running. If you have this path

```
/mySite/dir1/dir2/dir3/myAlias

```

then Drupal is installed in `/mySite`, but the root of the webserver is still in `/`.

If you want to get rid of `/mySite` you have to point your webserver at this directory. Usually you define a vhost with this path and choose a local sub domain, which is configured in the nameserver or your local host file.

With a correct configured vhost there shouldn't be any problems.

See https://httpd.apache.org/docs/current/vhosts/
> 1 votes

---
Tags: 8, uri
---


title: Simple field to display static data

text:
# Question
Title: Simple field to display static data
I am trying to do module with different share buttons in form of field to content type. It has no settings, I just need to enable it in admin panel and the button should appear on node. But I cannot get to work simple sample of code like this:

```
function fblike_field_info() {
    return array(
        'fblike' => array(
            'label' => t('Facebook Like'),
            'description' => t('This field displays Facebook Like button.'),
            'settings' => array(),
            'instance_settings' => array(),
            'default_widget' => 'fblike_default_widget',
            'default_formatter' => 'fblike_default_formatter',
        ),
    );
}

function fblike_field_widget_info() {
    return array(
        'fblike_default_widget' => array(
            'label' => 'Like Box',
            'field types' => array('fblike'),
        ),
    );
}

function fblike_field_formatter_info() {
    return array(
        'fblike_default_formatter' => array(
            'label' => t('Like Box (default)'),
            'field types' => array('fblike'),
        ),
    );
}

function fblike_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $link = '<div class="fb-like" data-href="HTTP://ENTER.YOUR.URL.HERE" data-width="80" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>';

    $element = array();
    $element[0] = array('#markup' => $link);

    return $element;
}

```

The result of this code is:

```
<div class="field field-name-field-lubi-to field-type-fblike field-label-above">
    <div class="field-label">Like: </div>
    <div class="field-items"></div>
</div>

```

I already run out of ideas. I have created many modules with fields before, but none was that simple... Am I missing something?

# Answer
> 0 votes
Ok, got this. As far as my field has nothing in $items, in order to print something I had to use this snippet:

```
function fblike_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
    foreach ($entities as $id => $entity) {
        if (empty($items[$id])) {
            $items[$id][0] = 'something';
        }
    }
}

```

---
Tags: entities, social-network
---


# Question
Title: How to specify the numbers of characters for teaser for views block?
I know we can specify the specify limit for the teaser by going to content type -\> manage display -\> teasers. I have made the views block for teasers and I want to display only few lines for that content in particular views block and do not want to affect the stand treasure setting. So, is there any setting in Views which specify the teasers limit for the particular Views block?

# Answer
On the view settings for the field, click on *Rewrite results. Select * Trim this field to a maximum length* and enter a value for the maximum allowed length.
> 1 votes

---
Tags: 7, views, blocks
---


# Question
Title: Fraud detection on hotmail from Simplenews Newsletter
I send newsletters from my Drupal-7 website using Simplenews newsletter module.
But when a user has hotmail, the mail comes with a flag "Be careful. This sender is not approved by our controls for fraud detection."
I googled this and I saw that it has to do something with SPF but I don't understand what this is and what steps do I have to do to fix this issue.
Is there an option from administrator or a line of code I can use?
Thanks in advance!

# Answer
There are a few steps you can also carry out by looking here How can I prevent my mail from being classified as spam?. It includes setting up Domain Keys, SPF etc.

You can also refer to some steps for Microsoft here How to prevent email sent from drupal from going into spam box.
> 1 votes

# Answer
It comes from your host. If it has been used for spam before, there's not much you can easily do.

I highlight "easily".

Set up smtp with Google for $5/month and save yourself the heartache.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to set up a question/assignment pool for a course website?
I have done quite a bit of Drupal work in the past, but am a bit stuck on this one. The basic idea is that the site will offer 1-on-1 tutoring to students. There will be there levels of users: Course Admins, Tutors, Students. What I am looking to do is the following:

1. A course admin can create a pool of "readings." A reading consists of something to read, and an arbitrary number of questions to be answered (currently a text-field entry with unlimited number of values.
2. A tutor, can now create an "assignment" (another content type), for a student that has been assigned to them. To create an assignment, the tutor would simply select from the list of available readings (The tutor doesn't create any questions, readings, etc.. on their own, they must choose from the pool that has been created by course admins). I am envisioning the assignment content type as a cloned reading, with the addition of answer fields for the student to fill in. I believe the reading should be cloned, so that if a course admin updates the questions in a reading while the student is working through answering the questions, their answers will correspond to the old questions.

Any thoughts on how this might be done? Will it require me to write a custom module, or can something like this be accomplished through the basic content type creation + some rules? Any thoughts would be greatly appreciated.

# Answer
> 0 votes
You might want to start from the Answers module. Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

* Question.
* Answers.

The Answers module comes with integrations with other modules such as:

* the Rules module, to add all sorts of business logic to fit your requirements.
* the Userpoints module (and supports voting).

Here is a summary of how I'd implement what you're looking for:

* the **Questions** and **Answers** are 2 content types, implemented via the Answers module.
* Implement the **Readings** as a (3rd) content type, in which you add Entity references to the various Questions that would fit.
* Implement the **assignment** as a (4th) content type, in which you add Entity references to the appropriate readings.

Not sure if it would be a requirement here, but I can imagine you also might want to add the Group module. Some more details about that:

* you can organize the various students that attend a selected course (with group type = Class, or Training), and with each specific course implemented as a "Group".
* the Group roles that would make sense in this case are:
    + course admin.
    + tutors.
    + students.
    + outsiders (= anybody else who is not (yet) involved in a specific class, but for which you want to show them something about such classes, to create awareness).

Disclosure: I'm a (co-)maintainer of the Answers module.

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


# Question
Title: User Reference field with full list of users, but with current user as default selected value
Whether I'm using User Reference module or Entity Reference module, I can't seem to create a drop-down list of all users, where the current user is selected by default.

So all users will be in the list, but I just want to the default selection to be the current user. How can I do this?

# Answer
Using hook\_form\_alter():

```
function example_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id === 'my_form') {
        $form['field_user']['#default_value'] = array($user->uid => $user->name);
    }
}

```

Not tested, but it's the idea.
> 2 votes

# Answer
This is a bit of a stretch, but you could set up a dummy user called 'current user' and set it as the default user for your field. Then, use Rules to target all User entity reference fields (whenever a new node is saved) and change 'current user' to the currently logged in user.
> 0 votes

# Answer
If someone is still looking for a programmatic answer, I got the following to work with my code.

```
$form['field_user']['und']['#default_value'] = (string)$user->uid;

```

You must cast the $user-\>uid to a string because this is what the options array is expecting. I am not certain why I had to use the \['und'\], but it wouldn't work for me without it. I would try it without the \['und'\] if it isn't working for you the way it is.
> 0 votes

# Answer
For a user reference autocomplete field, I did the following:

```
if ($form_id === 'my_node_form') {
  global $user;
  if (empty($form['field_my_field'][LANGUAGE_NONE][0]['uid']['#default_value'])) {
    $form['field_my_field'][LANGUAGE_NONE][0]['uid']['#default_value'] = $user->uid;
  }
}

```

I tested if the value is empty first, so I don't overwrite an existing value when editing the content.
> 0 votes

---
Tags: 7, entities, users
---


# Question
Title: Uninstalling a created custom module in drupal 8
I've created a custom module in drupal 8 and on this module i've created:

* Content types
* Fields
* Entities
* Views ...

all this programmatically.

But the problem when i try to uninstall it the database keep all this forms stored !!!

I'm wondering if there is a solution to automatically delete them from database when uninstalling a module

I appreciate any kind of help :)

# Answer
> 2 votes
See How to delete a content type, programmatically?

You can add enforced dependencies on any config entity, if you do so, drupal will automatically remove them.

That's much better then using hook\_uninstall(), as the user is informed about what will be removed on the uninstall confirm page.

# Answer
> 0 votes
Usually, you need to implement hook\_uninstall to remove from the database all the information set by the module. It is not removed automatically.

Be aware that this hook needs to be implemented in the module's .install file, according to the documentation above.

---
Tags: entities, 8, installation
---


# Question
Title: How to do a date range entityQuery with a Date only field in Drupal 8?
In Drupal 8, the **Date only** field stores data in a **varchar** column in a **CCYY-MM-DD** format, e.g., **2016-04-18**.

As such, you can't simply do a greater than (**\>=**), less than (**\<=**) or similar timestamp based entityQuery anymore.

Is there a simple solution on how to deal with this? Specifically I am attempting to do two queries, one where the date field is between 14 and 21 days old, and one where the date field is 21 and over days old.

# Answer
I'm doing lots of conditions like that in entity queries, I haven't encountered a problem yet.

The main thing you have to be aware of is the timezone the data is stored, which is UTC. You need to convert it to the storage timezone (there's a constant for that), or your query will be off by a few hours.

Here's an example based on something I'm doing, if you only store days, then there is a constant for formatting that too.

```
$date = new DrupalDateTime('21 days ago');
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$formatted = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);

$nids = \Drupal::entityQuery('node')
  ->condition('your_date_field.value', $formatted, '<=')
  ->range(0, 50)
  ->execute();

```

As of **Drupal 8.5** change one should use following to get formatted date

```
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

```

```
$date = new DrupalDateTime('21 days ago');
$date->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$formatted = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

```
> 25 votes

---
Tags: 8, database
---


# Question
Title: How to update 8.0.x to 8.1.x with composer?
This is excerpt from my composer.json file (trimmed for readability). It was created by running `composer create-project drupal/drupal my_site_name 8.0.*` as described on drupal.org:

```
{
  "name": "drupal/drupal",
  "type": "project",
  "require": {
    "composer/installers": "^1.0.21",
    "wikimedia/composer-merge-plugin": "^1.3.0"
  },
  "replace": {
    "drupal/core": "~8.0"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "extra": {
    "merge-plugin": {
      "include": [
        "core/composer.json"
      ],
      "recurse": false,
      "replace": false,
      "merge-extra": false
    }
  }
}

```
1. If I just do `composer update` \- core is not updated, only packages inside `vendor` dir.
2. If in addition to the above, I update my `composer.json` file and replace core version with `~8.1` \- still core not affected.

The only thing that worked for me was to:

1. Remove `core` dir, `vendor` and `composer.lock`.
2. Edit `composer.json` and:
    1. Remove `replace` section.
    2. Add `"drupal/core": "~8.1"` to `require` section.
3. Run `composer install`.

That worked however every installed package complained that:

> Class Drupal\Core\Composer\Composer is not autoloadable, can not call post-package-install script

So I'm not sure if the whole process completed flawlessly. Also removing `core` directory seems like a desperate move.

What is the recommended procedure of updating core to the next minor version with composer (for example 8.0 =\> 8.1)? Note that I am *not using* drupal-composer as suggested in this answer.

# Update 1

After trying to use `composer require --update-with-dependencies "drupal/core:8.1.*"` I got no results:

```
$ composer create-project drupal/drupal my_site_name 8.0.*
Installing drupal/drupal (8.0.6)
  - Installing drupal/drupal (8.0.6)
    Cloning c5afca05cde0c94ef4d7aff5b078be27024670d2

Created project in my_site_name
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]? Y
$ cd my_site_name/
$ composer require --update-with-dependencies "drupal/core:8.1.*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

```

I'm using composer version `1.1-dev`.

# Answer
> 6 votes
I see, you directly get `drupal/drupal`. I don't think that's actually supported, you still get a vendor folder from git and the `composer.json` isn't properly set up. I'm using composer command from this site:

```
composer create-project drupal-composer/drupal-project:8.x-dev myproject --stability dev --no-interaction

```

Regarding update, the trick seems to be the following argument to composer require:

```
composer require --update-with-dependencies "drupal/core:8.1.*"

```

That updated drupal/core and all dependencies it has.

---
Tags: 8, composer
---


title: How to create a table with a filter?

text:
# Question
Title: How to create a table with a filter?
I am using drupal 7

The following code turns an array into a pagered table.

```
$rows = $data[data];
$per_page = 30;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));
echo $output;

```

Is it possible to add filters to the table?

Thanks

Updated 21/04/2016 as Per Neograph734s answer

I have built a module based around the code Neograph734 gave as an example.

My array is built like

```
Array
(
    [0] => Array
        (
            [EventTime] => 23/04/2016 15:00
            [EventType] => Foo
            [EventName] => Bar
            [EventRating] => 99.12
        )

    [1] => Array
        (
            [EventTime] => 23/04/2016 18:00
            [EventType] => FooFoo
            [EventName] => BarBar
            [EventRating] => 94.84
        )

```

The only ammendment I have made is in field to seach as below

```
foreach ($rows as $key => $row) {
  if (preg_match("/" . $form_state['storage']['title'] . "/", $row['EventName'])) {
    $temp_rows[$key] = $row;
  }
}

```

The table initially loads, I have a text area and a submit button. When I enter a search term the page reloads but the table does not filter, it still shows all results.

The html out put is

```
<tbody>
<tr>
<td>23/04/2016 15:00</td>
<td>Foo</td>
<td>Bar</td>
<td>99.12</td>
</tr>

```

What more do I have to change to get the text field to search the results?

Thanks

# Answer
It can be done by wrapping your table in a form, and then use the form API to render your table and re-render it on submit. You can have a look at this comment: https://www.drupal.org/node/1770512#comment-6428358

In short the render funtion:

```
function MY_MODULE_build_form($form, &$form_state) {
  // Filter field.
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title to look for'),
    '#size' => 15,
    '#default_value' => isset($form_state['storage']['title']) ? $form_state['storage']['title'] : '',
  );

  // Submit button.
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Find"),
  );

  // Modify table array here.
  // If your API supports filters, you can use that too.
  // My regex is bad, so you might need to tweak this.
  if (isset($form_state['storage']['title'])) {
    $temp_rows = array();

    foreach ($rows as $key => $row) {
      if (preg_match("/" . $form_state['storage']['title'] . "/", $row['field_to_search'])) {
        $temp_rows[$key] = $row;
      }
    }

    $rows = $temp_rows;
  }

  // Render the table array.
  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Empty Rows')
  );

  return $form;
}

```

And the Submit function

```
function MY_MODULE_build_form_submit($form, &$form_state) {
  // Set the provided filter value in the storage.
  $form_state['storage']['title'] = $form_state['values']['title'];
  // Show the form again.
  $form_state['rebuild'] = TRUE;
}

```

You might want to fancy it up with some fieldsets, but those are left out to keep the answer understandable.
> 1 votes

# Answer
DataTables module offers you a theming function (see *theme\_datatable* in your source) or a views formatter.

> It is a quite handy and popular jQuery table sort/filter/pagination plugin

**But only client-side !** If you want the filter data server-side you need to use the form API too.

You can overwrite DataTables module behavior in your theme to initialize the jQuery plugins according your needs.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How do I add extra/custom plugins in CKEditor?
I do not see the templates plugin under available buttons in my text format

How do I get the templates plugin to show up?

# Answer
You have to build a plugin in Drupal using the CKEditor classes in the CKEditor module in core, it is not an automatic integration.

Check some of the existing modules that integrate plugins for examples on how to do this.

Checkout:
> 2 votes

---
Tags: 8, wysiwyg, plugins
---


title: 'A' tags in Custom Blocks get removed

text:
# Question
Title: 'A' tags in Custom Blocks get removed
I created a few regions for my footer. Inside of each region I've added a custom block with plain html code. One has the contact info, another has social media icons and the last one has a map.

The custom block dedicated for the social media icons has only an h2 heading and the a tags for the icons. I'm using font icons for the logos (I know probably not the best for accessibility), so the a tags don't have any text in between them. I am however using the title attribute along with the href attribute.

Everything gets saved and is rendered correctly, however, when I go back to the custom block to make edits all of the a tags are gone; the h2 tags are still there. As long as I don't hit the Save button again the site remains the same, but if I hit Save, obviously all of the icons are gone. I have Full HTML selected as the Text Format so I know that is not the issue. Is there a setting that I have to set to allow empty a tags or is this not allowed at all??

I don't want to hard-code these sections in my template as I want my site administrator to be able to edit each block if necessary.

Any help would be appreciated.

Thanx

I'm running Drupal 8.05 on Ubuntu 14.04

**UPDATE**

I double checked to make sure there aren't any missing tags. I also updated my code to:

```
<a href="" title="Best Rate Guarantee">
<span class="logo logo-bestrate></span>
<span class="screen-reader-text">Best Rate Guarantee</span>
</a>

```

This time the `a` tag remains but the empty span tag is removed.

# Answer
Just tested this on a fresh install of 8.0.6 and I think I see what is going on.

I saved a block using the Full HTML format with the following content:

```
<a href="#"> </a>
<a href="#"></a>

```

And had it display in my sidebar region. Everything worked fine, there are two links in this block, that can only really be seen if you inspect the html.

However, when going to **edit** the block again, with the default as-installed text format settings, ckeditor will wrap my first link with a P tag, and completely remove the second link.

So, you have a few options.

1. Enter an ` ` character inside your empty tag.
2. Disable the ckeditor for your format and just use the plain-text editor, with the Full HTML (or a custom filter of your creation) filter.

Ckeditor is doing the *fixing* of your html, so getting rid of it will solve your problem.
> 3 votes

---
Tags: 8, blocks, theming
---


# Question
Title: implementation of hook_menu() is not working
I want a page where a user can create 3 different content types : "Machine" , 'Equipment" or "Services" . My goal is to implement 3 tabs for each content type node creation form.

I implemented `hook_menu` like below :

```
function MyMODULE_menu() {

  $items['instrument'] = array(
    'title' => 'Instrument',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );

  $items['instrument/machine'] = array(
    'title' => 'Machine',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'product_node_form',
  );
  $items['instrument/equipment'] = array(
    'title' => 'Equipment',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'equipments_node_form',
  );
  $items['instrument/service'] = array(
    'title' => 'Service',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'member_profile_node_form',
  );

  return $items;
}

```

After enabling my module, I expected that the menu item should be in main menu, but it wasn't there and I got a 'page not found error' when targeting "mywebsiteaddress/instrument" .

Where is my mistake?

# Answer
There are 2 things going on: you've not defined the permissions on the menu & you've not defined the page callback for when the 'instrument' path is accessed. Without this, Drupal doesn't know when or what to display for your 'instrument' menu item.

Doing something like this:

```
  $items['instrument'] = array(
    'title' => 'Instrument',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    //@TODO: define a function called mymodule_instrument_page_callback
    // that will render the page for the 'instrument' path.
    'page callback' => 'mymodule_instrument_page_callback',
    // Setting 'access arguments' => array('view content')
    // will allow anyone with the 'view content' permission to view the menu item.
    //'access callback' can be used for dynamically determining access
    'access arguments' => array('view content'),
  );

```

Will make your menu item available. See the `hook_menu()` docs for information on page & access callbacks.
> 3 votes

---
Tags: 7, routes
---


# Question
Title: How can I add or remove links to nodes in a list depending on the values of some of the fields
I have a lot of content migrated over from a legacy CMS. All of the nodes have some value, but there were a lot of entries that don't need more than for their information to show up in the long lists (They don't need individual node pages). Let's call the three fields that need checking:

* abstract
* related\_websites
* public\_files

What would be the best way to set it up so that if abstract is empty, and the multiple entry allowed related\_websites and public\_files both have no entries, that the entry still be listed, but there be no link to the full node.

I'll need to do this all over the place, from search results to listings by date and by content type, so the easier it is to implement the better. Would this be better done in a theme or a module?

# Answer
> 2 votes
This is probably one of those questions that might fall under opinion-based, but I'll give my answer.

The answer really depends on your needs. It comes down to the question, *does stub content impact display or workflow (editing, moderating, viewing, etc.) around the content?* In either case, you'll want a centralized piece of logic (e.g. `mytheme_is_stub()` or `mymodule_is_stub()` function) that determines if the content meet your stub criteria.

If it impacts just the display then you want a theme; you can use your centralized logic to determine when/where to alter rendering of content.

If it impacts the workflow (e.g. you want to prevent an author from creating stub content or alert them about stub content) then you want a module; you can use your centralized logic to determine when/where to alter workflow around the content.

From your description (altering links, search display, etc.), it sounds like your only concern is display, if that's the case then you want a theme.

---
Tags: 7
---


# Question
Title: Include a part template on specific node page
I would like to include some custom html code only on a specific node. I created "parts" directory and put a custom twig template in it. (mytheme/templates/parts/custom\_html.html.twig)

I then copied over the page.html.twig to my templates directory, and included the custom template with:

```
{% include directory ~ '/templates/parts/custom_html.html.twig' %}

```

I want to show this only on a certain node, say "node/2". I don't wan't to create a custom template just for this page, like "page--node--2.html.twig".

Is there a way of using a condition to just show this template on the specific node?

Kind of like this?

```
{% if 'node/2' %}
    {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

```

# Answer
If you want override page.html.twig for special node 2. You can try this code

```
{% if node.id == '2' %}
   {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

```

if other template you need process in your function theme first:

```
YOUR_THEME_process_FUNCTION_THEME(&$vars) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $vars['node'] = $node;
  }
}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Restrict "add more" button to add new fieldset after adding 5 fieldsets
I have taken a field of type field collection in my user-profile-form and its cardinality is set to unlimited as I wanted to have "add more" button for the users. I want to restrict the addition of fieldset to five numbers.

If I change the number of fields to be displayed to 5 from edit, it renders all the five fieldsets altogether which I do not want.

I tried overriding field\_multiple\_value\_form() in my template.php file but did not succeeded. Please suggest some ideas to achieve this. Thanks In advance.

# Answer
This can be achieved using css. First of all write `hook_form_alter()` on your custom module. and your code should be like this..

```

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    if (isset($form['your_field']['und']['#max_delta']) && $form['your_field']['und']['#max_delta'] == 4) {
      $form['your_field']['und']['add_more']['#prefix'] = '';
      $form['your_field']['und']['add_more']['#suffix'] = '';
    }
  }
}

```

Where `$form['your_field']` is your field collection field machine name. You can write your custom css on #prefix and #suffix and set it to display none.
> 1 votes

# Answer
Try using this module Multivalue Settings

> This module adds some useful settings for fields that can contain multiple values. You can specify:
>
> Number of values allowed Number of values required Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.) Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra)

I had tested and worked well for me. But please use this module at your own risk, as the module owner himself said that its quite buggy.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I download a JPG file from the server?
I have written a custom module in which i have a download button like given below.

```
$form['topics_info_graph']['download_graph'] = array(
 '#type'  => 'button',
 '#value' =>  t('Download Graph'),
 '#button_type' => 'button',
 '#ajax' => array(
   'callback' => 'digitaliq_bckgrd_variable_ajax_download_callback',
   'wrapper' => 'download_graph',
   'event' => 'click',
 ),
);

```

Onclick of this button i need to download a jpg image which is located in the temp folder. I'm able identify the file name and the path, Not sure how to download. any help?

```
function digitaliq_bcgrd_variable_file_download($filename) {
  $temporary_directory = variable_get('file_public_path', conf_path().'/files').'/tmp';
  $temp_path = $temporary_directory . '/';
  // Download logic should come here, any help?
}

```

# Answer
You can set the response headers from the PHP code to trigger a browser download of the file, e.g, something like:

```
function digitaliq_bcgrd_variable_file_download($filename) {
  $tmp = variable_get('file_public_path', conf_path().'/files').'/tmp';
  $filepath = $tmp . '/'. $filename;
  if ($data = file_get_contents($filepath)) {
    $file = new stdClass();
    $file->contents = $data;
    $file->filename = $filename;
    return EXAMPLE_serve_download($file);
  }
  drupal_not_found();
}

/**
 * Serve a file for download
 * @param $file
 * An object keyed with filename and contents
 */
function EXAMPLE_serve_download($file, $type = 'application/octet-stream') {

  if (empty($file->contents)) {
    drupal_not_found();
  }

  $headers = array(
    'Content-Type'              => $type,
    'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
    'Content-Transfer-Encoding' => 'binary',
    'Pragma'                    => 'no-cache',
    'Cache-Control'             => 'must-revalidate, post-check=0, pre-check=0',
    'Expires'                   => '0',
    'Accept-Ranges'             => 'bytes'
  );
  if (ob_get_level()) {
    ob_end_clean();
  }
  foreach ($headers as $name => $value) {
    drupal_add_http_header($name, $value);
  }

  drupal_send_headers();
  print $file->contents;
  drupal_exit();

}

```
> 0 votes

# Answer
You can connect to the server using the FTP protocol, and download the file to show it.

```
function example_download_image() {
  $local_file = 'tmp/download.jpg';
  $server_file = 'tmp_server/download.jpg';
  $ftp_server = "ftp.server.com";
  $conn_id = ftp_connect($ftp_server);
  $ftp_user_name = "user_name";
  $ftp_user_pass = "password";
  $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  ftp_pasv($conn_id, true);
  if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    // Show the file.
  }
  else {
    drupal_set_message("There was a problem\n");
  }
  ftp_close($conn_id);
}

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Show users a different page (depending on their role) after logging in
In my site I have two different roles for users named recruiter and candidate. when they register their account they can choose their role (recruiter or candidate). And when they login my site I will check user is recruiter or candidate. after this check I will show them a different page (recruiter page and candidate page).

How to proceed with this?

# Answer
> 2 votes
Have a look at the Front Page module. Module description:

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> * Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
> * Redirect - Allows you to redirect users to a local or remote URL.
> * Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> * Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

One of the options should fit your need.

# Answer
> 1 votes
You can write a simple module for assigning role

```
/**
 * Implements hook_form_BASE_ID_alter()
 */
function CUSTOM_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Get the system roles.
  $roles = array_map('check_plain', user_roles(TRUE));

  $form['roles'] = array(
    '#type' => 'select',
    '#title' => t('Roles'),
    '#default_value' => array(),
    '#options' => $roles,
  );
}

/**
 * Implements hook_user_insert()
 */
function CUSTOM_MODULE_user_insert(&$edit, $account, $category) {
  // Save the role if it's set.
  if (isset($edit['roles'])) {
    // Push the roles to $account object so that user_save can get the role property.
    $account->roles[] = $edit['roles'];
  }
}

```

And after the user is logged in use Rules module to redirect to any of your page

# Answer
> 1 votes
These are both well used Drupal modules. Login destination does pretty much what you want, Login Toboggan doesn't quite do that but adds some nice signup features that you might want to use concurrently.

Login destination

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.

or

Login toboggan

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> 1. Allow users to login using either their username OR their e-mail address.
> 2. Allow users to login immediately. Provide a login form on
> 3. Access Denied pages for non-logged-in (anonymous) users.
> 4. The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> 5. Customize the registration form with two e-mail fields to ensure accuracy.
> 6. Optionally redirect the user to a specific page when using the 'immediate login' feature.
> 7. Optionally redirect the user to a specific page upon validation of their e-mail address.
> 8. Optionally display a user message indicating a successful login.
> 9. Optionally combine both the login and registration form on one page.
> 10. Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
> 11. Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

# Answer
> 1 votes
Here is the easiest way to do it without installing additional modules: create a module with this code and specify inside the code role names and destinations:

```
function MY_MODULE_user_login(&$edit, $account)
{

    if (user_has_role_by_role_name('role_one', $account)) {
        drupal_goto('role_one_goes_here'); // relative path
    } elseif (user_has_role_by_role_name('role_two', $account)) {
        drupal_goto('role_two_goes_here'); // relative path
    }
}

function user_has_role_by_role_name($role_name, $user)
{
    $role_object = user_role_load_by_name($role_name);
    if (user_has_role($role_object->rid, $user)) {
        return true;
    } else {
        return false;
    }
}

```

# Answer
> 1 votes
You can use the Rules module for this. Here is a rule (in Rules export format tht you can import in your own site using the Rules UI) that should be close to what you'd need (for a recruiter):

```
{ "rules_redirect_to_recruiter_content" : {
    "LABEL" : "Redirect recruiter to recruiter content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "recruiter\/content" } } ]
  }
}

```

This rule assumes that the recruiter role has role id = 4 (change to whatever role id that fits). And the path (in the Rules Action) to redirect to is assumed to be `recruiter/content` (change that path to fit your needs).

You could create a similar rule for "Candidate", starting from a clone from the Recruiter role. Or you could use the the Conditional Rules module to consolidate both rules in a single one.

---
Tags: users, redirection
---