Get all the fields attached to an term How can I get a list of all the fields that have been attached to a taxonomy vocabulary?

I have created 2 new fields using admin/structure/taxonomy/[machinename]/fields now I need to get all the fields and use them on a settings form. I have the vocabulary machine name, but how do I retrieve all fields created?

You can use field_info_instances() which:

  Retrieves information about field instances.

In the case of taxonomy terms the code would look like this:

$instances = field_info_instances('taxonomy_term', $vocab_machine_name);

The $instances array will contain (amongst other things) the machine names of all the fields attached to the term, if you want further information about any or all of those fields you can run the names through field_info_field().

I think the file that function lives in is included by default but if not just add this before you call it:

module_load_include('inc', 'field', 'field.info');


Add a class to the  tag on a node view Is there any module that adds a field to all nodes and then add the value of that field as a class on the  tag of the page when the node is displayed?

This is quite simple and could likely be done in template.php. I would start with the following:

hook_preprocess_html() to hook into the rendering of the <body> tag.
menu_get_object() for loading the current node (in some themes it might already be present in $variables as  $variables['node']).
Grab the data the user entered into the field using field_get_items or something similar.
Pass it to drupal_clean_css_identifier to ensure it's ready to be used as a class.
Add it to the end of the $variables['classes_array'] variable.
Clear the cache to ensure your new hook is picked up.


How to switch between conflictual hooks? In a custom module I'm implementing the hook_menu_alter hook to alter the page callback for the $menu['taxonomy/term/%taxonomy_term'] menu.

I've noticed that my hook is not implemented because another contrib module ( Taxonomy Display module ) already implements the same hook (all works fine if I disable TD).

What I need is not to prevail on TD hook with mine, but to use my hook under a certain condition, and TD hook for all other cases.

The condition is the presence of parameter "v" in the querystring, like the following example:

if url == taxonomy/term/tid?v=value then use mymodule_menu_alter

if url == taxonomy/term/tid then use taxonomy_display_menu_alter

How I can do that?

Thank you very much!

MXT

If you implement a hook, it will always be executed.

The condition of a query string makes things more complicated in your situation, because all menu items are defined by their path (taxonomy/term/tid in your case). This means that - as far as Drupal is concerned - taxonomy/term/tid?v=value and taxonomy/term/tid have the same menu item, so both requests will be handled by the same code.

Is it really necessary that the URL takes the form of ?v=value? If you could make it taxonomy/term/tid/value, you can create your own custom menu item for taxonomy/term/%/%, and simply leave the taxonomy/term/tid path as is.


how to perform versioning content between users? I need to create a content type "Project Software". Users can upload source code to their projects as a portfolio editing option. In one project can participate more users. So I need a solution for versioning the project so that it can be shared for online editing code.

You should take a look at the project module. This is used on the drupal site as well.


Create a log of create/delete users in Drupal 7 I'm creating a log with several actions in drupal.

I register similar actions with hook_watchdog.

/**
* Implements hook_watchdog().
*/
function MYMODULE_log_watchdog(array $log_entry) {

  if($log_entry['message']=='Login attempt failed for %user.'){
    my_log_function();
  }
}

But I do not know how to detect that is created or deleted a user, and record this information in my custom log.

I'm new in drupal development and I Appreciate any guidance to investigate. Thanks :)

You could actually log the details about user creation at hook_user_insert(), and deletion using hook_user_delete().

User creation: Acts on new user creation

function MODULE_user_insert(&$edit, $account, $category) {
  watchdog('user', 'User created with ID: %userid', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}

User deletion: Acts on account deletion

function MODULE_user_delete($account) {
  watchdog('user', 'User having ID: %userid deleted', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}


How should I load a node with its images programatically? I want to load a node with its images in Drupal 7, such as using the following code:

  $current_node = node_load(arg(1));
  db_query("SELECT nid, title FROM {node} WHERE type = :type AND created < :created LIMIT 1", array(':type' =>  $current_node->type, ':created' => $current_node->created))->fetchObject()

I wish to load the image field in the content; I think I should use left join to load the image file.

Does anybody know what to do next? What is the image table name?

You're going to have to join another table for every field that you want to grab the data for, which is just a pain. Instead, you could just get the nid with your query, and use node_load() a second time to get the other node object, complete with attached fields.

You can do that like so:

$args = array(':type' => $current_node->type, ':created' => $current_node->created);
$sql = 'SELECT nid FROM {node} WHERE type = :type AND created < :created';
$nid = db_query_range($sql, 0, 1, $args)->fetchField();

$new_node = node_load($nid);

$title = $node->title;
$image_field_values = field_get_items('node', $new_node, 'field_image');

$first_image = array_shift($image_field_values);
$image_file = file_load($first_image['fid']);

$image_html = theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $image_file->uri,
  'alt' => 'Some alt text'
));

$body_values = field_get_items('node', $new_node, 'body');

// And so on


Drupal alter some javascript of contrib module? I am working on a project that implements the Drupalchat module.
Everything works perfectly, but the client requests some custom changes.

They want people to be unable to have private conversations with eachother, but they do need to be able to see eachother!

They can only chat in the public chatroom, that Drupalchat provides by default.

A moderator user (drupal user role) however can chat privately with other users.

Is there a clean way to "hook" into the drupalchat.js file and alter the behaviour for this?

I have found the portion of code that needs to be altered, but of course I don't want to hack the contrib module.

I tried IRC about this, but nobody seemed to have a clue how to implement this.

Anyone done something like this in the past?

Thanks in advance!

I believe this has already been answered here: How to override jQuery from contrib module

To override the JavaScript file added to a page from a module, you need to implement hook_js_alter()....


A better solution to make image field into div background? In Drupal 7, I want to turn my image field in Views to looks something like

so I can apply the JQuery Parallax scrolling effect. However, I'm not able to get the full "absolute path" of my image, even I use the "absolute path" on "output this field as a link" and "strip HTML tags" features. All I got is the file name, not the full absolute path.

Another issue I have is the "Global: Custom text" in fields, it does not has the text filter option, so I would not be able to write the above code.

So far, I only found the "BackgroundField" module for the replacement. Anyone know a better solution for div background image?

PS: the CSS trick only make it looks similar, they are totally differnt.

------ update info on Feb. 2 2015 : 12:58pm ---

The Views that I have is a list of node that contain Title and other fields. Therefore, each node should has their own background from image field.

------ update info on Feb. 2 2015 : 02:46pm ---

Looks like the "BackgroundField" module I mentioned above is similar to Background Images, which does not work too.

There is also the Background Images module suite:

  Background images is a collection of modules that allows users to add
  background images to html elements on pages of the site.

There is also a Field Group sub-module for background image support called Field Group Background Image:

  This module creates a field group display formatter that consists in a
   wrapper with a background.

  The background can be set from:

  An image field of the entity being displayed
  A color field (of Color Field or jQuery Colorpicker modules)

  This module can be used alongside
  Display Suite, and is particularly useful for creating custom
  Fieldable Panels Panes bundles.

You mention parallax scrolling ... I know what that is, I've never had to implement it -- you may want to try to use Parallex Background:

  This a simple module that allows to set a vertical Parallax effect on
  the background of any element on the DOM.

I kindly suggest you work more on your Google-fu skills.


Hide tabs on all pages On every page on my site, there are always these tabs on display:

  News, Events, Grant.

I have been able to hide them on specific pages using CSS Injector however I want to disable these tabs from appearing.

How can I do this?

I have added a screenshot for reference:

Are those tabs menu entries? Check the menus you have listed in structure > menus. I'm not sure what menu it would be in because it may depend on the theme so click through them all.

Those could also be potentially generated by a View so check entries in structure > views as well.


How do I delete all terms from a vocabulary (bulk delete)? I have a large vocabulary, and admin views does not yet work for taxonomy. Taxonomy Manager does not do this as well.
Are there other options for bulk-deleting taxonomy terms?

A favorite method of bulk-deleting content by content type, taxonomy vocabulary, etc utilizes the http://drupal.org/project/devel module. For deleting all terms in a vocabulary:

Enable the Devel and Devel Generate modules
Go to Development > Generate Terms
Select the Vocabulary from which you wish to delete terms
Enter "0" for number of Terms to generate
Check "Delete existing terms before generating new ones"
Click Submit

Voila-- empty vocabulary, otherwise untouched.


How to set properties for a specific chart only using the views integration of the Charts module? I'm creating charts using the charts module and its integration with the Views module.

I want to set options for only some charts and found that in charts.api.php:

/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

It seems perfect for what I want because it has the if ($chart_id === 'view_name__display_name') { line for specific views but I wonder if I directly add some settings code such as $chart['#title_font_size'] = 10; here (to charts.api.php) or is there any other way to do this?

I mean overriding the charts.api.php inside of the charts module is OK or do I have to write and run these codes anywhere else?

EDIT:

Based on rooby's comments, these are the two ways that I tried to set the properties for each charts (created with views module):

1. Custom Module

I created a custom module called benim.

This is the benim.info file:

name = Benim
description = Override charts properties.
package = Other
core = 7.x

And this is the benim.module file:

<?php

function benim_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__block_1') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 50;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'true',

    );

  }
}

function benim_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__block_1') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

2. Template.php

I added the lines below to the theme's template.php.

function mytheme_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__page') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 150;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'false',

    );

    $chart['yaxis'] = array(
    '#type' => 'chart_yaxis',
    '#allowDecimals' => 'false',

    );

  }
}

function mytheme_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__page') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

(above mytheme is the name of the actual theme)

Unfortunately, both two ways didn't work for me. I wondered if the $chart_id parameter is correct and checked for different views but the result didn't change.

Note: I also tried clearing caches, and trying inside another theme.

No, not in the charts module, in a custom module of your own.

It is also possible for you to use drupal alter hooks from your theme's template.php file however you should be careful what you put in your theme.
You should only put code relating to visuals in the theme, if you are doing more functional code it should go in a module.

A good rule of thumb is whether or not you would want to keep that functionality if you ever changed themes. If you would want to keep it then that is a possible indicator that it is functional, not visual, and should be in a module.

.api.php files are files that give developers information on the function and hooks that a module makes available to others.

It is basically just documentation so you editing it will do nothing (except for then making that documentation incorrect, which is bad if anyone else wants to use it).

Some reasons why it is generally not a good idea to modify the module itself can be found at Why don't we hack core? (it is talking about drupal core but the same goes for other contrib modules and themes).
One of the main reasons we have drupal hooks is so you don't have to modify the original module if you want to make changes.

So you would create a custom drupal module and then in that module implement the hook like this (changing MODULENAME to the name of the module and the chart ID to match the ID of your specific chart):

/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function MODULENAME_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

There are lots of other drupal module development resources besides drupal.org docs too. There are some good affordable textbooks and some paid training type websites, as well as a scattering of blog posts in random corners of the internet.

Here is a more functional example of using the definition alter hook.

/**
 * Alter an individual chart's raw library representation.
 *
 * This hook is called AFTER hook_chart_alter(), after Charts module has
 * converted the renderable into the chart definition that will be used by the
 * library. Note that the structure of $definition will differ based on the
 * charting library used. Switching charting libraries may cause your code
 * to break when using this hook.
 *
 * Even though this hook may be fragile, it may provide developers with access
 * to library-specific functionality.
 *
 * @param $definition
 *   The chart definition to be modified. The raw values are passed directly to
 *   the charting library.
 * @param $chart
 *   The chart renderable. This may be used for reference (or read to add
 *   support for new properties), but any changes to this variable will not
 *   have an effect on output.
 * @param $chart_id
 *   The chart ID, derived from the $chart['#chart_id'] property. Note that not
 *   all charts may have a $chart_id.
 */
function THEMENAME_chart_definition_alter(&$definition, $chart, $chart_id) {
  // For the portfolio charts.
  if ($chart_id == 'MY_CHART_ID') {
    $definition['legend']['borderRadius'] = 0;
    $definition['legend']['borderColor'] = NULL;
    $definition['legend']['style']['fontFamily'] = 'Helvetica,Arial,"Nimbus Sans L",sans-serif';
    $definition['legend']['backgroundColor'] = 'transparent';
    $definition['legend']['layout'] = 'vertical';
    $definition['legend']['verticalAlign'] = 'top';
    $definition['legend']['padding'] = 0;
    $definition['legend']['margin'] = 0;
    $definition['legend']['itemStyle']['color'] = '#555555';
    $definition['legend']['itemStyle']['fontSize'] = '12px';
  }
}


In a general sense, what is the purpose of the Drupal DB Semaphore Table I understand the purpose a semaphores in IPC programming but I'm not finding a good, or any, explanation as to the purpose of this table.

The semaphore table is used from the locking mechanism implemented by default from Drupal. It is not different from the usual mechanism of locking seen in programming: A value is used to verify an operation is already in progress, to avoid conflicts or race conditions. The difference is that, normally, the lock is a file, while Drupal uses the row in a database.

In fact, the locking mechanism has functions to acquire a lock (lock_acquire()), or wait a lock is released (lock_wait()). In both the cases, the semaphore database is used.

// lock_acquire()
// Optimistically try to acquire the lock, then retry once if it fails.
// The first time through the loop cannot be a retry.
$retry = FALSE;
// We always want to do this code at least once.
do {
  try {
    db_insert('semaphore')
      ->fields(array(
        'name' => $name,
        'value' => _lock_id(),
        'expire' => $expire,
      ))
      ->execute();
    // We track all acquired locks in the global variable.
    $locks[$name] = TRUE;
    // We never need to try again.
    $retry = FALSE;
  }
  catch (PDOException $e) {
    // Suppress the error. If this is our first pass through the loop,
    // then $retry is FALSE. In this case, the insert must have failed
    // meaning some other request acquired the lock but did not release it.
    // We decide whether to retry by checking lock_may_be_available()
    // Since this will break the lock in case it is expired.
    $retry = $retry ? FALSE : lock_may_be_available($name);
  }

  //lock_may_be_available()
  $lock = db_query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
  if (!$lock) {
    return TRUE;
  }
  $expire = (float) $lock['expire'];
  $now = microtime(TRUE);
  if ($now > $expire) {
    // We check two conditions to prevent a race condition where another
    // request acquired the lock and set a new expire time. We add a small
    // number to $expire to avoid errors with float to string conversion.
    return (bool) db_delete('semaphore')
      ->condition('name', $name)
      ->condition('value', $lock['value'])
      ->condition('expire', 0.0001 + $expire, '<=')
      ->execute();
  }
  return FALSE;

In Drupal, different users can requests the same page, which means different threads or processes could execute the same code at the same time. This could cause problems when the code is, for example, updating a database table. Using locks is a way to avoid this could cause problems.

The reason a database table is used is simply that Drupal requires a database engine to work; using a database table also for the locking mechanism is a way to reduce the requirements. The locking mechanism could be implemented using the APCu extension too, and if I recall correctly, there is a module doing that.


Using hook_form_alter() and hook_cron() together I am interested in adding a function to the cron queue after I submit a form. I am confused how to call the cron after the form submits.

I am using hook_form_alter for catching the submit:

function rating_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id)  {
        case 'comment_node_form':
            $form['#submit'][] = 'add_rating_queue_function';
            break;
     }
}

function add_rating_queue_function($form, &$form_state) {
    ....
}

my hook_cron_queue_info:

function add_rating_cron_queue_info(){
  $queues['update_rating'] = array(
    'worker callback' => 'add_rating_queue_function',
    'time' => 120,
  );
  return $queues;
}

I am a little confused on how to call hook_cron or hook_cron_queue_info to add my add_rating_queue_function to the cron.

Can I just call $form['#submit'][] = 'add_rating_cron_queue_info'; inside my hook_form_alter

You don't invoke hook_cron_queue_info(); you add an item to your cron queue, which is nothing else that a normal Drupal queue that is exposed to Drupal cron through hook_cron_queue_info().

What you should do in your add_rating_queue_function() is using code similar to the following one.

$queue = DrupalQueue::get('update_rating');
// Add a new item to the queue.
$queue->createItem($data);

$data is the data that is passed to the worker callback you define for the update_rating queue in add_rating_cron_queue_info().

As for running the Drupal cron tasks, you can simply call drupal_run_cron(). This is what system_run_cron_submit() does.

function system_run_cron_submit($form, &$form_state) {
  // Run cron manually from Cron form.
  if (drupal_cron_run()) {
    drupal_set_message(t('Cron run successfully.'));
  }
  else {
    drupal_set_message(t('Cron run failed.'), 'error');
  }

  drupal_goto('admin/config/system/cron');
}

system_run_cron_submit() is the submission callback for the "Run cron" button you find at admin/config/system/cron.

In your case, you simply need to call drupal_run_cron() without checking the error code.

As Jeremy French said, drupal_run_cron() should not be called too often, and in this way. In admin/config/system/cron, the function call is triggered by the user, but a module should not be calling drupal_run_cron(), especially because Drupal 7 includes the code from Poormanscron. This mean that cron tasks could be already executed during page requests; adding a further call to drupal_run_cron() could make the site slower. A better code could be the following one.

if (lock_acquire('cron', 2.0)) {
  $last_cron_execution = variable_get('cron_last', 0);
  lock_release('cron');

  // Check cron tasks were not already executed, or they were not executed few minutes ago.
  // Set $execute if they were executed far enough.

  if ($execute) {
    drupal_run_cron();
  }
}


Making contextual node paths and reference lists First off, I am about to set up a site presenting a catalog of products. Since it's quite possible that at some point we'd open a store, I decided to use Commerce Product Display right from the start to present the products, assuming that it will be much easier to migrate to a real shop when we're ready. (Is that assumption correct?)

Now, each product will be tagged using two independent taxonomies (ie. each Display Product will have 2 taxonomy fields). That's because each product has two contexts possible: how it's built and how it can be used. The context will depend on the path user takes at the front page or the link they paste into the browser.

The issue I'm facing is that for each product I want to generate a list of related products, depending on the context.

Two questions now:
1. Is it possible to display a given Product Display page with different contextual path/breadcrumbs?
2. In a Product Display page, what module would you use to present a list of related products: Node Reference or Views Field?

Whatever you may have experience in setting up similar sites, I would be more than curious to hear from you, to learn about the precautions and caveats.

You need the Views Module.  I have both of the other modules enabled, so I am not certain exactly what functionality they contain applies.  The module Views Field View allows the user to contain a view in a field of another view.  I do not think that is necessary for what you want to do.  If you are not familiar with views I recommend watching the "Taming the Beast" video series at Nodeone.se. It will give you a good idea on how you will want to proceed.


How to share content title, image and body on Instagram? I want to share content's title, image and body on Instagram of my Drupal website,

But I am not able to find the solution.

Any suggestions?

If you want to show Instagram feeds in your website (as in revision 2 of your question ...), then there are typically 3 modules to pick from (quotes are from their project pages):

Instagram Block:

  ... integrates with Instagram and creates a block containing your most recent instagram posts.

Instagram Feeds:

  This is a Feature module. It allows you to create Instagram feeds for your site that will download images from Instagram using filtering by hashtags and / or usernames.

Drupagram:

  In this early implementation the module will interact with the Instagr.am API and be able to fetch media items. Advanced methods like relationships between Instagr.am users and such will be added later on.

Note: posting to Instagram doesn't seem to be available, since that isn't allowed through their API (by design).


Hide taxonomy term from a view filter where the filter results are empty I have several nodes and several taxonomies, but only some nodes have taxonomy relationships.

My problem is that the taxonomy filter shows those terms too which don't have any node relationships at all, example:

So even if I don't have any nodes in "Category 1", the term will show up in the filter.
Is there a way to remove those taxonomy terms from the filter which have no content associated to them?

In Views, there is an option to specify a relationship and to require that relationship. You can find it in your View's config page, under Advanced. Just add a relationship to your taxonomy vocabulary and check the option to require the relationship.
The screen shot below is from the Content view that ships with Drupal 8, which is a great example of how to define a required relationship.


Using a PHP class defined in the module file inside the implementation of hook_install() If the implementation of hook_install() of my module needs to use a class defined in the module file, should the code first load the module file with drupal_load()?

I would think that when the hook is invoked, the Drupal registry has not been yet updated to contain any reference to the PHP classes defined in the modules used by my module, and which are referred in the .info file. I looked at Drupal code, but I could not find any proof for what I think Drupal does.

Should I use drupal_load() or the file will be loaded automatically when I try to create an instance of the PHP class defined in the module file? Is it different with hook_update_N()?

No need, it's already loaded. Check http://api.drupal.org/api/drupal/includes--module.inc/function/module_enable/7

if ($existing->status == 0) {
  // Load the module's code.
  drupal_load('module', $module);
  module_load_install($module);
  // …
}


Internal path in twig template I'm trying to link to a Drupal path like "Contact Us" in my Twig template.
I've tried this code in my Twig template but I can't get any result.

{{ 'Contact'|t }}

As well as this:

{{ 'Contact'|t }}
{{ 'Contact'|t }}

What is the correct way to link to an internal Drupal path in Twig?

The path() & url() Drupal Twig functions expect a route name and will not work with a Drupal path. For a relative/absolute path to /contact, you can use path()/url() respectively with the contact.site_page route:

{{ 'Contact'|t }}
{{ 'Contact'|t }}

If you don't know your route name, what you're looking for is link()

{{ link('Contact'|t, 'base:contact', { 'class':[] }) }}

See this d.o. page for more explanation about these 3 functions and their differences.


Best way to add a wrapper  to selected fields in a content type I have a content type called resources which has a bunch of fields including a screenshot image field. When I order the items the screenshot shows at the bottom (or at whatever weight I set it). But what I want is for the screenshot to appear to the RIGHT of the text in the other fields (basically like a float:right with css). But although I have the class of the item using Firebug and have styled it float:right accordingly it still doesn't go next to the other fields, it gets placed below them...to the right.

I think what I need to do is find a way to add a wrapper  to the other fields so I can float that  left and my screenshot field right...but I don't know how to add a wrapper  to fields in a content type.

Anyone know of a good way to do this?

Maybe the Field Group module is what you are looking for? According to the documentation, it provides many kind of wrappers.

Hope that helps,


Private folder issues with NGINX So I have been setting up my Drupal 8 installation and I'm having troubles with my private folder setup.

I went on to settings.php and specified the path which I wanted for my private folder as sites/default/files/private. It seemed to be working well for a while, but now it isn't.

I have configured Drupal to use the private folder as default location for file uploads and it shows the sites/default/files/privatepath as the private folder path.

Now my issue is that I created a custom content-type with a private folder file upload field. This is for a restricted area I have in the website which I only want authorized (logged in) users to be able to access - both that area, and the files linked there.

The area was successfully blocked via role permissions and works great. The files attached to content - even though the content-type settings are explicitly and correctly set to use the private folder for upload - result in the following behavior:

files served by direct HTTP in sites/default/filesare accessible, regardless of Drupal login state - as intended
files served by direct HTTP in sites/default/files/private are blocked with a 403 forbidden by NGINX regardless of Drupal login state - as intended
restricted files served by Drupal in the restricted area with an URI similar to system/files/YEAR-MONTH don't show Drupal's access denied 403 page (the intended effect), BUT INSTEAD:

if they are images, I get an NGINX 404 NOT FOUND error page
if they are other file-types, they are accessible without restriction (exactly what I'm trying to prevent).

Right now I'm lost as I've been searching around for answers on these issues, but I can't seem to find them.

I'm using a shared web server setup in which I don't have direct access to NGINX's .conf files. I'm also using the IMCE File Manager module. I think that the images issue is related to some NGINX conf and as such I'll have to contact the web server maintainer to fix it, but I'd like to have some insight to share with them about this. Also, what can possibly explain the files being uploaded to the private folder being accessible without any restriction?

Any help would be very welcome, thanks!

It has been a while since I created this question, and as such I might be missing quite a few details, but I eventually did find a solution.

  TL;DR It should probably relate to NGINX, so cover all the bases related to it. NGINX's official Drupal recipe helped me a lot,
  you might want to check that first. Although, if you're using Drupal 8, you'll need to update/change some settings for it. You might find some of them here.

Can't recall much about my specific case, but this checklist might be worth checking out in your setup:

settings.php be careful and mindful of the options you have setup in your settings file. IIRC, I think the private folder path value was all I changed regarding this issue.
Drupal configuration - in Drupal's admin backend, go to Configuration > Media > File System and make sure you have the correct option selected for your use case, either public/private. This will setup your default file upload location, but can be overridden in the content type's definition, if I'm not mistaken.
Content type definition - make sure that your content type using the file field is setup properly and also according to your needs. I think at some point I even re-created my content-types just to make sure there wasn't stale info in the DB.
Drupal role permissions -  this was probably one of my biggest headaches with this issue. Make sure they are properly setup and test them thoroughly. In this process I discovered the Masquerade module, which has helped me a lot ever since.
Folder permissions - The folders you want to use for both private and public uploads should be writable by Drupal/NGINX, but NGINX should not enable HTTP access to them.
NGINX -  this is definitely the most important part. What you basically need to absolutely make sure of is that Drupal handles it's own URLs, and everything else is handled by NGINX accordingly. This can get confusing really fast, so here are some more tips:

Drupal will have it's own file URL being generated internally and saved to the DB. This should make Drupal respond and take over HTTP requests to a system/files/YEAR-MONTH-type URL.
NGINX on the other hand, must let Drupal handle those requests, while intercepting and preventing direct access to sites/default/files/private, or whatever folder you have setup for private files.
This should be fixed by setting up the correct NGINX directive regarding the path you want/need it to handle. This might help. Also, go read about Perusio's NGINX setup, as there are a lot of valuable nuggets of information there (D8's setup is equivalent to D7).
I think some specific NGINX directives may target certain file-types differently (maybe something related to MIME types, not sure). This could explain if your issue happens with, ie, JPG, but not PDF or vice-versa. Couldn't find info on this, though.

@GokulNK I'm sorry if this isn't enough help, but I really can't recall what I did to fix it. Hopefully it'll point you in the right direction, though.

EDIT: I found an old email with the webserver's maintainer discussing some NGINX directives that has some info that might be relevant:

# handled by NGINX
location ~ ^/sites/default/files/private/ {
    return 403;
}

# Handle private files through Drupal.
location ~ ^/system/files/ { # For Drupal >= 7
    try_files $uri /index.php?$query_string;
}


What is wrong with this code? I am having a slight problem with my code; I am trying to do a if statement to make the date not print if a node is using a certain term. I have parsed $node to narrow down what term I would like to exclude the date from being used.

This is what is returned in the dump:

Array ([und] => Array ([0] => Array ([tid] => 103 )))

This is what I have for my code to have the date being displayed:

      if (arg(0) == 'node' && is_numeric(arg(1))) {
        $node = node_load(arg(1));
        $user = user_load(array('uid' => $node->uid));
        foreach ($node->field_newsections['und']['0'] as $node_time);
      }

      hide($content['comments']);
      hide($content['links']);
      $nodecontent = render($content);
      $newcontent = preg_replace("/
]*?>/", "", $nodecontent);
      $newcontent = str_replace("
", "

", $newcontent);

      if ($node->type == 'post' || 'news') {
        echo '
'. date('l, F j, Y g:ia', $node->created). '
';
      }
      else ($node_time == '108') {
        echo 'working';
      }

      print render($newcontent);

I am probably over looking something small.

There are three things that needs to be corrected, in your code.

You are using a foreach statement without any block; this means that that control statement is not doing anything.

foreach ($node->field_newsections['und']['0'] as $node_time);

You are using an else statement followed by a condition; or you use an else statement without condition, or you really meant to use the elseif statement.

else ($node_time == '108') {
  //...
}

You are using render() with $newcontent, which is set with a previous call to render().

$nodecontent = render($content);
$newcontent = preg_replace("/
]*?>/", "", $nodecontent);
$newcontent = str_replace("
", "

", $newcontent);

While render(), which returns a string, checks when the parameter it gets is a string, instead of an array, and it returns that parameter immediately, it is useless to call render() with the result of a previous call to render(), even if that string has been modified from any function to alter a string.

Also, as you said (in a comment for this answer) that you are using that code inside the "node.tpl.php" template file, that template file has already access to the $nodevariable that contains the node object for the node being shown. As the template file is only used for nodes, the following code is useless:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  $user = user_load(array('uid' => $node->uid));
  // …
}

It is also unusual for a theme replacing the HTML content; that is normally done in a module.

Supposing that you are trying to use the last item in the $node->field_newsections['und']['0'] array (which seems a term array), I would rather use the following code:

$tid = array_pop($node->field_newsections['und']);
$node_time = $tid['tid'];

hide($content['comments']);
hide($content['links']);
$nodecontent = render($content);
$newcontent = preg_replace("/
]*?>/", "", $nodecontent);
$newcontent = str_replace("
", "

", $newcontent);

if ($node_time != '103') {
  print '
'. date('l, F j, Y g:ia', $node->created). '
';
}

print $newcontent;


Fail to install drush via pear I try to install drush using the following command:

pear install drush/drush

I get this error message:

  No releases available for package "pear.drush.org/drush" install failed.

Then I try with sudo:

sudo install drush/drush

I get this error message:

  downloading drush-5.4.0.tgz …
  Starting to download drush-5.4.0.tgz (398,652 bytes) done: 398,652 bytes
  Could not rename /usr/bin/.tmpdrush to /usr/bin/drush copy(/usr/bin/drush): failed to open stream: No such file or directory
  ERROR: commit failed.

I installed pear, and added the pear.drush.org channel. What is wrong?

I realize that my question was not very clear. I was trying  to install drush using pear on OSX Mountain Lion and I got those errors. Anyway I managed to accomplish my task another way, by installing "homebrew" package manager and following a few steps from this tutorial (step 8 and 9).

Update: an even simpler way to install drush using homebrew:

brew install drush

That's it.

Use the following commands:

sudo rm /usr/bin/drush
sudo pear install drush/drush
sudo drush --version


CTools modal return incorrectly return html instead of ajax commands I am trying to create custom login form using Ctools modal window. There seems to be a problem upon submitting the correct username and password.

The page callback function is supposed to return a JSON of the ajax commands. Right now it is instead returning an AJAX error, with the response as the HTML text of the user profile page (eg. user/123). The return code is 200. Which seems to suggest that the function got redirected to the user page, which shouldn't happen for AJAX call. I might be wrong on this though.

I have used the same pattern for other forms, such as register form and reset password, which work fine. Anybody has any idea why this is happening? Thank you all.

Here are my codes:

hook_menu:

$items['modal/user_login/%ctools_js'] = array(
    'file'=> 'popup_login.inc',
    'page callback' => 'my_module_user_login',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);
$items['test_ctool_popup'] = array(
    'title' => "Test Login Popup Page",
    'page callback' => 'my_module_test_login_page',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
);

page callback function: my_module_test_login_page

function my_module_test_login_page () {
    ctools_include('ajax');
    ctools_include('modal');
    ctools_modal_add_js();
    ctools_add_js('ajax-responder');
    if(!user_is_logged_in()){
        $link = ctools_modal_text_button(
            'Log in modal',
            'modal/user_login/nojs',
            'Log in');
    } else {
        $link = 'user already logged in';
    }

    return << TRUE,
    //'title' => t('Log In')
);
$output = ctools_modal_form_wrapper('my_module_user_login_form',$form_state);
if (!empty($form_state['ajax_commands'])) {
    ctools_add_js('ajax-responder');
    $output = $form_state['ajax_commands'];
}
print ajax_render($output);
}

form function my_module_user_login_form

function my_module_user_login_form ($form, &$form_state) {
    $login_form = user_login($form, $form_state);
    $login_form['name']['#title'] = t('Email');
    $login_form['name']['#size'] = 25;
    $login_form['pass']['#size'] = 25;
    //$login_form['#validate'][] = '_ewp_property_user_login_form_validate';
    return $login_form;
}

submit function my_module_user_login_form_submit

function my_module_user_login_form_submit ($form, &$form_state) {
    user_login_submit ($form, $form_state);
    unset($form_state['redirect']);
    $commands = array();
    $commands[] = ctools_modal_command_dismiss(t('Log In Successful.'));
    $commands[] = ctools_ajax_command_reload();
    //$commands[] = ctools_ajax_command_redirect('modal/dismiss_modal/nojs');
    $form_state['ajax_commands'] = $commands;
}

Turns out the offending part is not the logic, but the function name. The my_module_user_login_form function happens to be a invoke hook form, which interferes with the modal.

Changing the function name solved the problems.


Organic Groups Support for Context Module I would like to achieve following functionality.

In Context Conditions check Group Type such as Pubic, Private, Moderate
Check User is member of a Group or Not !

Is it possible using any module ?? I verified Context OG module but it's not giving options that i am looking for !

Any solutions to override the context and check for above conditions ?

Have you read this article? http://drupalconnect.com/blog/creating-drupal-context-plugins

I think it can help you to build you own module to use with context.

Oskar


hook_node_view() is not working I am building a module for Drupal 8 which needs to use hook_node_view(). I tried the following code

<?php

/**
 * @file
 * Demonstrates the possibilities of forms in Drupal 8.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Node;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_form_alter()
 */
function demo_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  drupal_set_message(t('Found a form with ID %form_id', array('%form_id' => $form_id)));
}

/**
 * Implements hook_node_view()
 */
function demo_form_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
   drupal_set_message(t('its working'));
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Only alters the Search form 'search_block_form'.
 */
function demo_form_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['hello'] = array(
    '#markup' => t('Go ahead, try me ...') . '<br />',
    '#weight' => -1,
  );
}

I can't see any message from demo_form_node_view(). If the hook was correct, it should have shown the message. I am new to Drupal and I can't figure out why it is not working.

In Drupal 8, the core Drupal hook hook_entity_view() is only called when the entity is "being assembled before rendering". See the documentation at https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook_entity_view

After the entity has been rendered, core Drupal will cache the rendered entity and serve the rendered entity from the cache when needed. The entity is not rendered every time it is used. So BY DESIGN hook_entity_view() will not be called again when the rendered entity is loaded from the cache, it will only be called when the entity needs to be re-rendered - that is, when the entity is changed and/or the cache of that entity is invalidated.

This behavior is different from the way it worked in Drupal 7 because Drupal 7 did not cache rendered entities like this.


How do I test that a text field in $form_state has been populated by the user? At the moment I am using the following code.

if (!empty($form_state['values']['my-field']) {
  // ...
}

If the user has entered 0 (a valid input in my case) my test will return FALSE. My guess is that I need to test for an empty string '', but I'm not sure.

This depends on the field in question and what values could possibly be entered into it.

In most cases an empty string would mean that the field has had no value set.
If zero is a valid value then check like this:

if ($form_state['values']['my-field'] !== '')

That will check that the value is an empty string, whereas != '' would also match zero and false etc.

Also, depending on your set-up and requirements, if the field has a default value you have to decide what happens in the case the the value in form state equals the default value, because in that case you don't know if the user has left the field default on purpose or not.


Get list of nodes by field-collection value I am having field_feature as a collection of fields (field-collection) in a content type called 'watches'. Those fields are,

field_water_resistance -> water_resistance(Term Reference)
field_gender -> gender(Term Reference)
field_function -> function(Term Reference)
field_sub_function -> sub_function(Term Reference)

And so on.

I have my query like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'watches','=')
    ->propertyCondition('status', 1);
$query->range($offset, 15);
$query->addTag('joinentity');
$query->addTag('fieldcollection');
$query->addMetaData('termscollection', $filterparams); // $filterparams is array of tids

Now I want to add above field collections in the query with the parameters (array of tids). How can we do that?

I know the EntityFieldQuery with the entity_type as field_collection_item but I don't know the same for entity_type as node.

How can we do that?

I think you have to possibilities to solve this:

Looks like you already got a tag for joining the field_group entities here:

$query->addTag('joinentity');

You could then implement hook_query_joinentity_alter() to implement the join, see also EntityFieldQuery INNER JOIN

You use db_select() or db_query() and add your joins there rather than an EFQ. I think this is preferable as implementing tags and hooks for those gets a bit messy IMO.


How to access form elements in table via getValue()? I'm trying to do so using array indices. Say, we have

$form['mytable'] = array(
'#type' => 'table',
'#header' => array(t('a'), t('b')));

$form['mytable'][1]['a'] = array(
'#type' => 'textfield',
'#required' => true));

$form['mytable'][1]['b'] = array(
'#type' => 'textfield',
'#required' => true));

What am I doing: $form_state->getValue('mytable[1][b]');, and it's not working. And how to pass such a field to setErrorByName?

You can access $form_state values like below

$values = $form_state->getValues();

If you are printing $values then you will get

Array
(
    [mytable] => Array
        (
            [1] => Array
                (
                    [a] => Value of a
                    [b] => Value of b
                )

        )
)

setErrorByName() function can be used while validating the elements.


Views filterable by current logged in user that equals Entity Reference field? I have nodes that have a user assigned to them as a responsible party via Entity Reference.  I would like to have a View display all the nodes that the current logged in user has they that they are the responsible party of.

Would a filter that looks something like this Content: Responsible Party (Current User) be do able?

I have gotten this far using the Entity Reference Filter for Views, but it doesn't give me a "Current User" option.

Add your entity reference field as Contextual filter in your View advanced settings and then in the section "when the filter value is not in the url" set the "Provide the default value" to "User ID from logged in user".


How do I export Entityform submissions to CSV? I see that it is possible to bulk download Entityform submissions to a CSV file.

How do I do it? I don't see a "Download as CSV" button anywhere.

My problem was that I installed Views Data Export after installing Entityforms.

I had to go to the Entityforms view (which is the automatically generated admin view showing the form's submissions), click the arrow next to "Edit View Name/Description" and click "Revert View".

Now a CSV/XML export button shows up on the Submissions view, and I can export happily.


How can I let authenticated users rebuild caches? Is there a way for authenticated users to clear the cache without giving them the administer site permission?

Yes, that's what I created Rebuild Cache Access for.

  This module provides a new permission: rebuild cache access. Every
  role with this permission set will have a nice and big "Rebuild Cache"
  admin toolbar button. Clicking this button simply fires
  drupal_flush_all_caches(). That's all.


cant see the list of databases in Feeds Database module UI tab I have installed the feeds module and Feeds Database module so i can migrate contents inside my non drupal datase to a drupal 7 one. But i cant see the list of databases in the Feeds Database tab. Anyone can help?

Here's a code of my database in settings.php

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'karljay',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),

  ),
   'test' =>
  array (
    'test' =>
    array (
      'database' => 'joan',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),

  ),
);

this seems to be the right code cause i can see the test database now in the database's list in drupal but i have a database error when i import something using feeds.
and here's my error

and to add more details here's my query

$q=msyql_query("SELECT subject from forumthreads");
$result=mysql_fetch_array($q);

and here's my mapping

i only have one field cause this is a test if i can really use feeds to migrate many data from other database

The documentation for this module is poor, but the solution is simple.

The module picks up the $databases array defined in your settings.php file. In most installations, only one database 'default' is defined. Use the format for 'default' and define a second database say 'test', listing the correct connection credentials. The 'test' database will show up in the drop down. The module removes 'default' from the list because it makes no sense to map a database to itself.

I think better documentation for Feeds Database is in order :). However, the core Database API can be configured for multiple databases. See Database Configuration.


What is the best way to generate node(book) to ePub? I want to create a Journal site that can generate book(node) to ePub, like Open Journal Systems(OJS). So what is the best way to generate node to ePub? I have tried Printer, but it only show the following error messages on iBook. File generated by PHPePub(Printer) can open by Calibre, but all images are missing.

  This page contains the following errors:

  error on line 47 at column 27: AttValue: " or ' expected
  Below is a rendering of the page up to the first error.

I know this answer is dead simple, but have you tried EPUB Export module?

  This project builds content objects from drupal and bundles them into an
  EPUB 3.0 document. Currently it will export a rendered entity seperate of all
  of the page markup and gather all the referenced resources within the content
  and bundle those into one EPUB document.

I tested it on a clean install and it appears to work as advertised.


Split Delivery : Drupal Commerce future : 2 qty in differnt Address : Single Order in Multiple Address I want to create split delivery functionality in Drupal 7. I want to split qty in differnt delivery address.ex
Like Product A have 2 qty .I want to deliver 1 qty to my friend house and 1 to  my Address.Please give some suggestion?

There is no module offering split shipping like this out of the box. The Commerce Shipment module does support making multiple shipments out of the products on an order, but it requires custom code to tell it on what basis the order ought to be split. To date, this has only included support for line item based splits for pre-orders, so you'd need to develop a user interface for selecting products / entering their addresses and the ability to split up individual line items based on quantity.


Why do breadcrumbs just show "Home"? Do breadcrumbs show by default in Drupal 8? I have created nodes, added them to the menu, and made some parent child relationships in the main menu. The breadcrumb in Bartik only shows 'Home'. Is there a trick or config to flag to get the breadcrumbs to show?

Looks like 'path' is required.. maybe it's always been like this and I just didn't realize. Installing Pathauto (from GitHub) and Token (from Drupal.org) corrects the issue.


How to automatically load block--[blockname].tpl.php to region--[regionname].tpl.php I have multiple customized blocks with different content (eg. Advertisements, Quotes, Youtube videos, etc..)

block--apple.tpl.php
block--pineapple.tpl.php
block--orange.tpl.php

Question: How can I automatically assign these blocks from different regions for example:

block--apple to sidebar_first region
block--pineapple to sidebar_right region
block--orange to region--myCustomRegion

Is there a theme function that automatically fills my target REGIONs with these BLOCKs without using the dashboard. I just want all blocks is ready when my theme is installed.
Thank you very much in advance.

There is no theming function to do this, and there cannot be, because assigning block to regions is more logic than theming matter. So you should do it at module level.

When you are implementing hook_block_info(), you can specify default region, like this:

$blocks['example_empty'] = array(
  'info' => t('Example: empty block'),
  'status' => TRUE,
  'region' => 'sidebar_first',
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => 'node/*',
);

You can also use hook_block_info_alter() to provide default regions for blocks not defined in your module.

See Examples for developers, block example for more details and samples.


Programatically altering a field formatter in Views I'd like to create a new (date) field formatter in Views, but also keep the existing formatters intact. As of now, I've managed to use hook_field_views_data_alter() to entirely replace the exiting handler with mine. However I would prefer to have my custom formatter available in the dropdown below. Is it possible to append an option to this dropdown for my custom formatter?

If you wish to display a field in a different way, there are a different ways to go about it.

Create a field template in your theme and change there. Just copying the field.tpl.php file would work changing the way the field is rendered on a node page. Note that field.tpl.php is a generic template which would be called on each field. You might want to try the specific template names like : field--article.tpl.php would get applied to all fields on article content type; field--body.tpl.php would get applied to body field on any content type; and field--body--article.tpl.php would only get applied to body field on the article content type.
Overriding the theme_field() function. E.g. Implementing the following functions in your theme's template.php file would do the same as with template copying THEMENAME_field__body__article(), THEMENAME_field__article(), THEMENAME_field__body(),
THEMENAME_field().
If the field is rendered in a view you could override it with the view template. To find out the specific template which you would need to override, click on "Theme: information" under the "Advanced" settings in the view to find the field template that applies to your field.
By creating your own custom field formatter by using this blog post. This will display the formatter in the dropdown as you intend.
There is also a module which helps your create custom formatters, which are ctools exportable. Which means you could easily featurize them. More about the module:

  The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.


I want to build multidimensional array at Twig I want to build multidimensional  array at Twig.

In php

 $attributes['attributes']['class'] = array();
 $attributes['attributes']['class'][] = 'innerTab';
 $attributes['html'] = TRUE;

Same thing I want to build in Twig.
I tried but not getting proper one . Please check my code below
          {% set ctn = 0 %}
         {% for key, value in menu.menu %}
{% set attributes = {'attributes':'class'} %}
{% set attributes = attributes|merge( [ { (ctn) :'innerTab'} ,  {'html' : true} ]  ) %}
{% set ctn = ctn+1  %}
 {% endfor %}

As a result I get :

  array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [0]=>
  string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } }
  array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [1]=>
  string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } }
  array(3) { ["attributes"]=> string(5) "class" [0]=> array(1) { [2]=>
  string(8) "innerTab" } [1]=> array(1) { ["html"]=> bool(true) } }

In Drupal 8 use an Attribute object instead of a multidimensional array:

D7 PHP:

$attributes['attributes']['class'] = array();
$attributes['attributes']['class'][] = 'innerTab';

D8 Twig:

{% set attributes = create_attribute() %}
{% set attributes = attributes.addClass('innerTab') %}

You can use the Attribute object in Twig link():

{{ link(title, support_url, attributes) }}


Views block template print individual field from content I created a view of paragraphs and I passed the parent ID as the contextual filter using a relationship to the content that use the field that reference the paragraph.

I can see the data been display and now I want to theme the output that I want to display on a block. I created a custom template file for the view block:

  block--views-block--MY-VIEW-NAME-block-1.html.twig

and it is working. I can see the content of the view by adding:

{% block content %}
{{ content }}
{% endblock %}

But I would like to access the fields value individually. I have try the followings without luck:

content.field_name
content.field_name[0]
content.field_name[0].value

What am I missing?

I finally found the answer to this issue. Here it is in case some one is having the same issue.

The solution is insanely simple use the views fields template.

In my case I created a new template:

views-view-fields--VIEW-NAME.html.twig

And now you can access your fields values like this:

{{ fields.field_NAME.content }}

More details here

Enjoy.


How to clear or rebuild a cached block for a specific user? I have a block with the cache setting DRUPAL_CACHE_PER_USER.

I want to clear the cache when a user performs a specific action. I want to clear the cached block only for the acting user, keeping the block cache for all other users.

How can I do that in Drupal 7?

This data is stored in the block_cache bin under the cid format:

<MODULE_MACHINE_NAME>:<BLOCK_MACHINE_NAME>:<THEME_MACHINE_NAME>:u.<UID>

Knowing that, you can build some wrapper function for cache_clear_all() that will delete any arbitrary UID's cached block:

function clear_user_block_cache($uid, $module = 'MYMODULE', $block = 'MYBLOCK', $theme = 'MYTHEME') {
  cache_clear_all("$module:$block:$theme:u.$uid");
}

You can invoke this function call whenever the user takes the relevant action.


How to set custom access for a custom page? For example, there is a page on the site, created before.

I need to set custom permission for it.

Par example, if a user doesn't have a photo in his profile, he shouldn't have access to page "/forum".

On Drupal 7 it was possible via hook_menu_alter and set access control there.

Could you clarify me, how can I it on Drupal 8 ?

Here's an example which prevents anonymous users from resetting their password.

services.yml:

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\MymoduleRouteSubscriber
    tags:
      - { name: event_subscriber }

src/Routing/MymoduleRouteSubscriber.php:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class MymoduleRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('user.pass')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Access\ResetPasswordAccessCheck::access');
    }
  }

}

src/Access/ResetPasswordAccessCheck.php:

<?php
namespace Drupal\mymodule\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

class ResetPasswordAccessCheck {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {

    return $account->isAnonymous() ? AccessResult::forbidden() : AccessResult::allowed();

  }

}

I've updated the documentation to clarify what return value is expected: https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

Forum access example

You only need the route subscriber in services.yml:

services:
  yrv_page_access.forum_route_subscriber:
    class: Drupal\yrv_page_access\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

RouteSubscriber:

<?php

namespace Drupal\yrv_page_access\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection){
    if ($route = $collection->get('forum.index')){
      $route->setRequirement('_custom_access', '\Drupal\yrv_page_access\Access\ForumAccessCheck::access');
    }
  }
}

Access check:

<?php

namespace Drupal\yrv_page_access\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

/*
 * Custom access to the forum page
 */
class ForumAccessCheck {

  public function access(AccountInterface $account){
    return AccessResult::forbidden();
  }
}


Recoverable fatal error after form submission in drupal7 Iam new to drupal.I have created a custom module named firstmodule .I have created a form using the tutorials section of drupal 7
when is submit i want to store this details in the registration which is present in db.

firstmodule.module

function firstmodule_form1_submit($form, &$form_state)

{

$firstname = $form_state['values']['name'];
    $username = $form_state['values']['username'];
    $password = $form_state['values']['password'];
    $year_of_birth = $form_state['values']['year_of_birth'];
    $email = $form_state['values']['email'];
    $file = $form_state['values']['file'];

I am using the insert query in the following way:

        db_insert('registration')->fields(array(
          'firstname' => $firstname,
          'username' => $username,
          'password' => $password,
          'yearofbirth' =>$year_of_birth,
          'email' => $email,
          'file' => $file,))
          ->execute();
}

it is showing me the error

  Recoverable fatal error: Object of class stdClass could not be
  converted to string in DatabaseStatementBase->execute() (line 2168 of
  /var/www/drupal-7.22/includes/database/database.inc).

please help with it

Here is an example of a file upload with some validation, hope it helps

function file_upload_form_validate($form, &$form_state) {

  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('txt csv'),
    'file_validate_size' => array(10000000),
  ));
  // If the file passed validation:
  if ($file) {
    // Move the file, into the Drupal file system
    if ($file = file_move($file, 'public://')) {
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', 'there was an error uploading the file');
    }
  }
  else {
    form_set_error('file', 'No file uploaded');
  }
}

function file_upload_form_submit($form, &$form_state) {
  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  $file->status = FILE_STATUS_PERMANENT;
  // Save file status.
  file_save($file);
  // here you can save your data
  $firstname = $form_state['values']['name'];
  $username = $form_state['values']['username'];
  $password = $form_state['values']['password'];
  $year_of_birth = $form_state['values']['year_of_birth'];
  $email = $form_state['values']['email'];

  db_insert('registration')->fields(array(
    'firstname' => $firstname,
    'username' => $username,
    'password' => $password,
    'yearofbirth' =>$year_of_birth,
    'email' => $email,
    'file' => $file->uri,))
  ->execute();

}


My website suddenly started giving Error 200 on anything AJAX related! The other day my website suddenly started acting weird. When using the Flag module to flag content, i get a 200 error! The content does get flagged once i refresh the page, but when clicking the flag link i get this error below.

When editing any of my Views, and say i click on the THEME INFORMATION link to modify the theme files i get another 200 error (see image).

When trying to open modal forms, same thing. This problem seems to have come out of nowhere overnight, as my site was ok, i went to sleep, next day problems. Now, i get the error on both my own theme (when say flagging content) and also on the Admin theme (Seven) when say editing a View. So i would guess that its related to a module rather than the theme? Anyone have any idea how i can go about figuring out whats causing this? My JS is not good at all so im beat here, been on this for a few days now :(

Any help would be much much appreciated.

When flagging a content:

When editing a View:

You've made a change somewhere that is adding <?php to the beginning of all responses.

In "When editing a View" above, you can see this <?php at the beginning of the response text.  Everything after the <?php is valid JSON and so likely the valid response.

I looked at your home page at http://www.spiritmolecule.com and it also has <?php added to the beginning of the HTML source.  This causes the <STYLE> tag to be ignored. <?php<STYLE TYPE="text/css"> gets interpreted as a single unrecognizable tag and so the CSS statement afterwards is displayed as text on the browser.

HTTP=200 normally means OK (no errors) which makes sense since it was able to respond, just it has the junk <?php in front.  Of course, in a file processed by PHP, <?php means the file is about to start some PHP code instead of HTML/JSON markup.  Did <?php get added to a file NOT processed by PHP (and so <?php is passed thru as response text)?

Only you can know what you did to get <?php added to the beginning of all responses, HTML or JSON.  Do you recall any other files that you changed before going to sleep?  Since the <?php gets added to many (or all?) responses, it is likely in a common file.

Good luck troubleshooting!


Using FBOauth, only allow existing users to associate a Facebook account How might I configure a login scheme where by

if someone already has an account on the site they may associate a FB account and login with it
But yet, deny login to any FB account that is not already associated with an existing account

Is something like this approachable?

In other words, I don't want random FB accounts to log into a Drupal instance but yet, want to allow existing users to associate a FB account with their Drupal login.

It turns out the FBOauth modules checks for the ability to create new accounts. Since we've limited our system only to User 1 and LDAP, no new FB accounts appear to be created. This leaves the user only to log in with an LDAP/AD account and then associate FB and their Drupal account. That is the exact behaviour for our use case!


webform email field autocomplete I can quite easily add ajax autocomplete properties to a regular textfield using the code below, but it doesn't work when I change the field to type webform_email. Is it possible to do?

function flower_order_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_68911') {
        //Add autocomplete fields for manager username
        $form['submitted']['name_of_authorising_manager']['#autocomplete_path'] = 'user/autocomplete';
    }
}

Here's the dpr output for the relevant field in the form:

Array
(
    [#type] =&gt; webform_email
    [#title] =&gt; Name of authorising manager:
    [#title_display] =&gt; inline
    [#default_value] =&gt;
    [#required] =&gt; 1
    [#weight] =&gt; 4
    [#description] =&gt;
    [#attributes] =&gt; Array
        (
            [class] =&gt; Array
                (
                    [0] =&gt; email
                )

        )

    [#element_validate] =&gt; Array
        (
            [0] =&gt; _webform_validate_email
        )

    [#theme_wrappers] =&gt; Array
        (
            [0] =&gt; webform_element
        )

    [#translatable] =&gt; Array
        (
            [0] =&gt; title
            [1] =&gt; description
        )

    [#webform_component] =&gt; Array
        (
            [nid] =&gt; 68911
            [cid] =&gt; 18
            [pid] =&gt; 0
            [form_key] =&gt; name_of_authorising_manager
            [name] =&gt; Name of authorising manager:
            [type] =&gt; email
            [value] =&gt;
            [extra] =&gt; Array
                (
                    [title_display] =&gt; inline
                    [private] =&gt; 0
                    [disabled] =&gt; 0
                    [unique] =&gt; 0
                    [width] =&gt;
                    [description] =&gt;
                    [attributes] =&gt; Array
                        (
                        )

                    [conditional_component] =&gt;
                    [conditional_operator] =&gt; =
                    [conditional_values] =&gt;
                )

            [mandatory] =&gt; 1
            [weight] =&gt; 4
            [page_num] =&gt; 1
        )

    [#webform_private] =&gt; 0
    [#validated] =&gt; 1
    [#webform_validated] =&gt;
)

You can only use type of fields which are defined in hook_element_info.

List all the type of elements using drush by:

drush ev "print_r(array_keys(module_invoke_all('element_info')));"

If you don't need to use Webform email, check the Email field module how it's implementing such element type. See: Usage of email field with the form API.


Accessible Checkboxes Using Drupal's Form API Im trying to get a set of checkboxes produced via Drupal's form api to pass the WCAG AA accessibility standards, the problem i am facing is with regard to labels and for attributes.

For example i am returning the following form definition via a hook_block_view(), i cant use drupal_get_form as normal as i dont want a form element wrapping the output which means i lose some of the processing that drupal_get_form does which is why i have to add in form_process_checkboxes and am missing some other functionality that gives the individual checkboxes their ID's(which is then used as the for attribute)

$form['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  '#title' => t('What standardized tests did you take?'),
   '#attributes' => array(
     'name' => 'example-checkboxes[]'
   )
);

$form['tests_taken'] = form_process_checkboxes($form['tests_taken']);

dsm($form);

return $form;

This produces the following markup.

    <input name="example-checkboxes[]" type="checkbox" value="SAT" class="form-checkbox">
SAT

    <input name="example-checkboxes[]" type="checkbox" value="ACT" class="form-checkbox">
ACT

I need the markup to either have labels with 'for' attributes pointing to the input elements or wrap the input elements with the label tag.

Heres thebest ive managed to come up with so far which doenst seem very satisfying

$form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#attributes' => array(
      'name' => 'example-checkboxes[]'
    )
  );

  $form['tests_taken'] = form_process_checkboxes($form['tests_taken']);

  foreach (element_children($form['tests_taken']) as $key) {
       $form['tests_taken'][$key]['#id'] = drupal_html_id('edit-' . $form['tests_taken'][$key]['#attributes']['name'] . '_' . $key);

  }

  dsm($form);
  return $form;

Which now produces this markup

<input name="example-checkboxes[]" type="checkbox" id="edit-example-checkboxes-sat" value="SAT" class="form-checkbox">
SAT

<input name="example-checkboxes[]" type="checkbox" id="edit-example-checkboxes-act" value="ACT" class="form-checkbox">
ACT

Anyone know of a cleaner way of doing this?

Try changing your code to the following, no need for the call to form_process_checkboxes.

function my_module_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'myform':
    $block['content'] = drupal_get_form('mymodule_form');
    break;
  }
  return $block;
}

function mymodule_form() {

  $form = array();
  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#attributes' => array(
      'name' => 'example-checkboxes[]'
    )
  );

  dsm($form);

  return $form;

}


Extract hex colors from image field for taxonomy vocabulary For a project in D7. I need to extract all the colors from an image field. I am looking for a module or solution to save the colors (ie Taxonomy term). So I can search on them.

I have found a solution for D6: https://drupal.org/project/visual_search

Is there an alternative for D7?

If your happy to use a custom module then something a simple as this would do the trick:

$colours = db_query("SELECT field_my_colour_field_value FROM field_data_field_my_colour_field")->fetchCol();


Find the total dollar amount spent by shopper in Ubercart, using Views? I'd like to run a report that will show info about each shopper, as well as the total dollar amount they have spent on my site. I know that the "Customer Orders" page (for instance, mysite.com/admin/store/customers/orders/1 for user #1) shows the total amount spent by an individual customer... how can I access that total amount in Views so I can build a custom report?

Thanks!

Ugh, I found that Ubercart does have this already built-in, at this URL: admin/store/customers/view. Oh well, better late than never!


Imagecache: configure image canvas I'm using Drupal 7 and I'm trying to create an image style, which resizes and crops an image and adds another image as the background. The latter image is the canvas for this image style. I am using the Imagecache module and so far I tried either adding the canvas image as "Underlay (background)" or as "Overlay (watermark)", but with either of these selections the problem is that the background image and the front image are positioned at x:0, y:0, and the result is not what I want, meaning both image are on top of the other.

Is there a way to define an offset for the image I want to be inside the canvas image? Otherwise, is there another way of doing this?

Please let me know if I didn't express my question clearly.

Thank you!

I assume you are using imagecache_actions module. I enabled imagecache_canvasactions module too that comes with imagecache_actions module.

Once i enable above mentioned modules, i can able to see offset for X & Y while adding Underlay (Background Effect) . See screenshot below. I set offsets to 50 & 40 see the style in action in second image.


How to debug and fix error [fcgid:warn] (OS 109)The pipe has been ended , get overlap result error, [core:error] End of script output before headers I’m using :

Drupal 8 on Acquia DevDesktop version 2 with php 7.0.15.
php_mode is set to FAST CGI (mod_fcgid).
Info from the phpinfo() Apache/2.4.18 (Win32) OpenSSL/1.0.2j mod_fcgid/2.3.9

The problem is I’m getting 500 internal errors very frequently.

In the apache log this is displayed for each 500 error log as follows

[Thu Nov 09 09:24:36.140248 2017] [fcgid:warn] [pid 17112:tid 1268] (OS 109)The pipe has been ended.  : [client 127.0.0.1:56192] mod_fcgid: get overlap result error, referer: http://inzicht5.dd:8083/

[Thu Nov 09 09:24:36.140750 2017] [core:error] [pid 17112:tid 1268] [client 127.0.0.1:56192] End of script output before headers: index.php, referer: http://inzicht5.dd:8083/

Therefore I added into php.ini

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

And I added in php.ini

error_log = C:\php_errors.log

Activated error.log in php.ini. Checked by  phpinfo(). But still no php error is shown up. Yes, I restarted the server

I already installed MS distribution C++ 2015 version 14.024215

But still I do not get more information. Also I googled a lot of sites for this error but none of them are giving me directions.

How to get more debug information about this error?
How to solve it?

This issue should be fixed in the newest Varbase release. See: https://www.drupal.org/node/2912709


Drupal 7 - better navigation for Pages in custom menu I have several custom menus that link to Pages in my Drupal 7 site.  One custom menu is called Announcements.  When I visit a Page that is linked in the Announcements menu, I would like to display in the sidebar the other links that are in the Announcements menu.  I don't want to have to create a menu block for Announcements and manually maintain a list of nodes on which to show the menu block, to make it show only on the Announcements pages.  How can I dynamically list links from the custom menu that links to the current page?

It would also be nice if...

I have a page called News Archives on which a menu block is displayed for the Announcements menu as well as some other menus.  It would be nice to have a custom breadcrumb for any Page linked in the Announcements menu like 'Home > News Archives > [the current page]'.  I have the Custom Breadcrumbs module installed, if someone can think of a way to use this for this purpose.
The Pages in a given menu don't have any pattern to their URL, or hierarchy.  Many of them are just off the root site, e.g., http://mysite.com/page_linked_in_announcements_menu.  Is there any way to dynamically change a Page's URL alias to reflect which custom menu it belongs to?  So on the edit page for a Page, the URL alias might be "blah", but it's linked in the Announcements menu, so I can access it at /announcements/blah.  Then if I moved "blah" to My Other Custom Menu, its URL would automatically become /my-other-custom-menu/blah, without me having to edit the URL alias by hand.

This is a cross-post from Stack Overflow because I didn't know how to port the question over.

This best approach in this regard can be a single multi level menu along with Menu Block module.

Top level menu form main navigation to sections while first level children appear as section items menus. Menu Block configured with 2nd level items chooses second level items siblings of current active item.


PDOException: SQLSTATE[42000] Implicit conversion from data type nvarchar to varbinary(max) is not allowed I got this problem with my drupal 7.24, Windows server 2012, IIS8 and the sql server 2012.
I'm using the last dev version of sqlsrv which is suppose to fix a similar bug, but I still have this one.

PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. in dblog_watchdog() (line 160 of D:\inetpub\website\modules\dblog\dblog.module).

I've migrated my DB from a mysql to the sql server through the migration tool and using the drivers 5 and 3.51 to convert the schema. (got the same error in both case)
BTW I have hexadecimal data sometime instead of normal data.
function dblog_watchdog(array $log_entry) {
  Database::getConnection('default', 'default')->insert('watchdog')
    ->fields(array(
      'uid' => $log_entry['uid'],
      'type' => substr($log_entry['type'], 0, 64),
      'message' => $log_entry['message'],
      'variables' => serialize($log_entry['variables']),
      'severity' => $log_entry['severity'],
      'link' => substr($log_entry['link'], 0, 255),
      'location' => $log_entry['request_uri'],
      'referer' => $log_entry['referer'],
      'hostname' => substr($log_entry['ip'], 0, 128),
      'timestamp' => $log_entry['timestamp'],
    ))
    ->execute();
}

On the dbo.watchdog I have a column call variables which is a varbinary(max) (used to be a LONGBLOB on mysql) and got hex data now. I think the problem is coming from here.
When I comment those lines (insert query), it works, but with a lot of warning like:

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of D:\inetpub\website\includes\entity.inc).
Warning: Cannot modify header information - headers already sent by (output started at D:\inetpub\wendy\includes\common.inc:2700) in drupal_send_headers() (line 1216 of D:\inetpub\website\includes\bootstrap.inc)
PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. in variable_set() (line 975 of D:\inetpub\website\includes\bootstrap.inc).

Anyone got an idea how to fix that?

I've figured out the main problem, when I was using the SQL migration tool to migrate, it was creating a database, so I devided to create mine to check. The one created by the tool was Latin1_general_CL_AS and mine was SQL_Latin1_General_CP1_CI_AS instead. That seems to have fixed the problem


Manage content items using Views I'm creating a user-upload photo gallery, and I require admin approval on all user uploads. Photos will be a content type with just a few fields (Image, Taxonomy, Tags). I'd like to be able to view a grid of all uploaded photos at a glance, and then check a box next to each one and publish/unpublish all that are selected. Is there a method by which I an do this using Views? If not, is there another method/module that can provide this type of functionality?

Thanks!

Create a content view, filter by your gallery content type, add the image field, add the field  "Content: Published" (to let you know if content is published). Then add  "Bulk operations: Content" (you need to install Views Bulk Operations module). In the field settings you should select the option "Publish content" and "Unpublish content". You should now be able to bulk publish and unpublish the image galleries.


How do I add a meta tag in inside the  tag? How can I add the following meta tag inside the <head> tag?
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

I am trying to add it to a Drupal 8 site.

From different sources I found different way of adding meta tags in Drupal 8, hence compiling all ways.

1. Using THEME.theme file

I think same question has been asked on stakeoverflow: add meta tag to head in drupal 8
 and if you see the answer of @Danielishko, He has provided the following code,

Just add following code in your THEME.theme file, clear cache and you will be good to go. Note: function theme_preprocess_html(&$variables) {...} should be already there in your .theme file, hence do not create new one, otherwise it will give error.

function theme_preprocess_html(&$variables) {

  $xuacompatible = [
    '#tag' => 'meta',
    '#attributes' => [
      'http-equiv' => 'x-ua-compatible',
      'content' => 'ie=edge',
    ],
  ];

  $variables['page']['#attached']['html_head'][] = [$xuacompatible, 'x-ua-compatible'];
}

Output image:

2. Through Template file:

Another Question was asked on this topic: How to set / remove drupal 8 meta tags.

If you read the question in the above mentioned link, Questioner has mentioned that using html.html.twig template file you can directly add meta tags to ....

html.html.twig file you can find at core/modules/sytem/templates/html.html.twig, You can copy and paste that in your theme's template folder and your theme will use that one.

from html.html.twig

<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}

      {{ 'Skip to main content'|t }}

    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">

Output Image:

NOTE: This is my own logic and tried to find reference for this, I did not find any reference regarding this except one line provides by Questioner in above link, but since we edit template file for adding other stuff why we can not use to add  tags. PLEASE PROVIDE COMMENTS IF THIS IS NOT  A RIGHT WAY TO DO, It will also be learning experience for me, Thanks.

3. Create your own Custom Module

If you refer this tutorial of: Adding new HTML tags in the  in Drupal 8, He has described the general way of adding tag to head in Drupal 8. I have modified as per your requirement. You can refer this tutorial: Drupal 8: Create a Simple Module for how to develop simple module in Drupal 8, and following code will go in your module_name.module file, that's it.

for module_name.module file,

<?php
/**
 * Implements hook_page_attachments().
 */
function module_name_page_attachments(array &$page) {
  $xuacompatible = [
        '#tag' => 'meta',
        '#attributes' => [
          'http-equiv' => 'x-ua-compatible',
          'content' => 'ie=edge',
        ],
      ];
  $page['#attached']['html_head'][] = [$xuacompatible, 'x-ua-compatible'];
}

I think, this method and method described in 1st option are quite same.

4. Using Drupal module

I am not sure, how to use this approach, I tried to find. Here I am mentioning because when point of adding meta tags comes this module always pop-up.

I think this approach you should use. In the accepted answer he has describe the module way and you can use, Metatag module for that. This module has dependent modules Token & Ctools, which is very common thing. In that answer whole procedure has been described, so I am not mentioning here.


Find out if you're viewing a taxonomy page Clicking on a Taxonomy term generally takes you to a page showing several nodes which use that term. Is there a way to find out if you're viewing a specific vocabulary and save it to a variable? That way you can change the layout at will:

<?php if( $is_vocabulary_fruits ) : ?>
    Load this layout
<?php if( $is_vocabulary_cars ) : ?>
    Another layout different from the first
<?php else : ?>
    Nope, use this layout instead
<?php endif; ?>

I'm looking to place this in page.tpl.php. This means that the markup outside of the node.tpl.php is changed when viewing a taxonomy and not the node itself. How is this done in my template.php file?

When a taxonomy page is rendered, the template file used is taxonomy-term.tpl.php that receives, among other variables, the $term variable, which contains the term object for the taxonomy term associated to those nodes.
Basing on the vocabulary that owns that taxonomy term, you can change the layout of the page.

If you want to find out in page.tpl.php the taxonomy term associated with the nodes shown in the page (where the page's URL is example.com/taxonomy/term/[tid]), then you can use the following code:

$term = menu_get_object('taxonomy_term', 2);

If the page's URL is not example.com/taxonomy/term/[tid], then the function returns FALSE. The code can also be executed in a preprocess function, such as hook_preprocess_page().


Translation of list (text) values I am new do Drupal. I am testing out Drupal 8's multilingual capabilities.

I created a new content type with a field of type List (text) and a field of type Text. I have provided a translation for the text field, and switching language works fine when displaying it in a view. I have also entered a translation for the list field values, but those do not change when changing language. How do I get them to display in the selected language? I did set the Rendering Language to "Interface text language selected for the page". I don't see an option to make field values render in the selected language, but it's working fine for text fields. I cannot figure out why it does not work for list values.

You can refer the following tutorial for the same, it's well explained.

https://www.ostraining.com/blog/drupal/d8-multi-lingual/

https://www.drupal.org/docs/8/multilingual/choosing-and-installing-multilingual-modules


Custom Validator on Custom Form I see all kinds of examples of how to add a custom validator to an "existing form." Which means, you would use hook_form_alter. I want to add one in the code for my custom form.

I'm adding this in my buildForm():

$form['#validate'][] = 'mycustom_form_validate';

However, that function never seems to get called. I know naming the validation function "validateForm()" would make it work automatically. But I want to specifically call this validation function because things are going to get more complex. But I seem stuck on this baby step.

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#attributes']['novalidate'] = 'novalidate';
    $form['#cache']['max-age'] = 0;
    $form['#action'] = '#email_subscription';
    $form['#validate'][] = 'mycustom_form_validate';

    $form['fname'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First Name'),
      '#maxlength' => 255,
      '#size' => 64,
      '#required' => TRUE,
      '#required_error' => 'Please provide your first name.',
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('send'),
    ];

    return $form;
  }

  public function mycustom_form_validate(array &$form, FormStateInterface $form_state) {
    $valid = $this->validateEmail($form, $form_state);
    if (!$valid) {
      $form_state->setErrorByName('email', $this->t('Invalid email address.'));
    }
  }

You just need to change the line to:

$form['#validate'][] = '::mycustom_form_validate';

Drupal has special handling for that :: prefix (see FormState::prepareCallback), and processes the above to an equivalent callback of:

[$form_object, 'mycustom_form_validate']

Which will correctly resolve to your custom method.


How to use the language neutral url alias pattern in pathauto? I want to use the following patterns in pathauto:

myCT All languages: pattern1
myCT neutral language: pattern2
myCT EN language: pattern2

So that all neutral (UND) and EN nodes of myCT have pattern2 and all other languages have pattern1. I'm using the ALL languages pattern for all other, as I have many other languages that should have the same pattern and I do not want to repeat it.

I'm using entity translation module for myCT.

When I create a node and save it having the default language (UND) and automatic path alias, pattern1 is always generated. I have to re-edit the node to have it get the correct pattern (for UND/neutral language), pattern2.

First of all, the pathauto_pattern_load_by_entity function (pathauto.module file) is called before the node creation, so the language of the node is always UND during creation of a node.

Second, trying to debug the pathauto module I can see the following:

function pathauto_pattern_load_by_entity($entity, $bundle = '', $language = LANGUAGE_NONE) {
  $patterns = &drupal_static(__FUNCTION__, array());

  $pattern_id = "$entity:$bundle:$language";
  if (!isset($patterns[$pattern_id])) {
    $variables = array();
    if ($language != LANGUAGE_NONE) {
      $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
    }
    if ($bundle) {
      $variables[] = "pathauto_{$entity}_{$bundle}_pattern";
    }
    $variables[] = "pathauto_{$entity}_pattern";

    foreach ($variables as $variable) {
      if ($pattern = trim(variable_get($variable, ''))) {
        break;
      }
    }

    $patterns[$pattern_id] = $pattern;
  }

  return $patterns[$pattern_id];
}

So in the following lines it seems that it never takes into account the neutral language path.

if ($language != LANGUAGE_NONE) {
   $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
}

Shouldn't that if statement be removed? How is it possible to use the neutral language path otherwise?

You can use the Pathauto i18n module:

  This module provides functionality to create aliases for each
  language. Also this module will be helpful, if you use field
  translation and you want show node on all language with paths,
  different from node/nid.


There is no homepage URL I have just started learning/working with Drupal and I am trying to build a theme for a website (something that has nothing to do with a blog other than the fact that the content is dynamically generated).

I have just installed Drupal 8.4 with the Minimal profile and created the bare structure of my theme. However, when I go to visit http://mysite I get redirected to http://mysite/users/1.

I want to create a frontpage containing a large search bar and the thumbnails of some content (if that matters in any way). I created a page--front.html.twig but I still can't get rid of the redirect from / to /users/1.

Could you please give me some advice regarding this redirect and the more general idea of implementing a custom landing page?

This is the site default configuration:

/core/modules/system/config/install/system.site.yml

uuid: ''
name: 'Drupal'
mail: ''
slogan: ''
page:
  403: ''
  404: ''
  front: /user/login
admin_compact_mode: false
weight_select_max: 100
langcode: en
default_langcode: en

So if you have a Minimal install, you have to go to /admin/config/system/site-information and change the default front page.

The Standard profile overwrites this config to point it to the pre-installed front page view.


Straight to checkout with commerce So I have created a product in Commerce: a £15 one-off donation.

I don't need a product page for this (I have a custom block with links for different donation amounts). When you click a link, I want to use the product ID, and push the product straight to checkout.

How would I go about this?

The way to programatically add a product to the cart and send a user to checkout would be to use the function:

function commerce_cart_product_add_by_id**($product_id,
                        $quantity = 1, $combine = TRUE, $uid = NULL)

and

function drupal_goto**($path = '', array $options = array(),
       $http_response_code = 302)

to redirect the user to checkout.

Here is information on the functions:

commerce_cart_product_add_by_id
drupal_goto


entityQuery vs. entityTypeManager I have a custom content type user_in_club and I'd like to load a single specific node matching two field values. There are 2 ways (I know of) which can solve this:

$result = \Drupal::entityQuery('node')
->condition('type', 'user_in_club')
->condition('field_user_id', $account->id())
->condition('field_club_id',$active_club)
->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

OR

$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'user_in_club', 'field_user_id' => $account->id(), 'field_club_id' => $active_club ]);

In my single example only one node id is returned, but in case I  have multiple node ids returned, is one method to be preferred over the other in terms of performance etc ? I currently don't see a big difference other than ETQ is better to create more complex queries.

They're identical. loadByProperties() actually converts your conditions to an entity query internally.

I'd acually recommend to do an entity query yourself, directly. It's more readable and loadByProperties() might get deprecated in the future.


UC Node Checkout for pay to publish user content? Is there a way to use this module for a pay to publish set up, like in classifieds where user adds content and then pays to publish it in D7?

Generally speaking that is....I like many others having been paying for a module but the person who created it has disappeared now and it is first time ever I've paid for something re drupal. Normally I study up on anything open source- which just goes to show there are no shortcuts in this world.

Try Pay-per-node

This module allows creation of a number of nodes of chosen type for some users. It temporarily overrides the node creation permissions and keeps track of the number of nodes the user can create.

It can be used as standalone module or as an e-commerce plug-in. In the second case paypernode can be integrated with Ubercart, providing a new "product feature" which will allow, upon product purchase, to create a number of nodes.