How do I get Location / GMap / Views setup to display non-US map nodes? Drupal 6, Views 2

I'm using the Location module to store address information for various contacts in nodes. I am then using the Views module along with the GMap sub-module of Location to display these nodes as map markers on a Google Maps style map on a page in my site.

This works perfectly for USA addresses, but I can't get Canada or UK addresses to display on the node map. The link inside the node (from Location module) to view the location in an external Google Map works just fine, so I can confirm the addresses are valid. However, they do not display on my Drupal Views generated Google Map a la Location/GMap.

Note - disabled and/or cleared cache to make sure this wasn't an issue. Also Regenerated marker cache inside of Location configuration to rule that out also.

Is there some kind of configuration setting I'm missing?

I can confirm that it is possible to get locations and GMAP running on Drupal 6 for Canadian addresses.  I have done this on more than one occasion.

From your description it simply sounds some setting preventing the reverse geocoding of addresses. Edit one of your nodes with canadian addresses and confirm that the Lat and Lon field are empty.  Save then edit again and confirm it is still empty.

If the lat/lon fields are empty try the following

Make sure you have a valid google maps API key for the URL you are running the site under.
Confirm that the location module has access to this API keys. Reverse geocoding settings for locations module is under /admin/settings/location/geocoding go to Canada and click "Configure parameters"   Or go there directly: /admin/settings/location/geocoding/ca/google  Your Gmap google map api key should be displayed.
Confirm that as a user you have permission to save lat/long info.  Under user permissions (/admin/user/permissions) go to "location module" and check that  "submit latitude/longitude" is selected for users that will be creating the nodes with address information. If not then there will be no reverse geocoding for any address, Canadian or otherwise.
Once you have confirmed the above, revisit a node with a Canadian address.  Edit and hit save. This will re-run the reverse geocoding.  If a lat/long is not saved then I will have to do some more digging. Also if you have lots of nodes in need of reverse geocoding, it is possible to do this programmatically.
Are you using CCK field or location module itself to save the address and lat/on? I am uncertain whether or not reverse geocoding works with the cck location field in D6.


CKEditor ACF Configuration Help? I am new to configuring CKEditor on Drupal 7, and even with the UI, it has always been a pain. I am trying to have it to stop stripping / removing tags, specifically - code, pre, ins del, blockquote, q, dl, dd, dt. I have a test page which I use to test my site's styles and these are getting removed in both Full and Filtered. Grrrr...

Keep in mind I have no idea what I am doing here. Please help me figure this out so I do not waste another day on this. =(

ACF's extra allowed content

I have added the following there:

br; div; span; header; footer; section; aside; figure; a; img; strong; em; h1; h2; h3; h4; h5; h6; ins; del; cite; q; blockquote; code; pre; table; tr; td; th; thead; tfoot; caption; legend; col; ul; ol; li; dl; dd; dt;</code>

config.js

I have found config.js and added the following to get it to stop stripping out tags.

CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.allowedContent = 'br div span;' +
    'header footer section aside figure;' +
    'a[!href]; img[!src,alt,width,height];strong em h1 h2 h3 h4 h5 h6;' +
     'ins del cite q blockquote code pre;' +
     'table tr td th thead tfoot caption legend col;' +
     'ul ol li dl dd dt';
config.extraAllowedContent = ' br div(*) span(*);' +
    'header footer section aside figure;' +
    'a[!href]; img[!src,alt,width,height];strong em h1 h2 h3 h4 h5 h6;' +
    'ins del cite q blockquote code pre;' +
     'table tr td th thead tfoot caption legend col;' +
     'ul ol li dl dd dt';
};

If you just want to disable the content filter altogether, you can use:

config.allowedContent = TRUE;

Also, make sure you're clearing your Drupal cache AND browser cache. The CKEditor JS files are heavily cached by the browser and I wasted lots of time banging my head against the wall before I realized this.


A menu link that points to specfic place on a page (I can't use anchors) I have some embedded pdfs on my site using PDF Reader module, which is working great.  But my boss wants a link to a specific place in one of those pdfs.  Thus I need some way to add a link to the main menu, that will take the user to the page with the embedded pdf, and then automatically scroll down to the proper spot in the multi-page pdf.

I've looked at both the jquery.scrollTo module and the jquery.scrollTo script, but I can't see how to use these without using #anchors, which I cannot put into the middle of my embedded pdfs.

Is jquery.scrollTo the right way to go? Something else?

Thanks in advance,
Peace Corps Volunteer, In Way Over His Head

I know it's been a while, but I found this forum post and thought it might help you:

http://forums.adobe.com/thread/13098


How to store HTML data in a database field? I'm trying to write some code for the Image marker module to allow an HTML description to be stored in the database. Currently all text is escaped and stored as plain text.

The module stores x/y coordinates and descriptions as name/value pairs in a database field, for example:

x=208&y=251&id=208-251&description=wheel;x=77&y=142&id=77-142&description=light

Can I store HTML descriptions this way? Is there a better way to store this kind of data?

Basic info about user input sanitization in Drupal.


How to safely render node body on a custom variable? I created a custom template for my programmatically created block.

I defined a variable for the template called test

so in my render array I have

'#test' => $node->get('body')->value

Problem is when I print {{ test }} in my twig template, it literally prints the html rather than rendering it. Ex: <p> My node body </p>

I've also have tried:

'#test' => $node

Then on twig {{ test.body.value }}

but same result, the html does not get rendered.

The only way I found to make render is by doing {{ test.body.value|raw }} but raw filter should never be used on user entered data.

How can I make Drupal stop escaping the html safely?

Build a render element processed_text and set the text format from the body field, so that the right text filters are applied before you print the field with {{ body }}:

If you have the node in #test like in your second example:

'#test' => $node

then you can build the render element in twig:

{% set body = {
  '#type':   'processed_text',
  '#text':    test.body.value,
  '#format':  test.body.format,
} %}

{{ body }}

This is the preferred method, see the documentation of check_markup():

  Note: this function should only be used when filtering text for use
  elsewhere  than on a rendered HTML page. If this is part of a HTML
  page, then a  renderable array with a #type 'processed_text' element
  should be used instead  of this, because that will allow cacheability
  metadata to be set and bubbled  up and attachments to be associated
  (assets, placeholders, etc.). In other  words: if you are presenting
  the filtered text in a HTML page, the only way  this will be presented
  correctly, is by using the 'processed_text' element.

https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check_markup/8.2.x

Render element in php:

'#test' => [
  '#type' => 'processed_text',
  '#text' => $node->body->value,
  '#format' => $node->body->format,
],

and print in twig:

{{ test }}


How to add dev modules to a distribution without getting security updates warnings? I have made a distribution, which contains some modules which are in dev state. These modules are being by drush make checked out by git. So my drupal-org.make file contains something like:

projects[ctools][type] = module
projects[ctools][download][type] = git
projects[ctools][download][url] = http://git.drupal.org/project/ctools.git
projects[ctools][download][revision] = e720f61
projects[ctools][subdir] = "contrib"

(I need ctools' current dev version because of a batch that was commited shortly after 7.x-1.4 came out.)

This works ok but when using my distro I always get "security updates available"-warnings, which I would not get if I downloaded and used this same dev version on a standalone project.

What is the best way to handle this? Can I somehow tell drush make to download a specific dev version, as these dev versions are packaged by d.o. and are idenifiable: e.g. version = "7.x-1.4+4-dev"

Article Common Drush Make errors and their solutions has a solution for you. It seems that you should provide both branch and revision, if you want to clone exact revision and still have other info filled properly.

projects[ctools][type] = module
projects[ctools][download][type] = git
projects[ctools][download][revision] = 747151e
projects[ctools][download][branch] = 7.x-1.x

  Although you're specifying both a revision and a branch, drush make is smart enough to use the more specific thing (the revision) when cloning. It just uses the branch information for other metadata (updating the .info files in the things it checked out, and for displaying the contents of the distribution on the release node).

Emphasis mine.


How can I detect what control caused AJAX callback? I have a form containing a table, which displays rows from a database table, and has a couple of editable fields, which is all working fine.

I now want to make one of fields trigger an AJAX callback when changed, and the callback to update another field in the same row.

Can the callback function check which instance of the changed field triggered the callback, so it knows which row to update?

Thanks for your help, and happy new year!

James

I use this code since drupal 7, only changed the first line for drupal 8:

$triggering_element = $form_state->getTriggeringElement();
if ( isset($triggering_element) ) {
  $trigger = $triggering_element['#name'];
  if ( $trigger == 'op' ) {
    $trigger = $triggering_element['#parents']['0'];
  }
}
else {
  $trigger = '';
};

If trigger is 'op', then it is a button and i get the name from the parent.

And see comment of Ivan Jaros, make the names unique.


override 'Edit own content' using taxonomy access Can I override 'Edit own content' for a particular role and a particular node using taxonomy access? Or better, can I simply switch off Drupal's built-in access content module and solely rely on the settings of TAC (taxonomy access content module)?

What I'm trying to accomplish here is:

a user creates content, the user works on their own content until they think it's ready for moderation upon which they'll set a taxonomy term to 'finished content'. A moderator now comes into play and checks the content of the user. If they decide to approve the content they set a vocabulary term to 'approved content'. This triggers a rule which sets the locking vocabulary of that node to the term 'Locked'. At this point the author should not be able anymore to edit this content.

The problem is that node access permissions still allows the author to edit their own content. How would you tackle such a problem?
Cheers!

Ok, I've found a way around it. I'm using the Workbench Access module.

This module, which can be used as a stand alone module, allows you to use taxonomy terms as sections you can set on any node and then you need to assign the roles (or particular users) who can update nodes with these terms/sections. In conjunction with the taxonomy access control module I found that you must at least set the global default for that role to 'view'. If you don't, the users of that particular role won't have update AND view access which is not what I wanted. They can see what they've created but they can't change it anymore after they saved it or after a certain taxonomy term has been set, by themselves or automatically through rules.

Hope that helps others as well!
Cheers!


Question about adding a field value to a view programmatically I am having a problem getting a field to print and know it is something I am missing. I am trying to print a product field in a view that is created programmatically. Everything else is working fine, but I cannot pull the item size in to the view. here is the code:

 $form['assigned'] = array(
'#type' => 'fieldset',
'#title' => t('Assigned orders'),
'#tree' => TRUE,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$orders = views_get_view('get_drivers_orders');
$orders->set_display('default');
$orders->set_arguments(array('0' => $account->uid));
// change the amount of items to show
$orders->pre_execute();
$orders->execute();
$orders->render();
if ($orders->result) {
foreach ($orders->result as $key => $value) {
  $order = uc_order_load($value->field_driver_id_users_order_id);
  $form['assigned'][$key] = array(
    '#type' => 'fieldset',
    '#title' => t('Order #' . $value->field_driver_id_users_order_id),
    '#tree' => TRUE,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['assigned'][$key]['view'] = array(
    '#markup' => l('View order', 'user/' . $account->uid . '/delivery/' . $order->order_id),
  );
  foreach ($order->products as $product_id => $product) {
    $form['assigned'][$key][$product_id]['attribute'] = array(
      '#type' => 'item',
      '#title' => t($product->title),
      '#markup' => isset($product->data['attributes']['What would you like']) ? $product->data['attributes']['What would you like'][0] : '',
    );
    $form['assigned'][$key][$product_id]['size'] = array(
      '#type' => 'item',
      '#title' => t('Size:'),
      '#markup' => isset($product->data['size']) ? $product->data['size'][und][0]['value'] : '',
    );
  }
  $address = uc_custom_process_get_order_address($order);
  $form['assigned'][$key]['map'] = array(
    '#markup' => l('View map','http://www.google.com/maps?q='.$address.'(tooltip/infowindow title)',array('attributes' => array('target'=>'_blank'))),
  );
  $form['assigned'][$key]['total'] = array(
    '#type' => 'item',
    '#title' => t('Total:'),
    '#markup' => '$' . $order->order_total,
  );
}

Here is an image of the krumo of the the view with the products, I do hope someone can help!
    }

I have looked over the proposed solution and it does not fit my use case. I have a view that shows an individual order, that order has products, and those products have all of there values stored in $product->data. I have tried everything to get information from the 'size' field to display in that view and it is not happening. I am not trying to change a value, just display it! I hope this helps everyone help me! :D

So the issues was that Krumo pulled that information of its own accord, and the $order object did not have those details. I had to call $product->nid first, query the DB for the field values i needed, and insert them. I ended up with this code, in case it can help anyone!

    foreach ($order->products as $product_id => $product) {
    $pid = $product->nid;
    $ps = db_query('SELECT field_size_value FROM field_data_field_size WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $pp = db_query('SELECT field_pack_value FROM field_data_field_pack WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $form['assigned'][$key][$product_id]['attribute'] = array(
      '#type' => 'item',
      '#title' => t($product->title),
      '#markup' => isset($product->data['attributes']['What would you like']) ? $product->data['attributes']['What would you like'][0] : '',
    );
    if(!empty($ps)){
        $form['assigned'][$key][$product_id]['size'] = array(
      '#type' => 'item',
      '#title' => t('Size:'),
      '#markup' => $ps,
    );
    }
    if(!empty($pp)){
      $form['assigned'][$key][$product_id]['pack'] = array(
        '#type' => 'item',
        '#title' => t('Pack:'),
        '#markup' => $pp,
      );
    }
  }


Disable user field on profile edit page I've got a logintoboggan (http://drupal.org/project/logintoboggan/) module and my login is an email adress, so I dont want to have a "Name: " field on my profile edit page.

But when i just call in my theme preprocess page:

$vars['form']['account']['name']['#required'] = FALSE;

or unset() the field I've got an error:

  Username field is required.

How can I disable validation of this field? Thanks!

The username field is a required field in the {users} table so it has to be there one way or another.

A way round it might be to remove the "Change own username" permission for authenticated users at http://mysite.com/admin/user/permissions. I can't remember if the field will still display on the user edit form but either way it won't be editable.


How to give blocks a meaningful name in the views overview page? I think, the image will speak for itself:

I have tried the block & display titles, the block name & also the new administrative comment field. Still the views overview looks not very informative.

Thanks!

Currently your description is empty, you can add a description to your view which will help somewhat.

Click on the edit view name/description button


altering user_admin_account form I am working to change the standard display when pressing the "People" button.
Instead of showing "Username" I want it to show a custom field. For example "Last name".

I almost made it work, but the pager is not working. When I click page 2, the same info shows as page 1. Sorting is working though.

Here's the slightly changed code, which originated from the core user module.

<?php
function user_custom_form_user_admin_account_alter(&$form, &$form_state, $form_id) {

  $header = array(
    'field_lastname_value' => array('data' => t('Username'), 'field' => 'dn.field_lastname_value', 'sort' => 'asc'),
    'status' => array('data' => t('Status'), 'field' => 'u.status'),
    'roles' => array('data' => t('Roles')),
    'member_for' => array('data' => t('Member for'), 'field' => 'u.created'),
    'access' => array('data' => t('Last access'), 'field' => 'u.access'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('users', 'u');
  $query->condition('u.uid', 0, '<>');
  $query->leftJoin('field_data_field_lastname', 'dn', 'u.uid = dn.entity_id');
  user_build_filter_query($query);

  $count_query = clone $query;
  $count_query->addExpression('COUNT(dn.entity_id)');    // or u.uid, does not make any diff.

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
    ->fields('dn', array('field_lastname_value'))
    ->limit(20)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

...

    $account->name = $account->field_lastname_value;
    $options[$account->uid] = array(
      'field_lastname_value' => theme('username', array('account' => $account)),
      'status' =>  $status[$account->status],
      'roles' => theme('item_list', array('items' => $users_roles)),
      'member_for' => format_interval(REQUEST_TIME - $account->created),
      'access' =>  $account->access ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $account->access))) : t('never'),
      'operations' => array('data' => array('#type' => 'link', '#title' => t('edit'), '#href' => "user/$account->uid/edit", '#options' => array('query' => $destination))),
    );

      ...
}
        ?>

Can anyone help? I have been struggling with this for hours. I did try changing the position of pagerDefault and TableSort to all kind of possible places like in the beginning before the join, after the join, tried with other joins then just left join, I'm stuck. Maybe I have to call SELECT FROM the custom field table and join the users table? But that's odd.
Any help is really appreciated.

I faced a similar issue while adding a new field 'Mail' in the 'user_admin_account' form.

During my search I came across this post & also this post 'https://drupal.org/node/1899708' which address the same issue. I got a solution for this as described below:

/**
 * Implements hook_form_FORMID_alter()
 * @param $form
 * @param $form_state
 * @param $form_id
 * @return $form
 */
function CUSTOMMODULE_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  // Adding User Mail Field in the 'user_admin_account' form
  $mail_header = array(
    'mail' => array('data' => t('Mail'), 'field' => 'u.mail'),
  );
  // Placing Mail at 2nd position
  array_splice($form['accounts']['#header'], 1, 0, $mail_header);

  foreach($form['accounts']['#options'] as $key =>$value){
       $query = db_select('users', 'u')
        ->fields('u', array('mail'))
        ->condition('u.uid', $key)
        ->execute()
    ->fetchAssoc();

    array_unshift($form['accounts']['#options'][$key], $query['mail']);
  }

  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

Although this post dates back in '11, but as i did not get any solution based on my search so considered to post this answer. Hope it helps.


Add attribute to html and body I need to add class="no-trans" to body, also edit the html tag.
How I can edit the {{ html_attributes }} and {{ body_attributes }} ?

my html.html.twig

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ body_attributes }}>

Here is a preprocess alternative (maybe you will need access to some info to make custom html classes).

use Drupal\Core\Template\Attribute;

/**
 * Implements template_preprocess_html().
 */
function MODULE_OR_THEME_preprocess_html(&$vars) {

  if (is_array($vars['attributes'])) {
    $vars['attributes'] = new Attribute($vars['attributes']);
  }

  $vars['html_attributes']->addClass('goes-to-HTML-tag');
  $vars['attributes']->addClass('no-trans');
}


What to set up in a Kernel test to get custom content type to be available I have a custom module that defines a service and a custom content type. I have successfully written a Functional test for the service. Now, I'm seeing if I can write a Kernel test instead.

The issue that I'm encountering is that my custom content type has custom fields (naturally). When I create a piece of content of that type in the Kernel test environment, Drupal is not recognizing the custom fields.

I am using the EntityKernelTestBase.
I have set public static $modules = array('my_custom_module', 'node');

What piece(s) am I missing? I'm guessing there is some schema I need to say to install or some other method I need to call so that those custom fields are recognized.

<?php

namespace Drupal\Tests\my_custom_module\Kernel;

use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\node\Entity\Node;

/**
 * Tests the my custom service.
 *
 * @group my_custom_module
 */
class MyCustomServiceKernelTest extends EntityKernelTestBase {

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = array('my_custom_module', 'node');

  /**
   * {@inheritdoc}
   */
  public function setUp() {

    parent::setup();

    $user = $this->createUser();

    $container = \Drupal::getContainer();
    $container->get('current_user')->setAccount($user);

    // Create some aquifer pieces of content
    $node = Node::create(array(
      'title' => t('Some title'),
      'type' => 'my_custom_content_type',
      'language' => 'en',
      'field_my_custom_field_1' => 'Put stuff here',
      'field_my_custom_field_2' => 'more stuff',
      'field_my_custom_field' => 1000000,
    ));
    $node->save();
    $reloaded_entity = $this->reloadEntity($node);
    $this->assertSame('debug', $reloaded_entity);
  }
}

The debug assert statement shows that the reloaded entity does not contain my custom fields.

If I put a $node->set('field_my_custom_field_1', 'some value') statement in the code instead of passing those fields in the Node::create logic I get an error that the field name is not valid.

For kernel tests you need to specify which configurations you want installed. For instance, you'll need something like this in your test's setUp() method:

$this->installConfig(['my_custom_module']);

That takes an array of modules, so you'll probably need to specify additional modules (like filter, node, and field potentially).

This assumes your field configurations are bundled in your module's config/install directory.


Can't uninstall User Badges How can I uninstall the User Badges Module? I always get the same error when I try:

  Recoverable fatal error: Argument 1 passed to file_delete() must be an instance of stdClass, string given, called in...

Up to Drupal 7 all modules and themes list is stored in system table with there enabled (i.e. 1) / disabled (i.e. 0) status. To Disable your module, set the status to 0 for the module name that you want to disable. Check simple MySQL query below:

UPDATE system SET status='0' WHERE name='module_name';

After running the above query, try emptying the cache tables. You can identify cache tables by table name starting with cache_. To make sure Drupal doesn't try loading from cache.

You can find more details about same on Drupal.org in Disabling or enabling modules manually in the database Or check How to manually uninstall a module? question.


How do I force nodes to have revisions by default when using REST? We have a headless Drupal 8 content repository which we access via the REST API.  I'd like Drupal to track revisions automatically for all nodes, as soon as they are created.  I'm only aware of the "create new revision" checkbox on the node edit form.

How might I set Drupal to create revisions automatically?

All nodes are created programmatically via the REST API.

The node type setting mentioned by the other answers only applies to the node form, it does not affect programatically saved nodes.

You could try to implement hook_node_presave() and call setNewRevision(TRUE) or maybe the same in hook_node_load(). Or override the rest plugin (assuming you use that and not your own controllers).


How to list different terms with their nodes in one view? Now I had a question, is it possible to build a view which can display different terms with multiple content on drupal 8?

For example,

Term 1

node 1
node 2
node 3

Term 2

node 2
node 4
node 6

Term 3

node 5
node 7
node 8

Can someone help me out?

I appreciate your help!

You can achieve you requirement by below steps:

Create view at /admin/structure/views
Now add fields which you want to display.
Click on Settings under FORMAT section.

Now add your taxonomy field as Grouping Field


How to I add specific meta tags to panels pages? I have panels pages, and I need to set specific meta tags per page.  The meta tags module lets you set up defaults, but I need specific tags per URL.

I can't seem to find this anywhere.

There is now the Meta tags: Panels module.
Works fine for me.

  This module extends the Meta tags module by adding support for meta tags configuration for panels pages.


How to display translated term names in exposed form in block So I've got a views page displaying a list of nodes from specific content type. This view has filter form exposed in a block.

Some of the filters in the form are vocabularies. I'm using the BEF module to display the terms from each vocabulary as checkboxes instead of the default select lists.

The terms are translated - I'm using i18ntaxonomy for that, the vocabularies have this option selected: Localize terms. Terms are common for all languages, but their name and description may be localized.

The problem is that when the site is displayed in other languages different than the default one, the terms in the form are not translated.

I guess the problem is not with BEF as when I disable the module the terms remain untranslated.

I'm looking for any advice on how to debug/solve this issue.

This is definitely not the correct way to do it, but as the project deadline is tomorrow I've got no other choice but to hack the views module source code:

--- a/htdocs/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc
+++ b/htdocs/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc
@@ -122,7 +122,7 @@ class views_handler_filter_term_node_tid extends views_handler_filter_many_to_on
           $result = db_query("SELECT td.* FROM {term_data} td INNER JOIN {vocabulary} v ON td.vid = v.vid ORDER BY v.weight, v.name, td.weight, td.name");
         }
         while ($term = db_fetch_object($result)) {
-          $options[$term->tid] = $term->name;
+          $options[$term->tid] = i18ntaxonomy_translate_term_name($term);
         }
       }

I don't think a patch for the views module will be accepted. Any suggestions how should I proceed with this?

Your best path would be to open an issue with Views after confirming that the terms don't translate correctly with BEF module disabled.

I found this issue related to translation in BEF's queue, but that looks to be slightly different or only part of your issue.

Unfortunately it can be difficult for contrib module maintainers to test their modules in multiple languages unless they happen to run their own multilingual site, so it is up to the community to make them aware of issues and help test patches.

You also might want to take a look at http://drupal.org/project/i18nviews


LogicException : The controller must return a response (success ! given) i have a service that return for me true in the node (article) successfully create and false if something wrong ,  but in the controller i am getting this error 'LogicException : The controller must return a response (success ! given). dans Symfony\Component\HttpKernel\HttpKernel->handleRaw() (ligne 169 de /var/www/html/vendor/symfony/http-kernel/HttpKernel.php).'
can anyone tell me where is the problem in the controller return of my code please ?

service

 public function createArticle()
  {
    $node = Node::create(array(
      'type' => 'article custom',
      'title' => 'article custom',
      'langcode' => 'fr',
      'uid' => '1',
      'status' => 1,
      'field_fields' => array(),
    ));
    $node->save();
    if($node)
      return true;
    else
      return false;
  }

the controller methode

 public function myPageCreate()
  {
    $service = \Drupal::service('mymodule.ran');
    $createnode = $service->createArticle();
    if($createnode)
      return 'success !';
    else
      return 'somthing wrong !';
  }

A controller must provide a response, but drupal has extended the response handling to look for render arrays, that are then used the generate a response with the rendered html. If you don't provide a render array, then there is no response and then this error message will come up.


Extra fields in Search page Is a module available that can add a particular field on the search page?  I'd like for user's to see an image-field if applicable.

You can use Display Suite module to create custom view mode for search results.


Wrong $language_content variable I'm using entity translation module for node localization and dpm($language_content) always gives english, which is my default language. This outcome is for all languages, I don't understand what is the problem.

The $language_content variable is not set to the language used for the currently shown node, but it contains the value set by the language negotiation providers.

See language_initialize(), which is the function that initialize that and other variables, and that is called from the following code.

  // Ensure the language is correctly returned, even without multilanguage
  // support. Also make sure we have a $language fallback, in case a language
  // negotiation callback needs to do a full bootstrap.
  // Useful for eg. XML/HTML 'lang' attributes.
  $default = language_default();
  foreach ($types as $type) {
    $GLOBALS[$type] = $default;
  }
  if (drupal_multilingual()) {
    include_once DRUPAL_ROOT . '/includes/language.inc';
    foreach ($types as $type) {
      $GLOBALS[$type] = language_initialize($type);
    }
    // Allow modules to react on language system initialization in multilingual
    // environments.
    bootstrap_invoke_all('language_init');
  }

The language negotiation providers are the ones you set in admin/config/regional/language/configure.

If none of the provider is enabled, which what happens by default, that variable will be set with an object for English language.


Block displaying one parent and many children nodes using only Views 3 Drupal 7? I'm trying to generate a block that looks like this in Drupal 7 Views 3:

Parent Node (fields)

Child Node 1 (fields)
Child Node 2 (fields)
Child Node 3 (fields)
...

Parent node is a different content type than child node. For the time being, I've added a matching taxonomy field to the two content types. So to potentially establish a relationship, this value would be the same.
What is the best way to achieve this? It seems like a simple enough goal that Views should be able to handle. I prefer to thoroughly understand the core software w/ Views, before I blindly install a bunch of modules that I may not need.

I've achieved the desired output by creating a vocabulary of taxonomy terms which is essentially just a flat list of foreign keys. There is no semantic representation of a hierarchy here.

NOTE: This is a different example than the event calendar I described in the comments of my initial post, however the data model is the same.

Parent content type (Rich Menu) contains this taxonomy term field, in this example called "Menu".
Child content type (Rich Menu Item) also contains the "Menu" taxonomy term field.
If Rich Menu Item is a child of Rich Menu, the two term fields are set to match. NOTE: I wonder if this idea can be simplified using node references (References module) instead of taxonomy.

Then I created a new block view called "Rich Section Menu". This block will display the parent content type, Rich Menu, filtered by the taxonomy term from the field "Menu" (value = Section). Create an attachment to be displayed after the block which will render a list of children from the Rich Menu Item content type. The child content type will also be filtered by the Menu term field (value = Section). NOTE: Adding the relational term field to the list of filters is only necessary if you expect to have multiple parent/child relationships that share the same content types.

Tried to post screenshots of my Views configuration for clarity, but my reputation isn't high enough.

This achieves the output I desire, however it's a bit simplistic. I would prefer to create a semantically correct parent/child hierarchy using taxonomy or node references, and have Views render that output in a single block, without an attachment, with support for children more than one level deep.

So this works, but is there any way that I can do it better?


How to change view title tag ? Drupal uses the <h1> tag in the title of the view. I want to change title's tag <h1> to <h2>.

hope this will help you..

function mymodule_views_pre_render(&$view) {

  if ($view->name == 'view_name') {

    // Here you can do any php you want to get the title you need for your view.

    $view->build_info['title'] = "
My custom title!
";
  }

or by views-view-unformatted--viewmachinename.tpl.php file

 <?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>


Drush on production server without Composer I want Drush 9 on a Drupal 8 production server without having to install Composer. Is there any way to do this?

And if that is not possible, can anyone suggest an alternative to Drush especially for maintenance, updating and syncing the site with dev and staging?

If you don't want composer in production on your server, you can run the composer commands locally to install Drush, then make sure to push the vendordirectory to the server. Make sure to also commit the composer.json and composer.lock files, so that anyone else working with the codebase can handle composer on their own local machines as well.

In this way you never need composer on the remote production server, but can get drush.


Drupal not loading theme CSS with HTTPS I have a theme and am loading CSS in the traditional way, through the theme.info file, as follows:

stylesheets[all][] = css/style.min.css

However, my clients site uses HTTPS. And every 3rd or 4th load for some reason Drupal tries to load all my files via HTTP rather than HTTPS, causing all the stylesheets/js/images not to load.

Is there any way to force Drupal to use HTTPS on assets while maintaining using the theme.info file to load them?

For a Drupal 7 site using Cloudflare CDN and a Bootstrap theme, this worked for me: Set the base URL in your settings.php file, without including http:// or https://.

$base_url = '//my.domain.name';

For another Drupal 7 site with a different theme, just removing $base_url worked.
In both cases, I needed the site to work with secure URLs and without.


How to utilise RequireJS and still access Drupal(7) JS API? I have a project set up with Drupal loading in RequireJS which has a jQuery dependency defined.

All is well and good until I try something like this in a RequireJS managed module:

    (function($, Drupal) {
        Drupal.behaviors.someModuleName = {

            attach: function(context, settings) {
               // Some functional stuff here
            }
       };
    }(jQuery, Drupal));

The problem is that the attach function does not get called which leads me to think that Drupal is firing off its behaviours loader before Require has loaded up its modules.

Woops, I'm not sure how the explanation got lost!

The script include:

<script id="requirejs" data-rev="1485975293" data-main="main.js?rev=1485975293" src="require.js?rev=1485975293"></script>

Alright, so this is in my main.js (data-main) file, that requirejs uses for loading up the dependencies and all that.

I'm just posting the relevant code block here (notice the Drupal.attachBehaviors(document, Drupal.settings); at the end:

    require([
      'jquery',
      'underscore',
      'intentcontext',
      'app',
      'primary-menu'
      ], function ($, _, IntentContext, app) {
      'use strict';

       // DOM ready
      $(function() {

        // js loaded only on homepage
        if ($('body').hasClass('front')) {
          require(['homepage']);
        }

        /*
         * loaded js for foundation and intention
         */
        require(['foundation']);
        require(['intentinit']);

        // call drupal behaviors
        Drupal.attachBehaviors(document, Drupal.settings);
      }); // DOM ready
    });

And then example of a dependent js module (primary-menu.js):

    define([
      'jquery',
      'intentcontext'
    ], function ($, IntentContext) {
      'use strict';

      /*
       * constructor
       */
      var PrimaryMenu = function(context, settings) {
        var
          self = this;

        self.$elm = $(context).find('#block-system-main-menu');
        $('body').once('primaryMenu').each(function() {
          self.init();
        });
      }; // PrimaryMenu constructor

      /*
       * on document ready with drupal behaviors
       */
      (function($, Drupal) {
        Drupal.behaviors.primaryMenu = {
          attach: function(context, settings) {
            var
              primaryMenu = new PrimaryMenu(context, settings);
          }
        };
      }(jQuery, Drupal));
    });

Hope that helps.


How to download the projects within a distribution using git, not just the distribution itself? I've set $options['package-handler'] = 'git_drupalorg'; set in my .drushrc.php file. Now when I run drush make for a distribution (in this case, the 7.x-3.x-dev release of Commons), the distribution itself gets checked out using git, but not the individual projects (modules and themes) within it. How do I also get those projects checked out as individual git repositories? I'm assuming submodules come into play, but what exactly do I need to do to get that working?

There's no direct way to perform this.

This is a sequence that may fit for a dev environment. It is based on --package-handler=wget and drush make. No submodules. Contrib is downloaded to sites/all.

cd /tmp
drush dl commons --variant=profile-only
drush make commons/drupal-org-core.make distro
mv commons distro/profiles
rm -rf distro/sites/all/
drush make --no-core --no-gitinfofile --working-copy distro/profiles/commons/drupal-org.make  distro/sites/all

I used sites/all because drush make wants a non-existent destination, so distro/profiles/commons is not an option. An alternative is to perform the last make in a tmp directory and copy over the profile directory afterwards.

As a side note, drupal.org profiles provide three packages to download: profile-only, core-profile-and-projects, profile-and-projects. See http://drupal.org/node/1867206 for reference.

drush dl provides an option to choose among these three tarballs: --variant=<full,projects,profile-only>. All three options are available for --package-handler=wget whereas for git_drupalorg the only valid option is profile-only, since it corresponds to a single git project.

That said, there's room to implement a more complex workflow to provide (drush dl commons --variant=full --package-handler=git_drupalorg) by using submodules.


How can I hide the primary menu block to certain pages using PHP? I tried this code to hide the primary menu block from certain pages using the following code:

// Only show block from types array and nodes array
$match = FALSE;
// Which node types
$types = array('page' => 1);
// Which nodes (by nid)
$nodes = array(1, 13);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type]) && in_array($nid, $nodes)) {
        $match = TRUE;
  }
}
return $match;

Currently, the block is set to visible in the header section of the site; the theme being used  is the Bluemarine theme.

Is there anything else that needs to be done?

Print Screen

http://i.stack.imgur.com/m6y4I.jpg

Menu Print Screem

http://i.stack.imgur.com/yUBD2.jpg

You can do it from the block configuration

go to admin/build/block
search for the block and click "configure"
in the "Page specific visibility settings" click on "Show on only the listed pages"
write the page that you want this block to be visible on E.g "news" this will make that block visible on http://www.examble.com/news

Is that what you mean?

UPDATE:

if you want to control tha appearance programatically do the following

1- Disable the primary links block from "admin/build/block"

2- enable the primary links menu from your theme configuration (now i suppose you see the menu in all the pages and you want to specify the pages that you want this menu to appear in)

3- open page.tpl.php file

4- go to line 24 you will find something like this

<?php if (isset($primary_links)) { ?><?php print theme('links', $primary_links, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>

we will edit the following condition if (isset($primary_links))

now you should know something if you have url like this
http://yoursite.com/media/pictures

then the function arg(0) will return media and arg(1) will return pictures

another example

http://yoursite.com/admin

then the function arg(0) will return the first argument in your url which is admin

now lets back to the condition if (isset($primary_links))

we will edit it ... we wanna say to drupal if the first argument is equal to something then appear the menu else disable the menu

suppose that you want the menu to appeare in the page user

then you will edit the if (isset($primary_links)) to be

if (isset($primary_links) && (arg(0) == 'user')  )

suppose that you want this menu to appeare in page user and page admin

if (isset($primary_links) && (arg(0) == 'user' || arg(0) == 'admin')  )

one more advanced example... if you want the menu to appeare only in
user/1 page and admin  page

if (isset($primary_links) && ( (arg(0) == 'user' && arg(1) == '1') || arg(0) == 'admin')  )

hope that will help you


Displaying the contents of a document file (doc, docx, etc.) I'm looking for a way to display the contents of an uploaded document file such as a .docx file.

In Drupal 6 I used the iPaper module which did the trick as all I needed was api code to connect with the service, and the documents were able to be kept private.

But for Drupal 7, I'm pretty sure the File entity (fieldable files) module should do the trick, but I'm not able to get it working for any files other than .txt.

There are some Google viewer modules which I'm not sure what added functionality they have over the above module, but those don't appear to work correctly. One of them requires that files are public domain which doesn't work for this project due to privacy requirements.

Some other modules like group docs viewer and ajax docs viewer charge a hefty monthly fee for displaying rendered files, but all I need is a simple open source docx viewer.

What is the best way to proceed?
Which modules are stable for production use?

Best case would allow for user upload, file contents displayed under the actual file attachment, and the rendered document editable for the user.

Note: i've gotten the google docs module to work but that doesn't allow for private files. google needs to access the file publicly in order to render. scribd field also works to some extent but has too many errors and bugs still. looking for a better, simpler solution.

Maybe this module can be usefull : Flipping Book

  This module provides an integration point between Drupal7 and FlippingBook (http://flippingbook.com/).
  Flippingbook is a very used software to make digital publication from any document you have (.doc, .pdf...).


How to call a custom function when Migration(Import) is done? I am using migration to import nodes from a csv.
I want to change the file name when import is done.
How can I call a custom function when Import/Migration is done from a specific file to change its name?

I knwo about the postimpot but I am looping thorugh directories to import data from each csv file in each directory. So postimport is called every time a file has been imported. But in posImport I cant use argument to change the last imported file name only.

use a static variable in postimport to do a check that you're on the last folder or task or the import, there has to be some value you can track. You could even set a variable of all the csv files to do (in-order) within your migration class -- and check which file you're on in postimport.


How to remove span from rewrite result in a field view? In a custom view I have several fields excluded from display.
I wanted to use their values within an global:fieldset with rewrite output option.
This works but the values are embedded in a  that I don't want, and I didn't find the way to remove it. i.e. if rewrite text use the replacement patterns [field1],[field2],[field3] I got as result

field1 result, field2 result, field3 result

instead of only:
field1 result, field2 result, field3 result

You will need to click on the fields you excluded (one by one), click on Style settings and select Customize field HTML. Then select -None- under HTML Element. You may need to do this for Customize label and Customize wrapper. Click Apply. Don't forget to click Save.

EDIT: Since you have now clarified that you are using Views Fieldsets (and for next time, be sure to provide ALL details about your problem!), I believe you will need to override the default tpl.php file for the Views Fieldset fields.

Views Fieldset provides default tpl.php files inside the template folder inside the module folder (usually found in /sites/all/modules/views_fieldset. You need to copy the content of that file, save it in your theme's template folder and modify it. Follow the steps in this general tutorial (you will need to adapt it to your problem) to override the default template for Views Fieldset fields.  Good luck.


Delete field and related data (field_delete_field, field_delete_instance) I want to delete field from my Content Type using hook_update and wondering how to do it in most correct way.

I know that my field is only on 1 Content Type (page).

Here is my current solution.

function site_deployment_update_7001() {
  $fieldname = 'field_landing_page';

  if ($field = field_info_instance('node', $fieldname, 'page')) {
      field_delete_instance($field);
  }

  if ($field = field_info_field($fieldname)) {
    field_delete_field($field);
  }
}

However I'm a bit confused if I need to do field_delete_field after field_delete_instance. It's because on Drupal.org says that field_delete_instance doing field_delete_field as well (with condition: condition count($field['bundles']) == 0). I'm wondering about this condition, in what cases it is 0?

https://api.drupal.org/api/drupal/modules!field!field.crud.inc/function/field_delete_instance/7

function field_delete_instance($instance, $field_cleanup = TRUE) {
  // Mark the field instance for deletion.
  db_update('field_config_instance')->fields(array('deleted' => 1))->condition('field_name', $instance['field_name'])->condition('entity_type', $instance['entity_type'])->condition('bundle', $instance['bundle'])->execute();

  // Clear the cache.
  field_cache_clear();

  // Mark instance data for deletion.
  $field = field_info_field($instance['field_name']);
  module_invoke($field['storage']['module'], 'field_storage_delete_instance', $instance);

  // Let modules react to the deletion of the instance.
  module_invoke_all('field_delete_instance', $instance);

  // Delete the field itself if we just deleted its last instance.
  if ($field_cleanup && count($field['bundles']) == 0) {
    field_delete_field($field['field_name']);
  }
}

Please advise what are the best approach to delete field. Thanks!

As fields can be attachted to differents bundles

field_delete_instance deletes the field itself only when there no more bundles using it. maybe see field_info_field and this comment from field_delete_instance to clarify

So if in

 if ($field = field_info_instance('node', $fieldname, 'page')) {
   field_delete_instance($field);
 }

Applies and delete the last instance then in

  if ($field = field_info_field($fieldname)) {
    field_delete_field($field);
  }

Should be null and wont execute field_delete_field($field);


How to use separate databases for Drupal tables? So far, what I've read is you can config multisites to use different tables and share any table with other sites in that multisite config.

My question is if it is possible to get this config:

Database A has Site A's users and Site A content
Database B will only have Site B's content
Site B will use users table in database A.
Site B will have its content in database B.

It may not be a multisite question after all but rather, in short...

Is it possible for a Drupal site to use two different databases for some of its tables? How?

In the settings.php file used for the site, you can specific a different prefix for each database table.

  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main_',
      'users'     => 'shared_',
      'sessions'  => 'shared_',
      'role'      => 'shared_',
      'authmap'   => 'shared_',
    ),
    'collation' => 'utf8_general_ci',
  );

You can also refer different databases, or schema, using code similar to the following one.

  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main.',
      'users'     => 'shared.',
      'sessions'  => 'shared.',
      'role'      => 'shared.',
      'authmap'   => 'shared.',
    ),
    'collation' => 'utf8_general_ci',
  );

The difference between the last snippet, and the previous one is that the last character used for the prefixes is the dot, not the underscore. That causes the database engine to select a different database/schema, instead of the currently set one.
To be clearer, in the code I shown the database engine is still MySQL running on localhost; what changes is that for the users table, Drupal will use the shared database instead of the databasename one.

As far as I know, this is valid for Drupal 7, or higher. The same trick is not reported in the comments present in the default.settings.php file that comes with Drupal 6.

Reference

The comments shown in the default.settings.php file.


Creating nodes directly by SQL I am creating (content/nodes)  directly by SQL , I am inserting following tables :
node
node_revision
body_field

everything looks ok . But when I use FLAG module it does'nt show anything on the bookmarked view . Am i missing any other table which should be updated ?

Thanks
pks

Every time you create a node in SQL, God kills a kitten. There are multiple hooks that fire on node creation, that make sure that a new node is processed corectly. The correct way to create a node is with a node_save() function. It will fire the correct hooks, and register the node where it should. Please refer https://drupal.org/node/1388922


How to Schedule a publish date and time How do I schedule a publishing date for a node I've created but don't want to publish until a certain date/time?

Use the scheduler module. This module allows nodes to be published and unpublished on specified dates.


Alternate way to get form without using drupal_get_form I want to get a custom addto_cart_form in one of (commerce_addto_cart_confirmation) the popup. I used drupal_get_form to get that but unfortunately I cant able get the form on popup. I asked those question here but not get any response also. So now I want is there any alternate solution to get form. refer my old question1 and question2here. Thanks for any suggestion.

I don't belive you that mine work in any places

$form = drupal_get_form('yuor_form');
print drupal_render($form);

You can create block with form and output them where you want, somthing like that

function your_module_form_theme() {
  return array(
      'yuor_form' => array(
          'render element' => 'form',
          'template' => 'your_form',
          'path' => drupal_get_path('module', 'your_module_form') . '/templates',
      ),
  );
}


How to render a Views Content Pane programmatically? I have a view which displays all content of type "news" which is tagged with a specific tag, e.g. "world" (passed as parameter to the view).

The view machine name is news. It has a display of type Content Pane (machine name panel_pane_1). It also has a contextual filter set to "field_tags".

How to render this view content pane programmatically, passing tag value "world" to it?

(I've found ctools_content_render but no idea if this is the right function for this task and how to use it)

You can use

views_embed_view

e.g

print views_embed_view('news', 'panel_pane_1', 'world');

Any additional parameters will be passed as arguments, i.e contextual filter values.


Views Contextual Filter Match criteria with contains instead of equal to When setting up contextual filters, its fixed setting is if the argument equals the result. I want to be able to choose if my result contains my argument string. How can this be done?

Try using Views Argument Substitutions

  Contextual Filters allow a View to be filtered based on arguments
  passed via URL or other embedded method (e.g. the View Reference
  module), but contextual filters are inflexible compared with normal
  filters (which allow for "contains," "begins with," "ends with,"
  etc.).

  This module allows contextual filter arguments to be used as
  replacement tokens in filters and table arguments, so that passed-in
  arguments (such as from URLs or View Reference fields) can be used as
  values in normal View filters.


Know field type usage I need to know if a field type is used on a website in a content type. How can I know that with Drush or Drupal BO?

This should give you a list of the fields and types on your site.

drush field-info fields

Should output something like this

 Field name               Field type            Field bundle
 body                     text_with_summary     page,article
 field_image              image                 article
 field_category           entityreference       article
 field_name               text                  article


Is it possible to automatically create a .install file for a module? I have a content type that I want to install as part of a module or install profile. Is there anyway to automatically create all the field_create_field and field_create_instances code that would go in hook_install or do I have to do all that manually?

Is there any other way to capture the settings of a content type so I can migrate it and include it in an install profile?

If it's just the field and field instances that you want converted ready for an install file (i.e. if Features is too overkill for you or you don't want the extra dependency), then Field Inspector will give you all the code you need for creating your fields in code.

  Field inspector provides an administrative user interface for the
  Field Info API. This allows users to select what information,
  formatting, and fields they would like to see, and provides output in
  a manner that can be copied into a module, or install profile into a
  hook_install, or hook_update_N function.


How do I make a mini-panel pane a title? I've been replicating some work, in mini-panels, that's already on my site. On one of the mini-panels there is a custom-content pane that is acting as a header. In the gear icon drop down there is a little option called 'Panel Title' that can be selected.

However, I cannot find this option for other custom panel panes I create.

The content of the already-made title page is simply a Title input.

Would anyone know how I can create this?

OK, found it.

It wasn't in the pane settings as I thought (I was looking through loads of Panel documentation). Right at the top of the Edit Mini Panel page there is a dropdown menu called Title Type. You can set this to 'From Pane'.


How to call a function in template.php through ajax from a page? I have a button in drupal page template. When user clicks on that it will write the text in the text box to a text file.

I have written a function for that in template.php file. I want to pass the value in text box to the function using ajax. But how can I do it? What url should i give in javascript ajax function?

I would recommend using the Ajax Framework in Drupal 7 core: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7.

You will need to create a callback through hook_menu which will return the html you want to load.

See the examples module for how to do this. The two functions show adding a link and using the 'use-ajax' class and creating a link using a render array:
http://drupalcode.org/project/examples.git/blob/refs/heads/7.x-1.x:/ajax_example/ajax_example_misc.inc

They both link to 'ajax_link_callback' which calls the other function ajax_link_response().

'ajax_link_callback' is defined in hook menu like so:

 180   // A menu callback is required when using ajax outside of the Form API.
 181   $items['ajax_link_callback'] = array(
 182     'page callback' => 'ajax_link_response',
 183     'access callback' => 'user_access',
 184     'access arguments' => array('access content'),
 185     'type' => MENU_CALLBACK,
 186     'file' => 'ajax_example_misc.inc',
 187   );


Add tag to db_insert? I want to do some debugging with a db_insert query. I tried to use the addTag() method, but I got an error:

$query = db_insert('nodes') ->addTag('my query');

PHP Fatal error:  Call to undefined method InsertQuery_mysql::addTag()

Is there a way I can tag this query or otherwise make it available to hook_query_alter?

Edit This query is not giving me the expected results, and I want to know why. To see why, I need to see the query with its values. Looking in the documentation for InsertQuery_mysql, it appears there's no getArguments() method.

Is there any way to see the values that are being inserted?

There are the children classes of Query:

class DeleteQuery implements QueryConditionInterface
class InsertQuery
class MergeQuery implements QueryConditionInterface
class SelectQuery implements SelectQueryInterface
class TruncateQuery
class UpdateQuery implements QueryConditionInterface

Only SelectQuery implements addTag method. However, if you realyl are creating query object just there, you wouldn't need a tag anyway. Tags are only useful for hook_query_alter, and you shouldn't need to alter query you just created.

Your best options, as far as I know them, are:

Enable query log in your database
Devel module with it's query display


How to trace down to find where a field has been removed/hidden of a particular node I am using a purchased theme provided by 3rd party (it is actually a custom Drupal build comes with their modules and theme). My problem is that image fields are hidden some where in the module(s) provided by this theme.

I am sure that the apartment.field_image is not removed in the template (neither by using any hidden() function nor by non printing the $content['field_image']. I came to this conclusion by observing the $content using Devel module as well as by using standard dpm() function. That field is just not there (node content) at all.

I have also made sure its not hidden in the display settings of this content type its "image".

I have checked rest of the code by searching for preprocess, field_image and image to see if they are manipulating it anywhere. I found many processor functions which were manipulating something else like adding css etc., but but I dint find any traces where they are hiding/unsetting/removing the field.

Please guide me how can I trace it. My mind is just blowing off. Thought I would get good sleep after a week but looks not the case.

some things to look at: make sure under display, that the type of display is set correctly (full content, teaser, default, etc). Check if field permissions or similar is installed and that the permissions for that field are set correctly. Check for any rules or actions that could be causing it to be removed.

another - is it in a field collection, display settings for those are shown under /admin/structures/field collections not under the content type


Placing Content Outside of Region Container My custom bootstrap sub-theme has a main content region which is the place that all the main content is to go within a .container class.

The code for that section is as follows:

    {# Main #}
    {% block main %}

            {% if page.sidebar %}
              {% block sidebar %}

                  {{ page.sidebar }}

              {% endblock %}
            {% endif %}

            {%
              set content_classes = [
                page.sidebar ? 'col-sm-9',
                page.sidebar is empty ? 'col-sm-12'
              ]
            %}

              {% if page.announce %}
                {% block announce %}

{{ page.announce }}

                {% endblock %}
              {% endif %}

              {% block content %}

                {{ page.content }}
              {% endblock %}

    {% endblock %}

Now I want to create a couple view blocks on my homepage within this main content region but I'd like the backgrounds and content to extend outside the main container and be 100% of the screen width.

Is there a way for me to do this with my current code or is there another way to go about this?

Following your structure one way could be:

Wrap your views block structure as shown below:

 #Section ends

 #Row ends

 #Container ends

        #Full width, out of container
        [View_block] #View block out of container
        #Full width ends

 #Container opens

 #Row opens

 #section opens
        # Rest of the content is in container...

This will maintain the original structure and places your views blocks outside of the container and within the main content.
Even if this block is turned off, the page will not break.

Please modify as per your final output.


No shipping rates found for your order I have created a Flat Rate Service and defined 10 dollars base rate. No calculation rules nothing else. But when I am trying to checkout

Shipping service
No shipping rates found for your order. Please continue the checkout process.

Do I need to define any calculation rules etc..

You do not need to define any calculation rules. The problem is that you are checking out when the rule doesn't apply to you. For example, if you do NOT have the role B and you are checking out, when you are checking if the user has the role B, you will get this message.


Using Drupal 8's Migrate API, how can I map a nested (hierarchical) taxonomy term to the imported entity? We have a vocabulary of nested (hierarchical) category terms on a site and are using the Migrate API (via CSV) to import product entities that each have a category term.

The problem is that some of the nested term names are repeated so the importer would not know which nested term to use. For example:

PARENT 1--Child 1
PARENT 1--Child 2
PARENT 2--Child 1
PARENT 2--Child 2

As you can see, the term "Child 1" is used twice, but with different parents.

I can see two possible solutions but I don't know how to go about achieving them. So any help would be appreciated.

1) Would it be possible to include the hierarchy in a delimited field on the CSV and let Migrate create and nest all of the terms and then map the product entity term referring to the last term automatically.

For example. "Parent 1, Child, 1, Child 2"

2) Or, using a source plugin and TWO fields on the CSV, where one is the product category term and the other field is the parent and somehow have Migrate know which parent term ID to use for the category?

Currently, the category YML looks like this:

 field_prod_category:
    -
      plugin: explode
      source: WebCategory1
      delimiter: ','
    -
      plugin: entity_generate
      source:
      value_key: name
      bundle: product_categories
      entity_type: taxonomy_term
      ignore_case: true

On my project, I created a group migration with two migrations

taxonomy migration all taxonomy term.
taxonomy_parent update parent for terms have parent.

There are example code (I use the embedded_data source plugin for the sake of simplicity so that this example can be copy-pasted as a working example ) and source like that:

Migration group: migrate_plus.migration_group.taxonomy.yml

id: taxonomy
label: Import Taxonmy
description: Import Taxonomy.

Migration all term: migrate_plus.migration.taxonomy.yml

id: taxonomy
label: Import term taxonomy
migration_group: taxonomy
source:
  plugin: embedded_data
  data_rows:
    -
      id: 1
      name: 'Parent 1'
    -
      id: 2
      name: 'Children 1'
    -
      id: 3
      name: 'Children 2'
    -
      id: 4
      name: 'Children children 1'
  ids:
    id:
      type: integer
destination:
  plugin: entity:taxonomy_term
  default_bundle: custom_taxonomy
process:
  name: name

Set parent for term: migrate_plus.migration.taxonomy_parent.yml

id: taxonomy_parent
label: Set parent taxonomy
migration_group: taxonomy
source:
  plugin: embedded_data
  data_rows:
    -
      id: 2
      parent: 1
    -
      id: 3
      parent: 1
    -
      id: 4
      parent: 2
  ids:
    id:
      type: integer
destination:
  plugin: entity:taxonomy_term
  default_bundle: custom_taxonomy
  overwrite_properties:
    - parent
process:
  tid:
    plugin: migration_lookup
    migration: taxonomy
    source: id
  pid:
    plugin: migration_lookup
    migration: taxonomy
    source: parent
  parent: '@pid'

and result:


How to disable a taxonomy term? I am interested in disabling-turning off taxonomy terms.I don't want to delete them so as to enable them later.
How is this possible to do?
thanks

I think I found the answer:With the use of Taxonomy manager module,I can move the term to another vocabulary(selecting Double Tree),and when I need the term I can again move to the original voacabulary.
cheers


Allow users to see own content only I have two content types, provider and products.

The providers is a list of titles filtered by logged in user (each user can only see the providers he enterd). By clicking the provider the user is taken to a page that contains a table with all the provider products.

the provider and the products content type are linked via a unite content field using contextual filter (the mutual field called lpid).

In the products page the path is provider/%/products while the wildcard represents the lpid field.

Everything works great, what I am trying to do is to prevent from users to see other users content.

Is there a way to pass the wildcard via $_POST so the user will not be able manualy change the url?

TNX

"Allow users to see own content only", You can achieve this using contextual filter and relationships in advance settings in views module, Given by you already set the contextual filter set filter to login user,

1.) In Advanced settings add field Content:author in relationships.

2.) Then in Contextual Filters add User: Uid and choose provide default value and set Provide default value Type User ID from logged in user.


Please help with this query! Need to get taxonomy terms of related nodes I've inherited this code that runs on our home page. It's used to do a custom display of specific pieces of related info. Here's how things are set up:

We have an article. It has a series of node reference fields that allow us to link related images (actually nodes themselves, which contain a headshot and some text; it's not an actual attached image.) Each of those headshots has a thumbnail created via ImageCache so that we can display a small version in search results and on list-type pages.

We have a new requirement that if the related image node for a specific article has a certain taxonomy term (tid) associated with it, it should display differently than other images.

The existing query (which I did not write) looks like this:

SELECT DISTINCT n.title, nr.teaser, n.nid, DATE_FORMAT(FROM_UNIXTIME(n.created), '%M %e, %Y') AS date, f.filepath AS image, cfri.field_related_images_nid as image_id

FROM node n JOIN node_revisions nr ON n.nid = nr.nid
LEFT JOIN content_field_related_images cfri ON (n.nid = cfri.nid AND cfri.delta = 0)
LEFT JOIN content_field_att_file cfaf ON cfri.field_related_images_nid = cfaf.nid
LEFT JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn2 ON n.nid = tn2.nid

WHERE n.status = 1 AND n.type = 'article'   AND nr.body LIKE '%kimberly-clark%' AND tn2.tid = 143 ORDER BY n.created DESC LIMIT 3

This returns a recordset that looks like this:

TITLE         |  TEASER           |  NID |  DATE            |  IMAGE                            | IMAGE_ID
==========================================================================================================
Exec Profile  |  Could you please | 67491 | April 29, 2011  | sites/default/files/kcjones.jpg   | 67572
Unilver Ads   |  Unilever topped  | 67421 | April 20, 2011  | sites/default/files/unilever.jpg  | 66889

This is all well and good. But what I need to do is (in the same query, somehow) also return the tid that goes with the image_id from the term_node table. On its own for a single image node that query is simple:

SELECT tid FROM term_node WHERE nid = 67572

But how do I modify the existing query to bring in the tid based on the image_id found in the main part of the query? I'm guessing I need some kind of subquery, but this is stretching the limits of my sql chops...

You already have the {term_node} table joined in your query so I'm pretty sure you should just be able to change your first line to include tn2.tid. Try this:

SELECT DISTINCT n.title, nr.teaser, n.nid, tn2.tid, DATE_FORMAT(FROM_UNIXTIME(n.created), '%M %e, %Y') AS date, f.filepath AS image, cfri.field_related_images_nid as image_id
FROM node n JOIN node_revisions nr ON n.nid = nr.nid
LEFT JOIN content_field_related_images cfri ON (n.nid = cfri.nid AND cfri.delta = 0)
LEFT JOIN content_field_att_file cfaf ON cfri.field_related_images_nid = cfaf.nid
LEFT JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn2 ON n.nid = tn2.nid

WHERE n.status = 1 AND n.type = 'article'   AND nr.body LIKE '%kimberly-clark%' AND     tn2.tid = 143 ORDER BY n.created DESC LIMIT 3


How to show only an image of the YouTube video while using Media: YouTube module? Is there a way to show an image of a youtube video instead of the actual player ? This would be done only for the teaser view of the node.

I know that I can show a video thumbnail, but I need an image that looks like the actual player.

Thanks.

If you can grab the id of youtube video then you can use following pattern of url to get  a bigger youtube thumbnail.

http://img.youtube.com/vi/[your video id]/0.jpg


How to place the page title and local tasks tab in a Panels region? Is it possible to move the displayed page title (h1) and the local task tabs below it (the 'view' and 'edit' node tabs) to a region? Panels displays these by default for node/% page overrides.

I can add the local task tabs to a region of my choice, but I can't see how to remove the default node local task tabs.

And while I can set the page variant to 'no title', that's not really what I need, I want to define the region where it should be shown. I can add the 'Page title' from the page elements Panels content in the region I want, but it is empty when I set the page variant to 'no title'. I could add the title field and wrap it in h1 tags myself so I can use the 'no title' setting, or hide the first occurrence of the h1 with css and use the extra 'Page title' element, but it seems there should be a better way.

If you're just wanting to do that for a single variant, you may need a combination of panels configuration, e.g adding local tasks and page title to region as well as either hook_preprocess_page or perhaps hook_ctools_render_alter to remove the page title and tabs from default output based on path or other criteria.

For example:

template.php

/**
 * hook_preprocess_page
 * Alter variables for the page template
 */
function THEME_preprocess_page(&$vars){
  // If on a node page
  if ($node = menu_get_object('node')) {
    // Remove page title and menu tabs for this node type
    // as they're output in the panel variant instead
    if ($node->type == 'my_type') {
      $vars['title'] = FALSE;
      $vars['tabs'] = FALSE;
    }
  }

}


How can I make a slideshow with tabbed navigation/menu? I'm trying to make a slideshow that looks something like this

I'm using views slideshow but I could change it up if need be. Preferably views though.

My problem is the navigation to the right. I have created a content type for this slideshow and fields for the image, the green title and the black subtitle. The slideshow should run by itself and highlight the proper menu item in the sidebar, but also allow for the user to change slide by clicking a menu item.

Any ideas on if and how this could be done?

In most Views slideshows I've seen, the navigation is just part of the normal slideshow, but themed to not overlap, unlike the images.

Configure the View to select whatever information you need in the navigation, end then make your theme place the navigation to the right.

I would be surprised if VS does not already have functionality for connecting clicks on some elements with sliding to a certain image, but I don't know the ins and outs of the module enough to give more specific recommendations.


How to add comments per picture in a photo album? I have an activities content type that I want to add a photo gallery to (in the same content type). However I want comment capabilities per picture. How can I achieve this?

Would build this by creating a single content type with only one picture per node with the comments turned on just as you did.  Then build a view for your gallery with the comment as a link included.


Is there a module or technique to display blocks or panels based on device width? We have our ads set up as blocks or panels and we would like to prevent wide ads from rendering on narrow (mobile) devices. Additionally, we would like to render other ads only on wide (desktop) devices.

I'm new to drupal and new to the website in question, and I'm having trouble finding where the actual ad calls are made, so I figured the best solution would be to handle this at the block/panel level.

To be clear, I am trying to prevent the ads from even rendering, not just trying to hide them from view once rendered.

How about using the Themekey and/or Mobile Detect for switching mobile and desktop version of themes? Here is a quote about these modules (from their project pages):

Themekey:

ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.
... in combination with Drupal's theme inheritance you can easily achieve features like ... "mobile themes for different auto-detected mobile devices".

Mobile Detect:

... intended to aid developers utilizing mobile-first and responsive design techniques who also have a need for slight changes for mobile and tablet users. An example would be showing (or hiding) a block or content pane to a particular device.


Reinstalling CKEditor module I installed the latest recommanded release of CKEditor, but when I tried to change content authoring I got an error saying it wasn't installed properly.

So I tried uninstalling it by doing:

disable module ckeditor
uninstall
tried to look for the    module in my project and    delete there
also (site/all/modules) but it isn't present

When I trie to reinstall (dev version) I get:

Archivers can only operate on local files:
temporary://update-cache-235f2e3c/ckeditor-7.x-1.x-dev.tar.gz not
supported
and then when I trie the same link a second time:
CKEditor is already installed.

Also clearing the cache in development doesn't work.
How can I properly delete and reinstall ckeditor?

Disable the Module
Uninstall the Module
Delete the Module folder from sites/all/modules
Remove the CkEditor folder from site/all/libraries
Clear the Cache
Copy the CkEditor Module to site/all/modules folder
Copy the Downloaded CkEditor to sites/all/libraries folder
If in *nix systems, check the folder permissions. (Most of the time this happens to be the issue)
Enable the Module as usual.

More info is given CkEditor docs


How to redirect links to a single domain in a multi-domain setup? I am working on a project that uses Domain Access. The site has two domains one public(example.com) & one for members(example.com/members).

Some contents are common to both domains and some are domain specific.

Any link rendered on webpages has a relative path to that domain.

eg. A page that is displayed on both sites has the link (/some/link). Clicking it would take you to example.com/some/link if you click it on example.com AND to example.com/members/some/link if you click it on example.com/members

There are a few links that I want to appear on both domains but they should redirect to the members domain only.

eg. for the case described above the link should redirect to example.com/members/some/link even if it is clicked form the example.com domain.

Is there a way to do it?

UPDATE:

These are subdomains example.com & members.example.com. There is some server-side settings for url rewrite that makes them appear as example.com & example.com/members in URL.

There is a special module for that: https://www.drupal.org/project/domain_path_rewrite.

The idea is to automatically rewrite the relative links to the absolute ones so they always point to the proper domain. Something like:

/**
 * Implements hook_url_outbound_alter().
 */
function domain_path_rewrite_url_outbound_alter(&$path, &$options, $original_path) {
  if ($domain_path = _domain_path_rewrite_domain_path($original_path)) {
    $path = $domain_path['url'];
    $options['external'] = strpos($path, '//') !== FALSE;
  }
}

Of course, is's only possible if you're printing the links programmatically. Otherwise nobody knows to which domain the links belong to and most likely you need custom rewrite rule.


How do I set up an entityreference entity base field to show as a link to the target entity? I have a base field on my entity type that's an entity reference, e.g.:
    $fields['type'] = BaseFieldDefinition::create('entity_reference')

How do I set this up so it displays as a link to the target?

->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'entity_reference_label',
        'settings' => [
          'link' => TRUE,
        ],
      ])

and optionally to allow it to be configured in the UI:
      ->setDisplayConfigurable('view', TRUE)


Update Computed field with hook_cron I have a field age in profile of my Drupal Instant which computes age from the D.O.B of the user. How do I make sure the age is updated along with cron job. Is there any way to trigger.

Right now I believe it will only update when the profile is saved.

From your question, by hook_cron() this can be done. You can use a watchdog() function to make sure that the cron was run. The computed field has a table entry in the database, so you just need to find out that one and check each user's birthday from a DOB field stored in another table based on UID. Then if the user has updated the DOB then check for their ages and insert/update the value in the "field_age" computed field. All of the operation can take place in hook_cron() which will be invoked by cron.php each time the page is fired in crontab.


Undefined index errors when running cron.php I am getting a slew of errors when I attempt to run a cron job following my hosting company's instructions. From researching the errors, I suspect the instructions are wrong. But their support is telling me this is a development issue and they can't help me. So I hope someone here can tell me the correct way to run cron in this environment.

The site is running without error. Cron runs successfully by using "admin/reports/status/run-cron" or by using the URL provided for running cron from outside the site.

The instructions say to use the following command:

cd /home/username/public_html && php /home/username/public_html/cron.php >/dev/null 2>&1

This fails silently, meaning that nothing happens that I can see, but the status report does not indicate that cron has run. So I removed the ">/dev/null ..." part in order to allow the system to send me a result e-mail. Thus the command I'm using now is:

cd /home/username/public_html && php /home/username/public_html/cron.php

When this command executes, I get an e-mail with hundreds of errors, mostly like:

Notice:  Undefined index: argc in /home/username/public_html/includes/bootstrap.inc on line 3407
Notice:  Undefined index: SCRIPT_NAME in /home/username/public_html/includes/bootstrap.inc on line 1622

I found a forum post about the same kind of problem, and the offered solution was to "Use a URL to cron.php with wget or curl." Unfortunately, my Unix is rusty and I don't know how to do that.

Can someone suggest how to modify the command in the host instructions so that cron will run correctly?

Thanks for your help.

You shouldn't run cron.php throught php cli. basically you should have a line like this in your crontab file:

0 * * * * wget -O - -q -t 1 http://www.example.com/cron.php

but you also need to append security token to the url.

by reading Configuring cron jobs using the cron command page you will get a better idea of how it works.


How to get an generic image icon for image field type (like Generic File formatter for file field) I have media field on a paragraph entity.
This field can hold media types, files, image etc.

Looking at admin/structure/media/manage/file/display there is a generic file formatter. However, for image - admin/structure/media/manage/image/display there is not.

So when the data is rendered, I get generic icon for word documents, but not images.

How can I get all my media items to render as generic icons?

It seems this issue is being worked on at : #2568289: Not possible to reuse field formatters between entity_reference, file, and image fields
For now I've used the following code - included in the mytheme.theme file. (view mode custom_generic_file)
use Drupal\file\Plugin\Field\FieldType\FileItem;

/**
 * Implements hook_preprocess_field().
 */
  function mytheme_preprocess_field(&$variables, $hook) {
    __mytheme_preprocess_field__generic_download_icons_view_mode($variables, $hook);
  }

/**
 * Ensure generic icon view mode for image media entities.
 *
 * Image field type doesn't have a generic file formatter.
 *
 * Called by hook_preprocess_field().
 *
 * @see Drupal\file\Plugin\Field\FieldFormatter\GenericFileFormatter::viewElements()
 * @see https://www.drupal.org/project/drupal/issues/2568289
 */
   function __mytheme_preprocess_field__generic_download_icons_view_mode(&$variables, $hook) {
  if (isset($variables['entity_type'])
    && ($variables['entity_type'] == 'media')
    && isset($variables['field_type'])
    && ($variables['field_type'] == 'image')
    && isset($variables['element']['#view_mode'])
    && ($variables['element']['#view_mode'] == 'custom_generic_file')) {

    foreach ($variables['items'] as $key => $item) {
      /* @var Drupal\image\Plugin\Field\FieldType\ImageItem */
      if (isset($item['content']['#item']) && $item['content']['#item'] instanceof FileItem) {
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
        $entityReference = $item['content']['#item']->get('entity');
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
        $entityAdapter = $entityReference->getTarget();
        /** @var \Drupal\Core\Entity\EntityInterface $file */
        /** @var \Drupal\file\Entity\File $file */
        $file = $entityAdapter->getValue();
        $item['content'] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => NULL,
          '#cache' => [
            'tags' => $file->getCacheTags(),
          ],
        ];
        // Replace for real.
        $variables['items'][$key]['content'] = $item['content'];
      }
    }
  }
}


Drupal on custom page? I created a .php page outside of Drupal. On that page I want to check if a user is logged into my Drupal site.

Is that possible?

If the PHP file is in the same directory where cron.php, and index.php files from Drupal installation are, then you can use the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}

If the PHP file is in another directory, then you should use the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', 'the directory containing the includes directory from Drupal');
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}


Adding new text field to drupal 8 menu I am trying to add a new text field to the menu in Drupal 8, and I have done it using the instruction in the following post:

Add field(s) to menu link?

function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface
$entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['location'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Location'))
      ->setDisplayOptions('view', ['label' => 'hidden', 'type' => 'string', 'weight' => 0, ])
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

But I am not sure how to go about using hook_update_n to update the schema to reflect this change.

function menu_link_content_update_8201() { 'what do I put here to add the new field that I created'? }

I was able to workaround this issue by manually adding the location column in the mysql db and I can see the field showing up in the menu link editor and able to load and save it just fine in the cms UI.

But then I am not sure how to access this field in the twig file.

Any help would be grateful.  Thanks!

You only need an update hook if you want that your module can be updated on production sites already using the module. If you write a new module or the module is still in development you can simply reinstall the module. If you have data you want to keep during development use drush entity-updates after changing the code of the installed module.


how to inject dependencies into an access controller? I am altering an existing route and adding a custom access. The custom access is a method that I want to have it in it's own access controller:

  /**
   * Alters existing routes.
   */
  public function alterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    if ($route = $collection->get('entity.node.clone_form')) {
      // Add custom access
      $route->setRequirement('_custom_access', '\Drupal\eclone_extras\Controller\EcloneExtrasAccessController::access');
    }
  }

Then in my access controller I have:

namespace Drupal\eclone_extras\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class EcloneExtrasAccessController extends ControllerBase{

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity type ID.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * Constructs a new ContentEntityCloneBase.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param string $entity_type_id
   *   The entity type ID.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, $entity_type_id) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeId = $entity_type_id;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $container->get('entity_type.manager'),
      $entity_type->id()
    );
  }
  /**
   * Custom access checker for the create lock requirements route.
   *
   * @see \Drupal\content_lock\Routing\ContentLockRoutes::routes()
   */
  public function access() {
    // do access stuff
    return TRUE;
  }

}

But I keep getting the following errors:

0 passed in /var/www/drupal8/web/core/lib/Drupal/Core/Controller/ControllerBase.php on line 118 and exactly 2 expected in Drupal\eclone_extras\Controller\EcloneExtrasAccessController->__construct() (line 36 of modules/custom/eclone_extras/src/Controller/EcloneExtrasAccessController.php).

This can be done using services. Here's an example which injects the entity type manager interface.

eclone_extras.services.yml:

services:
  eclone_extras.access:
    class: Drupal\eclone_extras\Access\EcloneExtrasAccess
    arguments: ['@entity_type.manager']

Route subscriber:

 /**
   * Alters existing routes.
   */
  public function alterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    if ($route = $collection->get('entity.node.clone_form')) {
      // Add custom access
      $route->setRequirement('_custom_access', 'eclone_extras.access::access');
    }
  }

Access class:

namespace Drupal\eclone_extras\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

class EcloneExtrasAccess {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ContentEntityCloneBase.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param string $entity_type_id
   *   The entity type ID.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * Custom access checker for the create lock requirements route.
   *
   * @see \Drupal\content_lock\Routing\ContentLockRoutes::routes()
   */
  public function access() {
    // do access stuff
    return AccessResult::allowed();
  }

}

The access callback gets some parameters as well, such as Account and possibly request.

Refs:

https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes


How to create table view with progress bar? I want to create a tabular view with progress bar. The drupal-6 view consists of goals of activities I need to do. I have created a content type called Goal that is composed of activities/task. I want to list the goals in a tabular view and show a progress bar in one of the column that indicates how many task/activities under the goals have been completed. How can I do it?

You either need

A custom views field
A themed/templated existing field.

A good option in D7 for progress bars is jQuery UI progressbar ( API docs here ), as it's shipped with core.

You can add the required JS with

drupal_add_library('system', 'ui.progressbar');


Create if logic with fields My task is to create a field that is visible to the author node.

Let's say the content type is "article" and the field is "textid" that contains the node ID number.

I've already created it with Display suite as a custom field with token [node:nid], so the result is some text with number of the node ID.

How can I make that field visible only by the node author?

What hook should I use?

You can simply use Field Permissions module:

  Author-level permissions allow viewing and editing of fields based on who the entity owner
  is.

This seems to be exactly what you need.

To have real field (not display suite element), you can use Computed Field - more complicated than Display Suite, true, but at the same time more versatile and integrates well with everything field-related.

On the other hand, you can forget all these modules, and in your node.tpl.php simply compare current user id with node author's id, and if they are equal, print your data.


How can I programmatically validate that an user has uploaded an image in CCK? I have an image field defined using CCK.  I need to detect or validate that the image has been uploaded.  Is it possible?

Thanks to all.

You may have to use hook_form_FORM_ID_alter().Define your own module and in your module try the following code

function yourModuleName_FORM_ID_alter(&$form, &$form_state) {
  $form['#validate'][] = 'yourModuleName_FORM_ID_validate';
}

//your validation function
function yourModuleName_FORM_ID_validate($form, &$form_state) {
  if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['machine_name_of_the_cck_field'])) {
    // File uploaded
  }
  else {
    //File not uploaded
  }
}


Close webform error messages I'm using the webform module for a contactform. But when the submission doesn't validate the user can't click away the alert box.

×

Look's like there is no js function attached. Is there a setting in the module for closing the alert box or should you implement it yourself?

I found a neat little module the other day called Message Close which once installed, adds a simple close icon to every message, whether status or vaildation. It also resets all margins and padding so once a message is closed, the page looks exactly as it does on a fresh load.

In the js of the module, you can use jquery to make the message fade out, or slide out.

This would be perfect for closing webform validation messages without needing a page reload.


How do I add an OR expression between two ->addExpression() in Drupal 7 I am trying to return flagged content that is either flagged as a favorite or flagged as visited. I can get them to return but i believe Drupal is doing an and between the 2 addExpression() in the query because it is only showing results if either both are flagged. Not one or the other.Here is my code. This is being used for the Drupal Services module to return some values. Any help would be greatly appreciated.

$query->leftJoin('flag_content', 'flag', "n.nid = flag.content_id AND flag.uid = $user->uid");
$query->addExpression("flag.fid is not null AND flag.fid = 2", "is_flagged");
$query->addExpression("flag.fid is not null AND flag.fid = 3", "is_visited");

addExpression() is for adding expressions to the query, (i.e. fields that will be selected), you can't use it to add conditions.

You could either use a combination of db_and() and db_or() to build up your conditions, or (and probably easier) just use the where() method instead:

$condition = '(flag.fid is not null AND flag.fid = :fid1) OR (flag.fid is not null AND flag.fid = :fid2)';
$query->where($condition, array(':fid1' => 2, ':fid2' => 3);