Store all images uploaded to website in specific directory I have been using various image gallery modules, customised views galleries/ slideshow and my images are ending up in multiple directories also stored as different sizes e.g. thumbnail, medium, large...

Is there also a way (maybe a script) to delete the file from anywhere in the directory when the node that holds the images is deleted?

Is there also a way (maybe a script) to delete the file from anywhere
  in the directory when the node that holds the images is deleted?

They get auto deleted when cron runs.


Colorbox images in grid I installed colorbox module and I'm showing images as thumbnails. Each image is in on new line. Is it possible to set it that images will be in the grid similar as here?

I have exactly the same settings as here but don't see any settings to view images as grid, but I have a feeling I saw this somewhere else, but don't remember where.

thank you

You can use CSS rules to position the images like you want.

Another options would be to use views to display the images, which has built in support for displaying items in a grid.

If you want a more detailed answer, you should provide more info in your question.


How to secure individual fields I am looking for a good way to add security at a field level based on a group.  Different groups will use the same content type. Does OG handle this requirement. I don't want to make the full node private.

I think you are looking for Field Permission module. It says :

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


One path alias for differents / multiple internal path? The problem is when a menu item points to a restricted page, the anonymous user can't see the menu link.

So I was looking for a way to setup a path alias so it would point to two internal path => one for anonymous and one for logged users.

Is this solution possible? Do you see another way to show restricted menu item to guests ?

You cannot have one alias for two items. That's not how router works. On the other side, you can create a page only guests will have permission to see, and place it under the same name in the same menu. Then both guests and logged in users will see identical menu, but they will actually get different set of menu items.

If that's not enough, you can use Menu per Role to get more control of who sees what in your menus.


How to db_insert into users? I'm inserting new users into tables users (using a webservice that insert), but how to make uid being automatically inserted and it would be always the next value of the current maximal value on table users (and auto-increment too) ?

Thank you

The users table doesn't have an auto-increment constraint on the primary key (or any field).

The recommended way to add users is using the API (user_save() etc), that will handle the ID for you.

Failing that, just query for the maximum ID in the table before you perform the insert; after the first insert, assuming you have exclusivity on this database while you're developing, you can maintain the increment in your code (no need to check the table each time).

Drupal does exactly the same thing in user_save():

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());


Calendar View of a Field Collections and Contextual Filters I've clicked my way into a corner. So I have a Field Collection called Performance Dates that is embedded to a Content Type of Performance that looks like this:

I would like to put this into a calendar view, listing all dates (the field collection) from a single performance (the Performance content type).

Since Entity Host ID is not offered as a contextual filter, I was thinking to create a contextual filter on the Field Collection's ID.

My question: If I am going about this the right way, is there a way to return an array of IDs here much like using SQL where id in (x, y, z)?

Got it. I started out creating a View from a Template.

Then, I decided to use a module called FullCalendar which is super easy to configure.

And here we go!

There is still some configurations to set in place but for the most part, this issue has been solved.


How do I override the view field? I want to override taxonomy term view views-view-field.html.twig to style the list of taxonomy term content.

I can't seem to find what the correct override is. My debug suggestions are not suggesting anything.

I have tried:

views-view-fields--taxonomy-term--%.html.twig
views-view-fields--taxonomy-term.html.twig

What is the correct template name to target the views-view-fields of the taxonomy term view?

views-view-fields--taxonomy-term.html.twig

This is the correct template suggestion. For it to work however, the default taxonomy view must be configured to render the content as fields rather than as the content its self.


Getting Miss always in varnish cache for the page using REST API While hitting URL using REST API, it is always giving Miss for varnish cache for specific path and giving response from Memcahce. In header if we can check for cache-control we are getting "must-revalidate, no-cache, private". Can someone guide us what exactly the issue or help us with the solution.

First of all, we need to disable "shield" module from our modules and then we need to check Cloudfare rules for caching and need to update accordingly.


GraphicsMagick in Drupal 7 D7 has ImageAPI and that ImageMagick Module is also installed. However I want to use GraphicsMagick with D7 but haven't been successful till now. I have both ImageMagick and GraphicsMagick installed in my Ubuntu Box, I also have pecl imagick and pecl gmagick installed. I know both pecls doesn't work at the same time, but I have been changing configs whenever necessary.

I have tested both ImageMagick and GraphicsMagick from command line, both works perfectly, but I couldn't make it work with Drupal. According to ImageMagick Module I just need to change in Image Toolkit from convert to gm, Drupal reads the executable binary perfectly. I try to upload photo which doesn't show after processing and is also not uploaded in the file. But when I change it back to convert and pecl imagick everything works smoothly.

Any suggestions how to use GraphicsMagick with Drupal 7 ?

I even tried that this http://drupal.org/sandbox/W32/1077458 sandbox project, but no luck...

Many years later, but for future reference, the problem might be related to the fact that you are using the PECL gmagick PHP extension. I believe the ImageMagick module is not meant to work with the gmagick PHP extension. There is a module meant to be used specifically with PECL's gmagick: https://www.drupal.org/project/gmagick . I hope that helps somebody.


how are user ids assigned to new users? what determines what user id to which a new user account will be assigned? On my site, Drupal 7.37, new user accounts are assigned to non-sequential user ids. All new users now have user ids well above 3500.

There are a couple of layers here...

Any code that calls user_save can technically affect what ID is assigned. If the account object has a uid property, that is used, otherwise it comes from the database:

// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

So if an ID is provided, great, if not (which is the norm), it gets more complicated.

The users table doesn't have an auto-increment column (probably because an ID of 0 is used for the anonymous user, and there's no way to support that across all DB platforms). If you were to just get the last inserted user ID + 1, you're open to race conditions when other requests get the same ID returned before the first script has had a chance to insert the record into users.

Because of that, the Sequence API is used. The sequences table has a single, auto-incremented primary key column. When a new, unique, identifier is required, a record is inserted into that table, and the auto-assigned ID is returned to Drupal. That ensures it's not susceptible to race conditions, as the operation has already completed and any other requests would be guaranteed a new ID.

If you just need to hack around the problem you mentioned, and you're not worried about or prepared to take the risk of race conditions, add this to a custom module:

function MYMODULE_user_presave(&$edit, $account, $category) {
  if (!empty($account->is_new)) {
    $account->uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField() + 1;
  }
}


What hook can alter fully rendered html? I'm rendering some JSON using Views and Views Datasource and due to a bug in Views Datasource, I can't seem to get the output rendered properly. So, I'm looking for a workaround.

What hook can I implement in my theme or module that will give me the final string that is about to sent back to the browser that will give me one last chance to alter it?

EDIT: I was in a hurry and worded that poorly. When I say the page won't render properly, I mean that the bug in Views Datasource doesn't use the proper data formatters for the data fields. I'm getting JSON back just fine, but some of the values within the JSON are not properly processed by the relevant module formatters. In this example, the Video field can contain a Video URL and a Thumbnail Image URL. The view is configured to display a Thumbnail Image URL, but due to the bug in Views Datasource, it is displaying the Video URL instead.

I can't just change the render array, because Views Datasource is not generating its output using a render array.

I highly recommend you not to alter the page output when you clearly know where the bug is. See Bala's answer. Or may be you want to let us know what is the exact problem ?

To answer your question, to alter the content that is going to be rendered, use hook_page_alter


How do service tags work? In the user.services.yml, it defines a theme negotiator service as such:

  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

This class determines whether or not the current user sees the admin theme when on the user path.

How does this work? What looks at this and knows when and where to call and instantiate that class? How is it correlated (beyond implementing the interface) to the service below:

  theme.negotiator:
    class: Drupal\Core\Theme\ThemeNegotiator
    arguments: ['@access_check.theme']
    tags:
      - { name: service_collector, tag: theme_negotiator, call: addNegotiator }

Is service_collector something that finds defined services and makes them available by tag name?

What other basic examples of this exist around Drupal 8 core?

Tags are used to find services while building the container by so called compiler passes. They are not available during runtime of the container.

You can find the default compiler passes in CoreServiceProvider::register().

Usually, the tag related compiler passes all do the same thing. Find all services and add them to a service, so that when that service is instantiated, it has a list of service objects that it can do something with.

Thats why this has been abstracted with the service_collector tag, which tells it to pass all services with the tag to the provided method. That's done in TaggedHandlersPass::process()


How to prevent from getting spammed in a contact form I have the captcha image module and an email address keeps spamming me in a website feedback contact form.  I do not know how to get their IP address and I do not want to take down the form for the public.  Any suggestions?

That is why Mollom exists: http://drupal.org/project/mollom

  Mollom may block a post outright if it is from a known spammer. If
  Mollom is unsure how to classify a post, it may require the completion
  of a CAPTCHA to accept the post. Posts that do not match a "spammy"
  text pattern and do not originate from known spammers are accepted
  without the need to complete a CAPTCHA.

  A stand-alone CAPTCHA solution, which neither considers user behavior
  nor point of origin, can never achieve this level of informed
  protection, and generally requires users to solve a CAPTCHA on every
  post. Using Mollom's text analysis, users must only solve CAPTCHAs
  when Mollom is unsure about a post.


In Views, how to wrap a div around every specified number of items I'm using D7, Views 3, and am playing around with using jQuery Cycle. What I would like to do is amend my view output so it's like in this example from the jQuery Cycle website:

I was hoping to use Semantic Views for this but I'm stuck on how to wrap the div class "slide" around every 3 items. Is it possible to do this? I only seem to be able to apply a div to every item and then apply the class to every 3rd item. Any help/guidance/tips much appreciated.

In the View, there is a Theme: Information Link under the Advanced Tab. There you can theme your view with template files the way you like.


Table of dynamic and static content? With Drupal and views you can generate a table with for example a list of users and their contact details.

Let's say I have a user outside of the system that I want to add to the table statically, what's the best way to do this in Drupal?

The ways I am thinking of are:

Write a module that db_select or use enityfieldquery into an array, add the external user info and put it through theme table and outputs it on a page.

Override the views template and add the user info there.

Are there better ways?

Low level way is to use hook_query_alter - with it, you can add UNION with anything.
More direct Views way is hook_views_post_execute:

This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.
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.


theming field collection in node add form I have themed node/add form of a special content type using the following instruction:

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

and I have changed this form to a table.

Now I'm struggling with a field collection with unlimited number of item.
As I have hidden the default form of displaying node/add form when I click on 'add another item' of the field collection, nothing happens.

What I want is to show the next form of the field collection as the next row of the table ready for the user to fill it out.

Any help would be appreciated.
thanks in Advanced.

You'll need to hook into the field collection entity on insert, and add a callback function to trigger the new row to appear via ajax in your table.

Check out field_collection.api.php in the field collection module for a full list of field collection api calls/methods.

Also, you may find the responses to this previous post as a good indicator of the direction to take: Perform actions on field collection insert or update


Linking terms to views instead of taxonomy pages I have created a view for movie genres, with contextual filters to generate such pages as /horror, /comedy, etc.

When I tag content or users, I want the links which then appear on these pages to refer to the view. Right now they go to the term page.

I have heard that the TVI module is the way to go, but I can't find any documentation about it.

I don't even want these term pages to exist at all - I have essentially made my own, to my own specs. How can I make this happen?

If you're dealing with a limited number of terms (genres), you can do the following:

Head to Structure > Taxonomy > List Terms (next to your genre category)
Click Edit next to a term.
Uncheck "Generate automatic URL alias" under the URL Path Settings.
Enter the path to your View.
Repeat.

You can also use the PathAuto module to set up rules for automatic forwarding of Taxonomy links to your Views. Install PathAuto, enable, click Configure, select the Patterns tab, and rewrite the URL path for Taxonomy.


Automatic username generation from name fields at registration Drupal core 8.6.5

I am trying to change the user registration process to omit the username field and generate the username from the first name and last name.

Since I am new to Drupal and want to learn more I try to go without project modules for that task.

So far I set up a custom module and deactivated the username field.
Now I should set a default value for it.

How can I set the username built of first name and last name before the process is going on?
And strip some blanks, unallowed characters, ...

I was thinking of hooking into function user_validate_name
Is that possible?

My module so far:

<?php
use \Drupal\Core\Form\FormStateInterface;

/**
* Implements hook_form_FORM_ID_alter().
*/
function my_register_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    $form['account']['name']['#access'] = FALSE;
    $form['account']['name']['#default_value'] ='tbd'; und
}

Thanks for your help!

This is an interesting case in Drupal 8. Previously we could look at the user registration form's validation processes, which in Form API were callback strings in the #validate property array (or attached to each element in the #element_validate property. Note that the Drupal term "element property" means an item in a form array prefixed with a "#".

A basic strategy is similar: alter the form's #validate property and add, not replace, a string referencing a valid PHP callable. Again, probably best to re-order validate callbacks for first-in, first-out.

// Probably best to add this as the first element of #validate
$form['#validate'][] = 'my_register_form_validate';

Then implement the function or callable.

function my_register_form_validate($form, FormStateInterface $formState) {
  // This should do the trick.
  $formState->setValue('name', $name);
  // But you might need to get the entity from form state storage?
}

But we also need to make sure that the user account form doesn't let you change user name, of it does, then add the same validation/form alter.

In Drupal 8, entities often have their properties validated not in the form but as part of Symfony Constraints as part of their Typed Data data definition. This is so that Drupal is more API-first rather than form-driven (like in Drupal 7).

So I think you're on the right track to look kind of into user_validate_name, but it appears to be unused except in the installer. I think that modifying the entity's base field definition and adding a new constraint would work too.

To do this implement hook_entity_base_field_info_alter. Also see the following question How to easily alter an entitys base field definition per bundle?.

function my_register_form_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['name']->getConstraints()
  }
}

Then implement a Constraint plugin and its corresponding ConstraintValidator class. The ConstraintValidator class might have a validate method like this:

public function validate($items, Constraint $constraint) {
  // The entity should be available on all fields as a parent typed data via FieldItemListInterface::getEntity method
  $entity = $items->getEntity();
  // Generate user name as say $name.
  $items->set($name);
}


Filters and relationships data from a display to another within the same view Hi everybody,

I've been freshly introduced to Drupal and I'm having my first "serious" issue with contextual filters and relationships. Here is the context :

I have a "process" content type and several contents (processes)based on it
Some processes (contents) have an field, called "sub-process", which is an entity reference to processes
I made a grid page view showing every process and a bloxk view showing every "sub-process"
In every cell of the grid, there is one process and I want to display the sub-processes attached to it.
I can display the name of every process's sub-process through the "sub-process" field, but I would like to display other properties of these subprocesses.
To do so, I used the Views Field View module and a Global : view field. The problem is that it shoes all the subprocesses in all the cells of the gris except the right ones.

Any idea how to proceed ?

On your "subprocess" display, you need to add a relationship to the process that is referencing that subprocess. Then add a contextual filter of the process id using the relationship you created. Finally, add a field "Id" in the "process" display and pass the process id as contextual filter in the global view field (check the replacing patterns).


Should I rewrite my links into aliases? Is it of any advantage, in addition to using Global Redirect, to rewrite html links from /node/nid to /article/this-is-the-title, even though in both cases traffic is directed to /article/this-is-the-title (by Global Redirect).

Edit:

From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests a way to intercept links, passing them through functions to "convert from node/nid to article/title". However, I am green at coding Drupal, and have no clue as to go about it. Could some one advise on alternatives? Or ways of making this less cumbersome?

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.

From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests using the l() function to have Drupal use "pretty paths" automatically.

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.


How can I add menu items when importing nodes into Drupal 7 (with the Feeds module)? I'm importing a site using the Feeds module, and I do not see any way to specify which nodes should get a menu item.  How can I do this?

If the Feeds module cannot do this, is there another way?

You can try the sandbox project Feeds Menu

  Adds mapping elements for menu entries for feeds


Alter a select form using preprocess function For some reason I want to alter the value of a select list in an exposed form of views .

I've added this code to the template.php and also Clear the cache :

function mytheme_preprocess_views_exposed_form(&$vars) {
  $myviewID = 'views-exposed-form-ouvrage-page';
    if ($vars['form']['#id'] == $myviewID){
      foreach($vars['form']['field_categorie_tid']["#options"] as $option_term){
        $optionterm = $optionterm."test";
       }
     }
}

After this with devel themer I can see the changes that I've mad but when I clear the cache the changes dosen't take in the select list

am I missing something ? I'm new with preprocess function

In your foreach loop, $option_term is a copy of the current variable returned from the iteration. If you want to change the original variable (i.e. what's in $vars['form']['field_categorie_tid']['#options'][index]) then you need to pass it by reference:

foreach($vars['form']['field_categorie_tid']["#options"] as &$option_term){
    $option_term .= 'test';
}

Or refer to the array member explicitly like so:

foreach($vars['form']['field_categorie_tid']["#options"] as $key => $option_term){
    $vars['form']['field_categorie_tid']["#options"][$key] .= 'test';
}

I generally prefer the second method as passing variables by reference in this way can sometimes cause some strange behaviour.

You also had a slight code error, the variable is called $option_term in your loop declaration but $optionterm in the loop body.

Just FYI, template preprocess functions are really not the best place for this sort of code. You would be far better off using hook_form_alter().


Variation on Views exposed filter I am working on a Drupal 7 site. One View on the site that lists hundreds of publications around a scientific theme has this great set of exposed filters in a bar at the top that allows researchers to search the publications. Unfortunately, the site owner and graphic artist went a little wild with another section, and designed this great set of filters that should bring up results in a View, but the filters aren't on a View page. Can the "exposed filters" for a View Page be placed on a different page altogether?

Thanks for your help!

Yes, make it a block. Assign it to a region on a particular page. When the user clicks the Apply button the view will be displayed.


How do I import product category based on taxonomy vocabulary? I have a products catalog based on taxonomy vocabulary, as advised the term reference field is on the product content type.

Products imports are working fine, but when I try to import product displays the mapping for term reference (Category vocabulary)does not appear in the target list.

I'm using Feeds 7.x-2.0-alpha8, Commerce Feeds 7.x-1.3, Commerce Kickstart 7.x-1.19 and Drupal Core 7.22

Thanks in advance

You probably need to add your taxonomy vocabulary field to the product display.


Print user uploaded logo in twig template How can I print a user uploaded logo (via the theme appearance UI) in a twig template?

For example, in block--system-branding-block.html.twig we can use

Available variables:
- site_logo: Logo for site as defined in Appearance or theme settings.

  <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />

What do I need to do to make that variable (or a custom variable) available to another twig template, like menu.html.twig?

I have found many solutions, but all them involved hardcoding the logo file name or location, both of which are obviously not user friendly.

All of you need to do is to Add New Regions to your Theme like logo_region and then print the site logo on desired twig template with below code:

{% if logo_region %}
  <div class="my-style">
    {{ page.logo_region }}
  </div>
{% endif %}

And finally enable/place your site brand in created region (logo_region) on Block layout page:admin/structure/block


How do I write a hook to compile css and js with drush make? We are using drush make in our deployment of new and updated platforms through Aegir and thus drush provision.
We do not keep our theme css and js under version control as it complicates any conflict resolution between coffee and scss source files.
I want to automate the compiling of the css and js directories as part of the Create new platform provisioning script run by Aegir but cannot think of the right way to do this.
Main issues:

The granularity of a drush-hook-post-make is too course; not every download needs to be processed: e.g. only one theme needs to run a compile script after having been cloned from our git repo by drush make. How would we distinguish which downloads needed post-make processing?

git pre-commit and post-checkout hooks are under vc in the theme's repo and would do the compiles but need to be explicitly invoked.  Currently we manually symlink to the vc'd git hooks and run the compiles ... would like to automate this step.

In general, you shouldn't use Drush for that. Instead, use a build process, and one of the steps in the build would be drush make.

There are a number of existing build systems that can be used to achieve what you're looking for, including (but not limited to):

Phing - https://www.phing.info/
Jenkins - https://jenkins-ci.org/
Grunt Drupal Tasks - https://github.com/phase2/grunt-drupal-tasks
Aquifer - https://github.com/aquifer/aquifer

A typical process would have the following steps:

Delete build TARGET directory
drush make drupal.make TARGET --prepare-install
Symbolically link custom profiles, themes, and modules
Execute task to compile CSS, JS


How to show different delta of a multi-value token? I have a multi-value field for user statistics (around 18 INT values): the field field_nurse_patients contains 18 integers 0,5,3,3...

Is there a way to get a format like below with tokens? Maybe with the token custom module or programmatically?

Desired output:

points: 0
height: 5
weight: 3

I've tried accessing the individual values like

[current-user:field_nurse_patients:0]
[current-user:field_nurse_patients:0:value]
[current-user:field_nurse_patients:value:0]
[current-user:field_nurse_patients:und:0:value]

None of which allows me to target the individual deltas.

There are a couple of similar (older) questions, but none of them really answers it.

Tokens for multi-valued fields?

What is the correct token for a multi value field?

You can get to the delta values of multi-value fields with the help of Compound token (it doesn't have to be a compound token, it can be something like [node:field_test:und:1:value]).

As you've already figured out you need Token filter to evaluate tokens in Textarea fields, such as Views Headers or Footers.


Payment to make a node featured I want users of a particular role to pay for featured nodes. On my site, the user role "premium member" is able to create nodes of type "products," but they have to pay to make their node (product) featured--for this I have a CCK checkbox field which will be checked on payment.

I am using moneyscript module for subscriptions, but I do not understand how to use it for my requirements.

I am thinking about using a custom module, but I'm also not understanding where to start and what should be the approach.

I presume you're using the MoneyScripts "Membership Suite" module? You'll want to install the Rules contrib module, which will allow you to modify content (your node's CCK field) when a payment is made:

  New Rules Integration allows you to take action when users purchase a new membership, make a payment, cancel their membership, etc! The possibilities are limitless!


Including custom functionality with multilingual capabilities from the start Imagine you have a global Drupal site with several languages. One market wants to add custom  functionality for just the English language. From a technical standpoint would it be better to develop the custom functionality with multilingual capabilities by default?

I understand this is a high-level question, but was wondering on the pros and cons. The custom functionality would fit well with other languages, so two specific questions are for instance:

Is the consideration of multilingual often more expensive than developing the monolingual version?
On the long-term is it better to have the multilingual version from the start instead of adding it in a later phase? (updating code after functionality was pushed live).

Generally speaking, making a module ready for multilingual use is so incredibly easy when you're building it that it makes a LOT of sense to do it.   Retrofitting would be a real pain in the ass!

I'm not exactly sure what module you're building, but it could be as simple as wrapping any user facing copy with t().


How do I create an ideogram-based 'features' list on nodes? I'd like to create a simple checklist-style list on a node. How can I do this?

I presume CCK is involved. I'm thinking that it would follow some logic like this: the node editor checks applicable boxes for the relevant feaures. If a box is ticked, then an image is displayed in the list (and so on) on the node.

If you get a Drupal 6 specific answer, that's great, but in the meantime, I would suggest you look at this question. It involves Drupal 7, but the basic principal is the same. If I have had the experience of doing this in D6 I would have added the information to that question, but I have not.


Which modules help with loading of large images in a nice transition? Currently I am using the single_page module that does the anchor page sliding thing on the page, but currently I'm loading big images onto this single page. Which modules or recommendations on how to streamline the loading of these large image files? I tried the image_lazyloader module but none of the images show up when activating this on the single_page module. I'm guessing these two modules have a conflict. What other possible options do i have? it seems that spotify.com has the same setup, how are they doing it there?

Take a look at JAIL. You will also need the jquery jail plugin.


What does Contextual Filters (in Views) serve for? I was playing with filtering content using views but seems I can't make them work the way I want : to display the articles of an edition based on the latest issue no. (or latest issue date) on the frontpage. I figure out this can be done using contextual filter but don't know how.

My content types are:

editions: edition_no, edition_date, edition_title
article: title, body, edition_no.

Many thanks for help.

Contextual filters in Views 3 replaces the 'Arguments' of Views 2.

It's best used with paths as outlined in this video: http://nodeone.se/blogg/learn-views-with-nodeone-part-19-contextual-filters-with-paths.

By the sounds of it, the filtering of your view could do the same job.


What are some ways to implement a hierarchical taxonomy page structure? I'm currently trying to decide how to architect a client's site, and they need to have the need to have a hierarchical page structure. This must be able to go at least 3 levels in depth and have the option of exposing various filters.

I would assume that using a view that accepts multiple arguments and using taxonomies would be the way to go about developing this, but I wanted to ask this community if there were any contrib module alternatives I might look into as well.

Drupal taxonomy was born for these needs.

And Views is perfect if you need simple filters.

If it's a high volume of pages and search functionality is going to be important, you can integrate it with Apache Solr and use Facets to filter. What better example than drupal.org


How to edit the id of a form element of a content type? I have a content type with a text field that I need Javascript to do some work on (when in the content type add/edit form). I prefer to have Javascript identify the form element by it's id so I would like to set the id of the form element to something meaningful.

I've attempted to set the id in with a hook_form_alter() but to no success. If I kint() out the template with the form I do see the id being set in the kint() info however the actual form element html is unchanged. My hook_form_alter():

function hook_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_element_name']['#id'] = 'element_name_id';
}

Is what I'm attempting possible and if so does anyone know how to do this? Or is there some completely different way of achieving this?

Thanks!

I figured it out by digging through the kint() statement. Turns out the id is buried deeper in the $form array. Here is what worked for me:

function hook_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_element_name']['widget']['0']['value']['#id'] = 'element_name_id';
}


"Fetch entity by property" for users that share terms with new node I have a content type of RFP that has a term reference field named "RFP Categories".  The users also have this same term reference.  When I publish a node, I want to email all users who selected a category that is tagged in the node.

This SE post (Email users on node creation based on taxonomy reference) comes very close to the answer I am looking for, but I'm not quite able to follow it.  I believe in their case they are setting the 'value' to a specific taxonomy term, whereas I need to fetch any use who has a term matching the node's terms.

My rule has the Fetch Entity by Property action seen below.  Unfortunately, I cannot see (or maybe I'm failing to understand) how to link the "RFP Category" terms in the node to the terms in the user entities. It is broken somehow because when I publish an RFP node, I get a SQLSTATE error.

This is what my rule looks like so far.

I think the reason for this is that the 'Value' property is asking what you want to match in what you are looking for, basically in pseudo terms, what you've got above is:

Find the Entities of type: User
Where the Entity's property: RFP Category
Is equal to: The author of the node's Categories

This is where your selection falls down, because you're trying to search for a set of answers where the data matches an Array. If the node you create can only have 1 term entry (not multiple), I would use the action 'Add a Variable' and set it to the taxonomy term you've created on your node, something like

Add a Variable > Taxonomy Term > [node:RFP-Category] I'm guessing to your setup

This will create a new token for you which contains the Taxonomy term you're searching for. Then in your Entity query, you can use this as your value property

eg

Find the Entities of type: User
Where the Entity's property: RFP Category
Is equal to: [Your New Token]

If your RFP category has more than 1 or unlimited values, you will have to create a loop of the categories on the node first, then use 'Add a variable' and carry on with the same method


Can the 'update' module be made less aggressive? Running an update check on all the installed modules on my site takes quite some time, and sometimes even exceeds PHP's runtime limits. Leaving the module enabled makes using the web based administration very difficult, as many different actions cause it to make a full run.

Is there a way to leave the module enabled, but only have full updates triggered by cron instead of every time the status or module pages are visited in admin?

I'm using Drupal 6.26.

As far as I can tell there's nothing about visiting the modules admin page (or any other admin page) that would invoke a check for update data.

Drupal 6

For Drupal 6 the work is done by _update_refresh(), which is inadvertently called from several places within the update module itself. Those of note include:

update_cron() - called only during a cron run.
update_status() - page callback, only invoked when visiting the update report page.
update_requirements() - invoked when you visit the status page.

Since none of those are called for every admin page, and Drupal 6 doesn't have auto-cron (you also mentioned in the comments you don't have poormanscron installed), it doesn't seem like any of the core functions will be the culprit.

There's no way to unset hook implementations for specific modules in Drupal 6 (there is in Drupal 7, see below) so short of editing the module file directly I don't think there's anything you can do about that.

Drupal 7

The work is done by update_get_available(), and that function is only called from 4 places by core:

update_cron() - called only during a cron run.
update_manager_update_form() - page callback, only invoked when visiting the update manager page.
update_requirements() - invoked when you visit the status page.
update_status() - page callback, only invoked when visiting the update report page.

If the update is happening on any other pages than those listed above it's either caused by a contrib/custom module, or (more likely) because you have auto-cron on, and the cron run is being invoked. There might be more to it than that but I can't find anything looking through the core code.

As far as the status page goes, you could remove the update module's implementation of hook_requirements() from the cached list of hook implementations, effectively stopping the check from happening when you go to that page. It means you won't ever get that particular line in the status report, but if you're ok checking for updates manually then this won't be a problem.

The way to do this is to implement hook_module_implements_alter() in a custom module:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'requirements') {
    unset($implementations['update']);
  }
}

Either version

You can slow the frequency of update-checks down a bit by setting the update_check_frequency variable to something longer than standard. The variable contains the number of days that need to pass before the update data is checked again.


Is it possible to use a replacement kernel without hacking core? I'd like to use a replacement DrupalKernel.

It looks like the default is hardcoded into index.php, despite the existence of DrupalKernelInterface:

$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');

I suspect the answer has to be no, but I thought I'd ask anyway: is it possible to use a custom kernel class without hacking index.php?

Well, let's take a look at the classes implementing DrupalKernelInterface. Beyond DrupalKernel, you will find

TestKernel
InstallerKernel
TestRunnnerKernel

Especially the second and the third are very interesting and gives you an idea what these can be used for: if you have a very unusual request flow which should be much more rare than in Drupal 7 then you can write a special Kernel to help. Your entry point will not be index.php but that's fine.


Add a class to a field based on the page regions I have my field tpl file which sets in a div classes 'field-item', 'odd/even' etc. I need to dynamically assign a class to it based on the regions that exist on the page. I am using bootstrap theme and the class I need to add reflects the column span count, so f I have a sidebar on the left I will have less space for that field and need a narrower column class.

Bootstrap already comes with a function doing it for page preprocess:

function mytheme_preprocess_page(&$variables) {
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 3;
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['columns'] = 2;
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['columns'] = 2;
  }
  else {
    $variables['columns'] = 1;
  }

So basically what I need is to make my field aware of that page variable. How can I use this variable on my field tpl file?

A quick look shows that the content region is wrapped in a class derived from that $columns variable, getting it from this function...

/**
 * Returns the correct span class for a region
 */
function _bootstrap_content_span($columns = 1) {
  $class = FALSE;

  switch($columns) {
    case 1:
      $class = 'span12';
      break;
    case 2:
      $class = 'span9';
      break;
    case 3:
      $class = 'span6';
      break;
  }

  return $class;
}

...so you should be able to use the cascading features of CSS to theme your field, eg...

.span12 .your-field-stuff {
  /* widescreen */
}

.span9 .your-field-stuff {
  /* one sidebar */
}

.span6 .your-field-stuff {
  /* two sidebars */
}


URL rewrite of localisation with nginx I'm having trouble with changing the url of a drupal localisation. All urls are clean, but contain a non-clean localisation part; ?q="language", e.g. ?q=de, ?q=fr.
The site runs on nginx + mysql + php5.

I want to change this to either site.tld/"language"/page or to no url at all, e.g. site.tld/page.

How to change this in the rewrite rules?

This answer should help:
https://serverfault.com/questions/488444/nginx-rewrite-convert-querystring-to-path/488480#488480

I would try something along the lines of:

location @drupal {
  if ($arg_lang) {
    rewrite ^(.*)$ $arg_lang/$1? permanent;
  }

  rewrite ^ /index.php;
}

The above assumes that requests with ?lang=XX do not have any other arguments, and that the request does not already have the language prefix in the page request (ex: /XX/node/123?lang=XX).


What is the difference between "Language: Not specified" & "Language: Not applicable"? What is the difference between Language: Not specified and Language: Not applicable in Drupal 8 In the context of multilinguality ?

There was no such distinction in Drupal 7 (and 6, IIRC) and it seems to me a bit redundant in comparison to the Drupal 7 method of Language: Natural vs Language: name. I also didn't find any documentation about this in a quick Google search about the difference and thought it would be nice if we would have an explanation here.

Not applicable means that we know that the very concept of Human languages doesn't apply to this textual piece of content. A relevant example for such content would be Binary code.

For more see http://www.w3.org/International/questions/qa-no-language#nonlinguistic.

Not specified means we don't know if the text might or might not include human-language content.

For more see http://www.w3.org/International/questions/qa-no-language#undetermined.

(Both "see more" links are taken from the code documentation in \Drupal\Core\Language\LanguageInterface which explains those constants quite well).

In general, both options makes no difference to how content is displayed, but they let you treat differently to content on your site if you'd wanted to (in views, custom code, ...)


Call custom form in a block I am trying to call a custom form in a block. The form is written in my custom module.
I tried different ways to call the form, but not getting the form.

Here is the syntax, I last tried.

$form = drupal_get_form('my_custom_form');
print drupal_render($form);
//my_custom_form is my form_id

(or)

drupal_render(drupal_get_form('my_custom_form'));

Here is the link I found a similar question, but didn't get the correct solution for my question.
Form within a block

You should return your form using drupal_get_form in the content definition of your block. Drupal will do the rest.

For example like this:

function YOURMODULE_block_info()
{
    $blocks = array();

    $blocks['custom_block'] = array(
        'info' => t('Custom block example'),
        'title' => t('Custom block example'),
        'region' => 'content',
        'status' => 1,
    );

    return $blocks;
}

function YOURMODULE_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'custom_block' :
            $block['content'] = YOURMODULE_block_content();
            break;
    }

    return $block;
}

function YOURMODULE_block_content()
{
    return drupal_get_form('my_custom_form');
}

function my_custom_form($form, &$form_state)
{
    // Build your form

    return $form
}


How can I set the template to use for a view page display? I created a view for my content, where fields are displayed as a page.
Scanning the source code, I noticed it uses the html--default--2.html.twig template.

I created a new custom template. how can I set that template for all the view pages, instead of the default template? I need to edit the whole page, including header and footer.

Notice that I've read this and this about custom templates for view.
I've tried to rename my custom template views-view--page.html.twig, and put it in my template folder, and also in /core/modules/views/templates, flushed cache, but nothing happens. My view page is still using the default template.

if you want to add new page template only for views:

Implement hook_theme_suggestions_page_alter like the following:

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function mymodule_theme_suggestions_page_alter(&$suggestions, $variables) {
  //- Get the current route name.
  $route_name = \Drupal::routeMatch()->getRouteName();
  //- Check if the current route is a view.
  if (strpos($route_name, 'view') === 0) {
    //- Add suggestion to page when its a view page.
    $suggestions[] = 'page_views_view';
  }
}

Now in your views page you will have suggestions something like:

<!-- FILE NAME SUGGESTIONS:
   x page-views-view.html.twig
   * page--en.html.twig
   * page--list-page.html.twig
   * page.html.twig
-->

Now implement hook_theme like the following:

/**
 2. Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'page_views_view' => [
      'base hook' => 'page',
    ],
  ];
}

Then Create page-views-view.html.twig template inside templates folder in your module root folder.
Flush all cache.


Images from ipad not rotating properly I have noticed that users who upload their images from iPad or iPhone have their images sometimes rotated in odd directions. I am not a Drupal guru and I generally find that documentation on drupal "how to" is ..well.. scarce,,

I have spent some time looking into this and did not find anything that would effectively help me.

What I would like to accomplish seems simple in principle but I need help.

Rather then forcing users to rotate images (they find that to be clunky and awkward I have an average user who is interested solely to have things happen simply and without hassle) I would like to have ALL my images on the site checked for orientation and have them automatically display the images in proper orientation.

I came across a module called Imagecache Actions and it is supposed to have Autorotate capability but I have no clue on how to use it for what I need.

ALL help would be greatly appreciated!

The -auto-orient operator is part of the ImageMagick image processing toolkit, to select the correct orientation of an image based on its EXIF data. Have a look at How to detect shot angle of photo ... for a more complete explanation.

The ImageMagick module integrates this function in Drupal, but they are still having an issue with autorotation. A recent patch is available there.

Your best bet is to try it out and see if it corrects your problem.


uid 1 super user - what is is for There is Drupal super user with uid = 1. I was trying to find out what is so special about this account and what activities will require this account. Is it necessary to have access to this account for Drupal page administration. I would like to know a list of thing that will require super user access. I would also like to know what is so special about this account. As far as I know there can be only one super user in Drupal.

The Drupal user with uid = 1 is created by Drupal during the installation process of Drupal. User 1 bypasses all access callbacks in the system by default -- he can see/do anything.

Beyond that it is a typical Drupal user. If you want to secure the "admin" or uid=1 user please refer to this documentation page: Securing user #1 on steps you can take to secure the usage of the uid=1 user.


Refresh two views with same exposed filter using ajax I have a site with a map and a grid in the same page and they both have exposed filters enabled, yet I only have the exposed filter of the grid visible at the page. When the grid view is not using ajax, when the page refreshes all works well, yet I would like to use ajax to update the map and the grid with filtered results at the same time to improve the user experience.

Things that I have tried and that I have already discarded:
- Views Global Filter: I've tried this approach but it is kind of a mess since I have many fields to filter and sort with, and custom search preferences that I store in a session preferences key. And when I used it i had the impression that it was not possible to use with sorting preferences.
- views_embed_view: I've read that this may be the solution in some posts, but I don't understand yet what this call does and my site has a complex layout and I just cannot embed one view after another.
- Other stuff in a custom exposed filters submit function.

Ideally the solution would be to call an ajax refresh function from the custom submit function or to trigger it with javascript, when the update of the grid is triggered, it would be simple since the grid and the amp use the same arguments.

What I have thought what could be a hacky solution is to add the second exposed filter, to hide it with display:none, and then fill it with javascript and trigger the submit event whenever the visible filter of the grid is triggered. Nevertheless, if someone with proper expertise in Drupal can give me hint of how this should be properly accomplished it would be great!

ATTACHMENT is what you need!

Try using an "Attachment" in view, what you can do is create your View which can be either Content, User or Term View and just after that add an Attachment and attach is it the required view display, before or after that depends upon your requirement also don't forget to inherit contextual and exposed filter which should act as the key property here.

For a quick view purpose, I'm attaching a demo view exported code:

$view = new view();
$view->name = 'demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Demo';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Author uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'node';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'Author UID';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'demo/%';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';
$handler->display->display_options['inherit_exposed_filters'] = TRUE;


Customize permission in permission page I want to have multiple roles in my site :
FirstOne is Admin :
 Admin is not super admin (user 1) but Admin can define permission for other users .
Permission is controlled by Super Admin .
i want to show some of the permission options in the admin/people/permissions not all of them for this role.

Any idea ?

Thanks in Advance

You can do this by using any of these modules :

User Protect

  This module allows fine-grained access control of user administrators,
  by providing various editing protection for users. The protections can
  be specific to a user, or applied to all users in a role.

Role Deligation

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

Administer Users by Role

  This module allows site builders to set up fine-grained permissions
  for allowing "sub-admin" users to edit and delete other users — more
  specific than Drupal Core's all-or-nothing 'administer users'
  permission. It also provides and enforces a 'create users' permission.


Change Drupal interface language back to English I made the mistake to translate the Drupal interface in my local language. But since the language is set into the database, I can't delete this language using the Drupal UI. And I'm not sure which file(s) to delete in the database.

Does anyone know a (faultlessly) way to translate the Drupal interface back to English?

You can change the language back to English by adding this to the url of any page:

&language=en

EDIT:

To have a seperate admin and front end language I'd suggest looking at the Admin Language module - http://drupal.org/project/admin_language

SECOND EDIT:

To do this via role have a look at this page - http://deglos.com/blog/2010/06/12/overriding-language-drupal-backend

They are doing what you want with a custom module. You could throw in the user role code there using the global $user.


Set default length for node id Is there a way to set the node ID length for a specific content type?

I want to have a specific content type have an ID of 8 digits long so that it can be used as a claim number for the clients paper work.

How would I go about setting this default?

It's generally considered bad database design to give primary keys any business meaning. Just think what will happen if your business changes and your claim number format isn't the same anymore. Changing primary keys in DB is very hard to do.

Malks advice is very good. Add a specific claim ID field to your content type and use token and Automatic Node Titles module and maybe Pathauto to get nice URLs.


how to validate file upload in drupal how to validate file upload in drupal
means,

in my form allowed only txt file, but now user also can upload image file also after change the extention .jpg -> .txt

function oz_workbench_moderation_buttons_form_alter(&$form, $form_state, $form_id) {
  dpm($form);
  if ($form_id == 'catalog_node_form'  )
    {
    $form['#validate'][] = 'upload_validate_function';
       return $form;
    }
}

function upload_validate_function(&$form, $form_state){
$extensions = array('txt' => 'text/plain; charset=us-ascii','doc' => 'application/msword; charset=binary','pdf' => 'application/pdf; charset=binary','xls' => 'application/octet-stream; charset=binary','docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary');
$uploadedfile=count($form_state['values']['field_application_document']['und']);
        for($i=0;$i<$uploadedfile-1;$i++){
                $file_name=$form_state['values']['field_application_document']['und'][$i]['fid'];
                $file_handler = file_load($file_name);
                $file = $file_handler->uri;
                $filename = $file_handler->filename;
                //echo $file;
                $finfo = new finfo(FILEINFO_MIME);
                $type = $finfo->file($file);
                //echo $type;
                    if (!in_array($type, $extensions) )
                    {
                    drupal_set_message(t($filename.' is not valid file'), 'error');
                    }
         }
}

If your are writing your own validation u can use finfo_file from php

http://www.php.net/manual/en/function.finfo-file.php

Example #1 A finfo_file() example

<?php
  $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
  }
  finfo_close($finfo);
?>

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel


getting response back from a Java Servlet to Drupal My working scenario is like this,
A webform (suppose an admission form for school) should be there on my drupal site and when a user clicks "submit" button a nicely formatted pdf file should be generated.

my approach is like this:
1. I have created a webform using webform module

I have written a servlet to generate pdf file (currently hosted at another server)
now I want to have communication between my servlet and drupal, so I created a small
module that will execute custom function whenever user clicks submit button of the webform.

I am using curl to send the form data to servlet and it is working with http code 200.following is my code.

define("URL","http://localhost:8080/pdf?");
//my data actuly its coming from the webform
$fields = array(
  'name'=>'deepak',
);

$fields_string = http_build_query($fields);
drupal_set_message($fields_string);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
curl_close($ch);

I am getting the PDF file encoding printed in the browser. How can I force User to download it.

please guide me.

To force download, you want to set the proper headers for filename, content-disposition and content-length. In your case, it may need to be set from the Servlet application, but without knowing the details of $response, that's difficult to determine.

In general, though, your headers should look something like this:

'Content-disposition:attachment;filename=foobar.pdf' (content-disposition:inline is the opposite of this)
'Content-length:1234567098'


How to Output Realtime Computed Field Value I have created a computed field (computed_field module) and I'd like the calculated value of this field to be computed on the fly for each of my views results.
Specifically, I have a start time, and and end time for each "Offer" (content type) in my view. I have created a computed field that determines whether the current time is between the start time, and end time, and then outputs a string value of "now" or "ending_soon" or "starting_soon" or "default" (if it's outside the parameters). I'm doing this all because I need to use the contents of this calculated field as a path variable for custom map markers in a google map (different 'pins' for offers/deals that are happening now, vs ones that are happen earlier or later in the day).
inside my THEMENAME.theme file:
function computed_field_field_now_compute($entity_type_manager, $entity, $fields, $delta)
{
  // from the database:
  $timestamp = $fields['field_business_dates'][0]['value'] ?? "";
  $endtimestamp = $fields['field_business_dates'][0]['end_value'] ?? "";

  $now = gmdate('Y-m-d\TH:i:s\Z');
  $utc = new DateTimeZone('UTC');
  $startDate = new DateTime($timestamp, $utc);
  $endDate = new DateTime($endtimestamp, $utc);
  $nowDate = new DateTime($now, $utc);
  $startSwatch = date_format($startDate, 'B');
  $endSwatch = date_format($endDate, 'B');
  $nowSwatch = date_format($nowDate,'B');
  $cutOffSwatch = 22; // Note: 41.6 = 1 hour;
  $endingSoonTime = $endSwatch - $cutOffSwatch;
  $startingSoonTime = $startSwatch - $cutOffSwatch;
  $value = "default";

  if ($nowSwatch >= $startSwatch && $nowSwatch <= $endSwatch) {
    if ($nowSwatch >= $endingSoonTime) {
      $value = "ending_soon";
    } else {
      $value = "now";
    }
  } else if ($nowSwatch >= $startingSoonTime && $nowSwatch <= $startSwatch) {
    $value = "starting_soon";
  } else {
    // return default value
  }
  return $value;
}

As these calculations are time-sensitive, I've turned off caching with the hope that the values are calculated on the fly and displayed in my view. But they are not displayed in views, and don't seem to display at all unless I save each individual node first. As I have over 6500 nodes...I don't see this as feasible. How can I ensure that when a view needs to display the calculated field, that the calculation is executed and rendered?

"How do I output a computed field value in real time?"
The answer is that you cannot.  The Computed Field module updates the value on entity save.  So, to get the most recent value, you have to save the entity.
If you are trying to show a value that you compute in a view, computed field is a bad solution because you will have to re-save all the entities whenever you display the view, which is horrible for performance.
Alternative solution idea
Since you're doing calculations based on time, one option might be to use Views filters.  Make a primary view that shows the default pins, and then embed or attach additional views that have filters that are set to find the pins for ending_soon and starting_soon.
If you need to override the Views filter calculations, you can do that in hook_views_pre_view():
Here's a code example from one of my sites where I override the filter value to use "midnight for the logged-in user's timezone)."
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() === 'my_view' && ($display_id === 'my_display') {
    $filters = $view->display_handler->getOption('filters');
    if ($filters['field_datetime_target_value']) {
      $user_timezone = date_default_timezone_get();
      $current_timestamp = \Drupal::time()->getCurrentTime();
      $midnight_usertimezone_datestring = MYMODULE_get_midnight_datestring("$current_timestamp");

      $filters['field_datetime_target_value']['value']['value'] = $midnight_usertimezone_datestring;
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}


How to scrape specific elements of the Drupal theme to a file? I want to save two divs - one with the site header and the other has the main nav menu - to a PHP file that can be used in other (even non-PHP) sites to replace their header and menu using Javascript DOM insertion and CORS with a header on the saved file that allows cross-origin resource sharing.

The idea is to update the distibution code automatically on cron or on demand, when changes in the menu are made, so they will be reflected in the satellite sites.

I have been able to create a working proof-of concept using simplehtmldom on the current version of our site. However, when I tried to adapt it to the new version in dev, using a different theme as a subtheme of Adaptive Theme, then simplehtmldom cannot read the URL properly - it seems that the blocks are missing see https://drupal.org/node/2139613

The divs are not $page regions, although the header-wrapper div contains the $page['header'] region (and the region is invisible to simplehtmldom).

I looked at the Web Widgets module, but that is for content and views - I want to get the theme elements in the header-wrapper and the nav-wrapper, two arbitrary divs at the top of the page.

It's also frustrating that I cannot access the $page array or even the $variables in my module. I had to set the module weight to 1 to be "heavier" than the simplehtmldom module, since there are other modules that require simplehtmldom module (like devel themer) and I don't want to load its library twice. But I tried the latest simplehtmldom library separately, with the same results.

I know there are scraping tools based on node.js but I'm looking for a more lightweight solution. simplehtmldom worked, but in the new site it doesn't

I solved the issue, and it may have been related to

// the zero here is necessary because simplehtmldom returns a collection
$topbar = $html->find('#header-wrapper', 0)

Here is my sample code - I am thinking about contributing a module for this function, with some admin settings

// get the header code and write it to a file
function module_name_global_header_write() {//dpm('raw_html');

    // there may be an issue if we are processing this function while viewing the same url as $sourceDomain
    // perhaps we will need to create a page or URL that is not viewed but can supply the HTML for the header
    $sourceDomain = 'http://site_name.com';
    $sourceMenuId = 'superfish-1';

    // initialize simplehtmldom objects
    $html = new simple_html_dom();
    $responsive_desktop_css = new simple_html_dom();
    $global_styles_css = new simple_html_dom();

    // load files into simplehtmldom
    $html->load_file($sourceDomain); // the generated HTML
    $global_styles_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/global.styles.css');
    $responsive_desktop_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/responsive.desktop.css');

    // #header-wrapper and #nav-wrapper are the ids of the header and menu
    $topbar = $html->find('#header-wrapper', 0); // the zero here is necessary because simplehtmldom returns a collection
    $navbar = $html->find('#nav-wrapper', 0);

    // prepare Cross Origin Resource Sharing header
    $header = "<!-- This header necessary using CORS http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ -->
    <?php
    header('Access-Control-Allow-Origin: *');
    ?>";

    // some more CSS rules that are not in the css files
    $morestyles = '#google-appliance-block-form{width:100%;height:30px;text-align:right}#block-google-appliance-ga-block-search-form .container-inline div{display: inline;}.element-invisible, #block-google-appliance-ga-block-search-form label, .url-textfield{display:none!important;}#nav-wrapper ul li a, #menu-bar ul li a {padding: 5px 8px;}#nav-wrapper ul li.last, #menu-bar ul li.last {
    border-right: none;}';

    // prepare the CSS style tag; in case we do not want css, we only have to unset the $global_styles_css var
    $cssStyles = $global_styles_css ? '<style>' . $global_styles_css . $responsive_desktop_css . $morestyles . '</style>' : '';
    // replace relative image urls with absolute
    $cssStyles = str_ireplace("../",$sourceDomain . "/sites/all/themes/adaptivetheme/site_namedaptive/",$cssStyles);

    // assemble output from components
    $output = $header . $topbar . $navbar . $cssStyles;

        // create directory if not exists
        if (!file_exists('public://global_header')) {
                mkdir('public://global_header', 0777, true);
        }

    //write the file that will be fetched by the script tag embedded in the target site
    $filename = "public://global_header/raw_header.php";
    file_put_contents($filename,$output);
}

here is the code in the js file:

//cross-browser see http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){ //IE
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}
var sourceURL = 'http://site.com/';
var request = createCORSRequest("get", sourceURL + "/sites/default/files/global_header/raw_header.php");

if (request){
    request.onload = function(){
    // do stuff if request is successful; if it fails, there is no replacement of existing HTML in target site
  // look first if a container with id #header-id exists, if not use the existing #topbar container
    document.getElementById('header-id') ? document.getElementById('header-id').innerHTML = request.responseText : document.getElementById('topbar').innerHTML = request.responseText;
    // change a relative image URL into absolute
    document.getElementById('branding').getElementsByTagName('img')[0].src = sourceURL + '/sites/default/files/image.png';
    // change relative Google Appliance Search action into absolute
    document.getElementById('google-appliance-block-form').action = sourceURL + '/';
    };
    request.send();
}

example script tag:

<script src="http://site.com/sites/all/modules/custom/module_name/module_name.js"></script>


blocked due to MIME type (“application/octet-stream”) mismatch I've been troubleshooting a memcache issue on our Drupal 7 site and in the process the front end CSS broke, meaning all content was unstyled.
The Chrome console has a message:

The resource from “/sites/all/themes/mbm/css/style.scss?qktcrf” was
blocked due to MIME type (“application/octet-stream”) mismatch
(X-Content-Type-Options: nosniff).

Should Drupal be using a .scss file on the front end?
If not, how would I determine where the breakdown of the .scss being converted to a .css file occurs?
Help appreciated.
Steve

Pretty sure that the scss files should be in a scss folder, and not the css folder.
/sites/all/themes/mbm/css/style.scss?qktcrf


How to save a vote of an anonymous user only after registering using modal window? Here is my usecase:

Only authenticated user can vote.
If an anonymous user tries voting, after the voting is done, the user is represented a modal window for login/register.
If the user registers or loges in, the vote is saved.

The vote calculation is done using cron or other module. I do not have tie up with any particular module (and fine with writing a basic one). I am currently trying my luck with Rules, Voting Rules, Fivestar and obviously, Voting API. For login/registration persona and fbauth is used, so no email verification is requierd.

A similar problem is discussed in A module that allows user to create content anonymously, then if they register, assigns the content to them, however my use case involved voting and email-free registration. Voting makes it more complicated while email-free registration (hopefully) makes it easier.

PS: I want to follow the same work flow for different nodes with plus1 (or similar) module, so a generic approach is requested.

You could store anonymous votes in a cookie, then on login/register, check to see if that cookie exists and cast the votes accordingly.

When an anon user tries to vote, use user_cookie_save() to save the Entity Type and Entity ID of the Entity that the user was trying to vote on in a cookie. Name it something like pending_votes. At the same time, you can trigger your modal login window. It's possible that a user won't login/register at that time and it's also possible that they will attempt to vote on other Entities before finally logging in. So you'll probably want to store the Entity Type and ID as a serialized array.
Then you can hook into a user logging in with hook_user_login() and check for the existence of the pending_votes cookie. If it's there, use it's contents along with votingapi_set_votes() to cast the pending votes. (delete the pending_votes cookie afterwards so they don't cast more votes each time they log in)


How do you modify the form after it validates and show's errors I have built a form using CCK in Drupal 6. I have two fields, one which is called health plans and the other is called terms. If I select a health plan I update the terms via AJAX (both are select lists).

So for example: (health_plan_field)Plan A -> (terms_field)(1, 3, 6, 12)

I submit the form and serialize the terms inside a session so that I can keep them.

My problem is that if the form has errors, the terms field is blank because it starts empty until a health plan is selected. So if I have already selected a plan and terms, when the form returns after errors I have nothing.

I have tried to use form_alter (have used this before) by recursively walking down the cck fields on $form to modify the term_field options based on what I have in the session. This does nothing on return.

My code is as follows (called from hook form alter):

function acg_pportal_new_service_order_form_cck_walkerTerms(&$array, &$cck_fields) {

$terms = unserialize($_SESSION['termDataFromForm']);
if (!empty($terms)){
    foreach($array as $key => &$value) {
        if (in_array($key, $cck_fields)) {
        unset($value['value']['#options']);
        $first = "";
        foreach($terms as $key2 => $value2){
            if (empty($first)){
                $first = $key2;
            }
            $value['value']['#options'][$key2] = $value2;
        }
            $value['value']['#default_value'] = $first;
            $value['value']['#value'] = $first;
        }

    }
    }
}

Is there anything that you know that will help me in this case.

You need to set the form to rebuild on validation fail.

$form['#rebuild'] = TRUE;   // cause form rebuild after validation failed

Then you can use your $form_state['values'] inside your hook_form_alter().

OR

You can create a custom function and use the #after_build property.


Drupal testing with DrupalGetAJAX I'm working on writing some automated tests for an AJAX API, and getting strange results. If I directly view the page, I see the following output, sent by drupal_json_output:

{"guid":"8e2a179e-c901-8744-05fc-e80de9500dd6","success":1}

My unit test hits this same URL. Here's the test function:

 public function testInit() {
    $response = $this->drupalGetAJAX('plugin/init', array('query' => array('guid' => $this->registered_user->uuid)));
    $this->assertEqual($response['guid'], $this->registered_user->uuid, 'GUID Loaded');
    $this->pass(json_encode($response));
  }

When I initiate the test run, it goes to the usual batch API progress page. Rather than moving directly to the test results page, I get "An error has occurred, please continue to the error page". Here's the output that follows:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=64&op=do StatusText: OK ResponseText: {"guid":"a06f78ec-1368-f4c4-c9ac-a710b3e941b5","success":1}{"status":true,"percentage":"100","message":"Processed test 1 of 1 - \u003Cem class=\u0022placeholder\u0022\u003EPlugin\u003C\/em\u003E.\u003Cdiv class=\u0022simpletest-fail\u0022\u003EOverall results: 7 passes, 1 fail, 0 exceptions, and 1 debug message\u003C\/div\u003E\u003Cdiv class=\u0022item-list\u0022\u003E\u003Cul\u003E\u003Cli class=\u0022first last\u0022\u003E\u003Cdiv class=\u0022simpletest-fail\u0022\u003EPlugin: 7 passes, 1 fail, 0 exceptions, and 1 debug message\u003C\/div\u003E\u003C\/li\u003E\n\u003C\/ul\u003E\u003C\/div\u003E"}

This reads to me like some sort of error within the test runner, as you can see the response from the AJAX API module is there. It looks like it's showing my module's JSON output concatenated to the output of the batch call to the test runner.

The output for $response is always "1" when viewing the test results page. In the detailed test result page, the call is listed as follows, returning 1 byte:

  GET
  http://platform.dev/plugin/init?guid=5b299683-49d8-7754-f9ca-3fb88e79ff0f
  returned 200 (1 byte).

For experimentation sake, I also ran the test suites for AJAX commands and the batch API. The same thing happens. My best guess is that this is a bug in Drupal 7.15.

The issue is a known one, and a patch fixed the issue - http://drupal.org/files/drupal.simpletest-curl-cookiejar.33.patch


how to use cookie to protect other node pages in Drupal some bots are grabbing my site's content everyday,I confirm if I set cookie protection the bots will not work again.

My question is how to use cookie to protect my content? if someone has no cookie then he can't go to next page.

Sounds like a case for user authentication?

The problem is the first page request will never have a server-side set cookie as it will be set on the subsequent request and you don't want to deny access on your homepage.

You could set the cookie with javascript, but then you risk blocking users with js disabled.

Requiring user login would be the easiest solution.


When and where does Panels get the title out of a View? Two part question about Drupal 7, Panels 3, and Views 3.

I have a view that I have added to a content area in a panels page.  Right now, the title from the display is being used as the pane title.  I need to dynamically set the title of this from a module.

When does Panels pull out the display title from the view?
Where exactly does it pull it out from?

I cannot seem to override this from any view hook.  For example,

function foo_views_pre_view (&$view, &$display_id, &$args)
{
    $view->display[$view->current_display]->display_options["title"] = "Foo";
}

doesn't seem to affect the pane title, though the value does propagate through all of the other view hooks.

I suspect I can create a workaround and use a custom block instead of the view directly, but I would rather not do that in this case.

Thanks.

I was hoping that someone would answer this, so I wouldn't have to answer my own question when I found the solution.

Credit goes to a co-worker (who doesn't really post here) who reminded me that you also need to update the handler:

function foo_views_pre_view (&$view, &$display_id, &$args)
{
  $view->display[$view->current_display]->display_options["title"] =
  $view->display[$view->current_display]->handler->options["title"] = "Foo";
}

When you do this, the title does propagate properly to the pane title.


Include AF container in pathauto URL I am using the 'Advanced Forum' module with Drupal 7, in conjunction with the 'pathauto' module. I would like to include the parent forum, if  not the container of the  parent forum as well, in the URL of the forum topic, so it is like: forums/catergory/forum/topic-title. However, I can not seem to find compatible tokens/replacement patterns in order to do so, so I was hoping somebody here could provide a solution for me, please!?

So far all I have is: forums/topic-title!

After several hours, and help from the user spovlot in #drupal-support, we have a working answer for D7:

(edit: this has been tidied up some more!)

Pattern for all forum topic paths:

forum/[node:taxonomy-forums:parents:join-path]/[node:taxonomy-forums:name]/[node:title]

combined with

Pattern for forum and forum containers:

forum/[term:parents:join-path]/[term:name]

This gives a result of:

/forum/container/sub-forum/title-of-a-post

Note that:

/forum is the name of the forum (i.e. no a forum, but a description)
Any number of containers and sub-forums will work. (forum/container/sub-a/sub-b/title-of-a-post)

Hope it helps!


Disabling core block system in Drupal 7 We are using Drupal 7 with context. I have understood that in Drupal 6 the core block system is inefficient in terms of performance. According to this article http://treehouseagency.com/blog/neil-hastings/2010/10/14/context-everywhere in context module (Drupal 6 version) there is a setting to disable the core block system. But in Drupal 7 context module configuration I cannot find this setting.

How can I make sure the core block system doesn't take part in the showing of the blocks? Ideally I would like to block access to admin/structure/block (since I don't want anybody to set blocks via that interface) but allow to access to admin/structure/block/add (since I want to be able to create blocks but show them with context).

The block module is not required by core; just go to mysite.com/admin/modules and disable it, if you don't want to use it in your site.

EDIT to address your updated question. This code should do the trick. It will deny access directly to the blocks admin overview page, but will still allow access to the add block page.

function mymodule_menu_alter(&$items) {
  // Deny access to the blocks overview page.
  $items['admin/structure/block']['access callback'] = FALSE;

  // Explicitly allow access to the block add page
  $items['admin/structure/block/add']['access callback'] = 'user_access';
  $items['admin/structure/block/add']['access arguments'] = array('required permissions');
}


Need to change the title of views I have created a view which displays all the posts of an author. I need to set the title as - "(Author Name)'s Posts" or "Posts by (Author Name)" where Author Name will change depending on the profile the reader is visiting. Can someone please help me with it...

If you are using Contextual Filter in the view then you can override the title by putting %1 for first argument, %2 for second argument etc..

Otherwise add a contextual filter for something like "Content:Author"(depend upon your need) in your created view & override the title in there by placing %1


How do I programmatically change contextual filters? Basing on a blog post, I wrote the following code.

/**
 * Implements hook_views_pre_view().
 */
function mm_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() != 'product_listing' && $display_id != 'page') {
    return;
  }

  $tid = reset($args);

  if (! $tid) {
    return;
  }

  $term = Term::load($tid);
  $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
    ->loadTree($term->getVocabularyId(), $tid);

  foreach($terms as $child_term) {
    $args[] = $child_term->tid;
  }

}

I cleared the cache, but the code I wrote doesn't have any effect. The SQL query is not altered; only single taxonomy ID is returned. I have selected Allow multiple values for the filter.

What is wrong with the code? How can I fix it?

Args should be concatenated with , or +.

This work:

  $term = Term::load($tid);
  $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
    ->loadTree($term->getVocabularyId(), $tid);

  foreach($terms as $child_term) {
    $args[0]  .= ',' . $child_term->tid;
  }


How do I embed a view of comments within a view of nodes using Entity Views Attach (EVA) I have one view of nodes. My row style is field. Originally I was trying to create a view that displayed all of the nodes, and all of the comments on those nodes.

I run into trouble using a relationship, because then I get duplicate records for every node. So I'm now trying to make a separate comments view and use entity views attach to attach the comment view as a field to the node.

The problem I am running into is that it seems like there is no way to do this using the fields row style. The only place I can add the comments view is in the displays option.
how can I display a view of my comments within a view of my nodes.

It's not really practical to intercalate the rows of one view into another view. Instead, what I would do, would be to create a view with node as its base table, include comments via a relationship, and select "distinct" under query settings in the advanced Views settings column.


Access denied to login to original node id Scenario is this:

User sent a link to a website where they must be authenticated to view content.
User clicks link.
They have an account but their session has expired so they get 403 access denied page.
They login.
The ideal outcome is they are redirected to the original link they tried to access.

I can get a login form to show on the 403 page but can't redirect to the node.

Has anyone any experience of this?

Login Destination claims to do what you need:

  It is also possible to keep users on the currently visited page after logging in or out.


How to load third party php library in drupal 7 module? Suppose i want to load facebook-php-sdk for facebook connect in my drupal website, how can i load that class file in my module, i tried with libraries module, with different function provided with that api, but everytimes i fail.

You can do the same way in Drupal for Facebook module and put these code in your custom module:

 $fb_lib_path = function_exists('libraries_get_path') ? libraries_get_path('facebook-php-sdk') : 'sites/all/libraries/facebook-php-sdk';
 $fb_platform = $fb_lib_path . '/src/facebook.php';
 try {
     if (!class_exists('Facebook') && !@include($fb_platform)) {
      //show error
      return NULL;
     }
     $fb = new Facebook(array(
       'appId' => $appId,
       'secret' => $secret,
       'cookie' => $cookie));
 }
 catch (Exception $e) {}

You can check the fb_api_init function of Drupal for Facebook module for more detail.


Custom Drush command without module I am a newbie into Drupal.
I recently learned to create custom Drush command inside a custom module. I am wondering if I can write a custom drush command and its definition without any module or outside module. for eg. If I have no custom module in my drupal project.
This custom command is available for execution only if my module is enabled. Can I write a drush command which is completely module independent?

Is it possible?

You might be interested in the drushify project, which will create a Drush commandfile for you, from a template.  You can give it the name of a module, and run it from a Drupal site to make a Drush command for a module, or just give it an arbitrary name and run it from outside any Drupal site, and it will create a global Drush command.

From there, you only need to go through and fill in the parts of the template that it made for you.  You may delete any of the optional hooks that you don't need -- which is usually most of them.


Is it possible to use a list of values from a views display as exposed filter of another view? I have a view with a page display where I have some fields showing. One of the fields is field foo. I want the user to be able to filter the view by the foo value, choosing one or multiple values. I want the items of foo to be available in a list. Can I accomplish this using the data of another display where I have all the unique values of foo?

Thanks!

To do this,

Install the entity reference module.
Create an entity reference view (like creating a block or content pane). The results in this view will be your exposed filter.
Create an entity reference field in your content type.
In that field's settings, select the above view.
Use this field as an exposed filter.

Without more detail, I can't really describe how to set it up accurately but this is generally the accepted method.


How do I export my site structure? Since Drupal 8 is days away from release, I've started experimenting with rebuilding my personal site on it. The one feature I am really looking forward to is configuration management in code.

Unfortunately, my taxonomy terms are not exported by the config module. From what I've found googling on the subject, neither are menu items.

Which leaves me stumped. The natural way to set a sites structure (or information architecture) is a combination of content types, taxonomy vocabularies and their terms, and a set of menus. Or, at least, that seems to be the natural way to me.

While googling, I could not find any discussion on this subject.

So, how do I export the taxonomy terms and menu items that define my sites structure?

Edit to add some details:

Assume the site is a magazine. It has Fiction, World Events, Technical, and Letters sections. There will always be a /fiction, a /world-events, a /technical, and a /letters menu items. There are several kinds of content types, each can go into various sections.

So I create a vocabulary for the sections.

sections
- fiction
- world events
- technical
- letters

A taxonomy reference field is added to each content type.

Thus, when content is created it is tagged with the appropriate section terms.

If the site deploys without one of those sections, it is broken. Thus the menu items, and taxonomy terms should be considered configuration. Not content.

From what I've read, the main problem is that terms and menu items can collide if you try to move them between instances. Terms have a incrementing tid. Menu items also have an incrementing id. Though I do see the taxonomy_term_data and menu_link_content tables which seem to map uuid's with term and menu item ids. So, couldn't that be used to make exporting them feasible?

Also, isn't one of the main uses cases for taxonomies defining a site's structure?

I guess what I'm stuck on is that some menu items and some taxonomy terms really should be considered as configuration, not data. As in, if I were coding this instead of using Drupal, I'd hard code them. Thus, they should be exportable so that they can be committed to version control.

And that's why I'm asking "How do I export my site structure?"

For install content, you can use Default Content for D8 (also on GitHub). For ongoing content syncing Entity Pilot is expected to enter public beta this week and there is an active initiative around Deploy module.

Disclaimer: Entity Pilot is my project.


Edit button in teasers i'm using display suite and views in one of my teaser content type and i'm trying to add an EDIT button right in the teaser, but i can't find the function to do this. So i came here to ask for help. Can you help me? Thank you

The edit function is usually provided in teasers with contextual links.

Activate the optional core module, and when the teaser is displayed, a contextual links icon will be displayed at the upper right corner of the rendered teaser.


Want to generate csv of a view programmatically in drupal 7 I have a view in drupal 7 and I want to generate a csv of this view programmatically after click any button.

Views data export

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML

You should created a Views with CSV display. And then created a bottom that point to that page.


How to add theme from github with composer I have a Drupal 8 installation and I like to install a theme from github.com using composer.

It is this theme https://github.com/forumone/gesso

Can anybody help me what I have to add to the composer.json and where?

If you still want download theme from github, you can edit file composer.json by add more repository:

Add this code

 {
    "type": "package",
    "package": {
        "name": "forumone/gesso",
        "version": "2.0",
        "type":"drupal-theme",
        "source": {
            "url": "https://github.com/forumone/gesso.git",
            "type": "git",
            "reference": "8.x-2.x"
        }
    }
}

after

{
    "type": "composer",
    "url": "https://packages.drupal.org/8"
},

and run composer require "forumone/gesso"
 to download theme and update composer.lock.


Views 2 - Don't display results if user DOES NOT have a specific permission I am trying to hide the results of a view from users who have a specific permission. For instance, Let's assume that a user has the permission "create page content". I would like for the view to show NO results to this user.

I can't restrict on roles because the user can have overlapping roles. Basically, I need the "Access" portion of views to work opposite of how it normally does.

I suspect I should be able to do this with the Global:Null argument validator, but I am having no luck. However I am assuming that has more to do with me weak php chops.

Thanks in advance.

Hook_perm to the rescue! I would suggest thinking the other way around: Grant access to the view's results if the user HAS a permission. Create a new permission and assign it only to the roles that may view the results.

In your custom module, add a new permission like so:

function mymodule_perm() {
    return array('can view results of my view');
}

Then in your view, change the 'Access' setting to your new permission.

You may run into problems if the roles that you're trying to exclude have the 'Access all views' permission (or a similar administrative views permission). If that is the case, you'll need to use a views hook to remove the results.

function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'the_view_name':
      if(!user_access('can view results of my view')) {
        $view->result = array();
      }
    break;
  }
}

I would flush caches in order to have this hook picked up by views.


Commerce Kickstart Facet Displays Item Count Even With Option Disabled I'm using Kickstart2.

I imported a new set of Categories and Collections using a Taxonomy Feed Importer. Seemed to work OK but now, the facet display -always- shows the item count for -all- search vocabularies, even though I have that option disabled in each search field eg.

admin/config/search/facetapi/search_api%2540product_display/block/field_category/edit

I can't see how the Feed Import would cause this so maybe that's a red herring, but regardless, this worked properly -before- my import and now I can't turn this item count off.

Any idea how to get rid of these?

You have to configure the settings under vocabulary, go to admin/structure/taxonomy/product_category/edit and then uncheck the Display number of items that's it, it will not show you the count anymore.