What is the difference between an entity in Drupal 7 and a content entity in Drupal 8? The Drupal Examples "entity" project was really helpful for me when I was learning the entity API in Drupal 7. I have seen no explanation though for why this doesn't exist in Drupal 8 or why it was renamed, etc.

I'm not sure what you are asking.

Example modules are named after what they're an example of, it's not for them to pick a name, really.

Drupal 8 has Content Entities, which evolved from the field structure of Drupal 7's entities and Config Entities, which are based on concepts from ctools exportables, entity.module's exportable entities and various other things.

Both share the same base class and a few comments and concepts but beyond that, they're quite different. Both are typed classes, Content entities have a strict although somewhat complex structure but are very extensible within that structure (That is, Entity -> Field Item List > Field Item > Property). They can have revisions and translations which are conceptually similar to field translations in 7.x but have a different API.

While there isn't that much documentation yet, https://www.drupal.org/developing/api/entity has some, there are also plenty of presentions from DrupalCons and other events about the concepts, API's and so on, including a recent one that I co-presented: https://2015.drupalcamp.at/session/entities-drupal-8.


Custom prefix for each value of a multi-value field I have a number field where a user needs to enter two values. Each value should have a custom prefix but that isn't possible within the field settings.

Does anybody know how this can be done? Thanks.

You can use form_alter function to do it:

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_number'][LANGUAGE_NONE][0]['value']['#prefix'] = '$';
    $form['field_number'][LANGUAGE_NONE][1]['value']['#prefix'] = '€';
  }
}


Get default value of a node field I have a field on a node which has a default value set, I need to access the default value of that field. But, I don't want to load any nodes of that type and access the field definitions, nor do I want to manually write a db_query and fetch the value directly from the db, I know there is a proper way to do it I just don't know of it.

Drupal 8.6.x

Use FieldDefinitionInterface::getDefaultValueLiteral:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (isset($definitions['field_example'])) {
  $default_value = $definitions['field_example']->getDefaultValueLiteral();
}


Remove lingering configuration data in block plugin I built a custom block plugin but after updating it there are configuration items that I no longer need. But removing the part that saves the configuration data in blockSubmit submit function doesn't actually remove the configuration data that existed before.

My original blockSubmit function was as follows

public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['row']       = $form_state->getValue('row');
        $this->configuration['columns']   = $form_state->getValue('columns');
}

But now I only want to store $this->configuration['columns'] like below

public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['columns']   = $form_state->getValue('columns');
}

Is there a way to delete the configuration data in $this->configuration['row'] ?
I don't mind it being a work around since I'm only going to be using it once. I wouldn't mind doing something like delete($this->configuration['row']); in the build function so it's removed when you visit a page that contains it.

Is there a way to remove this lingering configuration data in this block plugin?

There are several options.

You can unset the configuration 'row' in submit:

unset($this->configuration['row']);

You can load each block, remove the item from settings and save it. See https://drupal.stackexchange.com/a/224362/47547 how to load blocks. You can do this in an update hook.

You can export the configuration, remove the lines you don't want from the yaml files and import the configuration again. This would be the best option for a site owner who wants to clean up a single drupal installation.


Multiple Sticky Items within using 2 separate views I have 10 nodes and 2 views, one view named highlighted nodes, the other - other nodes

I created the concept that if a user sets one of their nodes to appear "sticky at the top of lists" then it would appear in the highlighted nodes view.

My second view outputs the rest of the nodes with an offset of 1 i.e. skipping the first node that I assumed "there will only be one" node that was set to sticky at the top of lists

My question is, how do I cater if two nodes are set to "sticky at the top of lists". Could you offer a solution?

Thanks in advance

You have to add a filter, for the view highlighted nodes:

Content: Sticky at top of lists (= Yes)

and for the view other nodes:

Content: Sticky at top of lists (= No)


Apply formatting to tables generated by tablefield module I am using the tablefield module to allow the user to create a "programme schedule" in a table format. The only issue I'm facing now is that the user would like to be able to apply text formatting like bold or italics to certain fields.

The only thing I can think of is styling through CSS, however, given the dynamic nature of this table, it does not seem very feasible. Is there any other table modules that could provide such functionality?

I haven't installed the module, but from the code it looks like there's an option in the field settings called "Table cell processing" in which you can allow the user to select what Input Format they want. This makes use of Drupal's text formats (Admin > Configuration > Content Authoring > Text formats). You could allow them to use HTML within the cell, or install some alternate Text Format module such as BBCode.


Generating Ubercart orders programmatically I am trying to generate ubercart orders programmatically in Drupal 8 and am doing it this way:

$order = Order::create(array(
  'uid' => $uid,
  'order_status' => uc_order_state_default('in_checkout'),
));
$order->save();
$product = Drupal::entityTypeManager()->getStorage('uc_order_product')->create(array(
  'qty' => 1,
  'order_id' => $order->id(),
  'nid' => $product_nid,
  'title' => $product_node->get('title')->value,
  'model' => '1001',
  'cost' => $product_node->get('display_price')->value,

));
$product->save();
uc_order_product_save($order->id(), $product);
$order->save();

Can someone please suggest what wrong I am doing here? Do I need to extend to some class in particular? This order is not generated.

I was able to resolve this by adding these to my file:

//for order
use Drupal\Core\Form\FormBase;
use Drupal\uc_order\Entity\Order;
use Drupal\user\Entity\User;
//for products
use Drupal\uc_order\EditableOrderPanePluginBase;
use Drupal\uc_order\Entity\OrderProduct;
use Drupal\uc_order\OrderInterface;


See a list of fields and what content types they are attached to I am trying to troubleshoot an issue with Panels. In one of the content panes, there are token replacements from a field.

I looked at the context menu for the page, and it was provided by a taxonomy. I'm assuming this is a field on a node, but I don't know which one.

We have a number of content types and taxonomies on the site. Is there a way, perhaps through a module, to see a list of all the fields that are on the site, and which content types they are attached to?

I'd like to avoid looking through the fields of each content type one by one, if possible.

You should be able to go to Admin > Reports > Field List and see a list of fields in the system and their types and what is using it.


Import content to ckeditor correctly I imported large number of articles from another CMS to Drupal 8.

The content is in HTML and when i open a page i have html not interpreted.

How do i tell Drupal/Ckeditor that the content is in HTML ?

For now the only thing working is when i edit an article and clic on source twice to get the HTML interpreted but i can't do that to the large number of articles that i have.

It was simple after all in the table node__body there is body_format and you should set it to full-html


New URL for the node overrides the URL of existing node using pathauto module I'm using Pathauto module to set the URL for the nodes in my site. I have already created about 20,000 nodes in my site. Usually, the Pathauto module doesn't allow to the users to create the node with existing URL by giving the error as "Path already in use". But in my case, I can change the URL of a node with an existing URL of a node. For example parks located in same country,

Gandhiji Park - /gandhiji-park (located in state1)

Gandhiji Park - /gandhiji-park-0 (located in state2)
I can change the URL of the park in state2 as /gandhiji-park and the node is saved in that URL.

If I search for gandhiji park in state2 the search filters out the park but the URL took me to park in state1.
Can anyone help me in this?

I faced the same problem in my website.
As you mentioned in your question :

  Usually, the Pathauto module doesn't allow to the users to create the node with existing URL by giving the error as "Path already in use"

This is true only when you hand code the URL alias. If "Generate automatic URL alias" box is checked then similar URL's are appended with numbers at the end (like in your case).

The method I used to prevent this problem was to install a module called Unique field which makes sure the no 2 nodes have the same title(and thus unique URL for each node).

In your case, since the damage is already done, the best option for you is to change your title or url to something like /gandhiji-park-state-2

Suggestion :

This is just a suggestion for URL structure and SEO. A general rule of thumb that I follow when creating URL, is to rank the keywords in the URL. The highest ranked keyword should come at the end of the url. For example www.example.com/less-specific-keyword/more-specific-keyword. This way you can rank higher in search engines for the same content and also users can get an idea about your content just by looking at the url.
For example, in your site you can structure the URL like this www.example.com/state/park/park-name.


What is the use of "Add view from template"? As when we select the view options three links appears but I don't understand what is the use of "Add view from template"

because when we click on this link we get this one...

and after further proceeding normal view is created. so what is the use of that link?

Modules give you some templates to work with instead of having to figure out the dirty details yourself.

For example:

You have the image module installed, so they give you a gallery template to work with. of course you're not obligated to use it but it's there.

If you download the Calendar module it will give you a bunch of templates as well.

There are several modules that give you templates to work with. And if you write your own custom modules, you to have access to create templates for users to use if you wish to.


How to check if a user has any previous order? I am working on Drupal Commerce site. Want to know if the customer is new or old. If customer has previously ordered any item from our website we can consider him old customer else if he is ordering first time he will be considered the new customer.

How can I get these values in a custom module?

Try this method. commerce_order_load_multiple will return order

function module_user_has_order() {
    $order = commerce_order_load_multiple(array(), array('uid' => 'user_id','status' => 'completed'));
  if(empty($order)) {
    //user has no previous order.
  }
  else {
    // user has previous order.
  }
}

Hope it works for you.


how should I add textfield ie jump pagination in views mini pagination of drupal I have created views of gallery by view. View has provided pagination option. I choose mini pager.

I want to implement Jump Pagination here. How should I add in view pagination?

Try the Pretty Pagination module . I think This is what you are looking for.

This module extends the default pagination into a more flexible format. It allows the user to jump to any specific page in the content just by entering the desired page number in an input box and hitting the ENTER key. The result is easier navigation, especially with sites where the content is spread over numerous pages.

Another module is
Pagerer module. Using this module you can give direct input of the page to go to through a jQuery UI Slider.

Pagerer is a module providing a collection of pager themes to enhance Drupal and Views standard pagers.
Features:

multi-pane pager

Views pager plugin

control whether to display links to pages, to items, or to item
ranges

direct input of the page to go to through an input widget

selection of the page to go to through a jQuery UI slider

selection of the page to go to through a client-side scrolling pager

links to progressively more distant pages (like +10, + 20, +100,
+200)

adaptive logic links

specify text to be used to render page separators (like a vertical
bar) and page breakers (like an ellipsis)

supports Views' AJAX enabled pager


Using References module, is it possible to only show nodes created by the logged in user in select list? I made a node reference field and it gives me a select list of all the nodes of a specific content type. However I only want the select list to show the nodes made by the logged in user. Is there any way to set conditions some way?

You can try making a views which return the list of all node title created by the user & then use View reference module to have field calling that.


Views Error - Views folder is empty I have a drupal site on remote server.
The site is working properly right now.

I just check and the views folder is empty!!

I looked into the ftp, and also on the remote server it looks like the views folder is empty.
The site works perfect currently with many views, but it looks like the views folder under public_html/sites/all/modules/views is empty.

When I checked the permission it say "0711". and it says that owner can read edit and everything..

How that can be that I see empty folder?

The problem was that the views folder was on the ROOT/modules folder, and not on the ROOT/sites/all/modules folder.


Strict warning Error I am getting this error when I create a new wiki...does anyone have any idea why this is happening and how to solve it?

  Strict warning: Creating default object from empty value in
  PanelizerEntityDefault->hook_field_attach_submit() (line 1113

Thanks!

It is a bug. However, there is a workaround for it.

In admin/config/content/panelizer make sure to mark "Panelize", "Allow Panel Choice", and "Provide Default Panel".

Here is a link to where i found the solution


Page node edit content-type How I can customize the node edit page? I need to use a custom template for it.
page--node--add-content-type.tpl.php works fine, but --edit--content-type.tpl.php doesn't.

You need to use function hook_preprocess_HOOK.

function themeName_preprocess_page(&$vars) {
    if (!empty($vars['node']) && arg(2) == 'edit') {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $vars['node']->type .'__edit';
  }
}

This allowed me to use: page--node--[contentType]--edit.tpl.php

Clear cache.


Taxonomy Filter with parents and child of select parent dropdown`s On my website i have pet type (dog, cat, rabbit...) those are taxonomies, and every pet type has its own child taxonomies called pet breed. So lets say we selected in first dropdown dog, in second dropdown i want to list dog breeds.

I have tried with http://drupal.org/project/hierarchical_select but i cant make it work.

I tried with Views but still my exposed filters doesnt show at all on Preview or in Block...

Any help would be nice. I tried searching but no luck...

http://www.pets4homes.co.uk/ this is what i want to acomplish same thing as that filter they have but just without taht location field.

the hierarchical select module is the correct solution for this purpose, why it does not work with you?

Setup steps:
1- add the module folder to sites/all/module
2- go to modules page and enable hierarchical select
3- add new field (Term reference) into your content type with (Hierarchical Select) widget type.


7 allow cross-origin framing CORS module I am embedding content in my article that are from the same domain. when I am opening my url with HTTP the embedded HTTPS content won't open and when I am opening my url with HTTPS the embedded HTTP content won't open. Same thing happen when i try to open content with localhost. I am getting this error in Firefox and Chrome:

Load denied by X-Frame-Options: http://mywebsite.com/embed/clips/sandy does not permit cross-origin framing.

OR

 Refused to display 'https://mywebsite.com/embed/clips/sandy' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

I installed the CORS module but it does not seems to help. In Domains (/admin/config/services/cors) I added:

*|<mirror>,https://mywebsite.com
*|<mirror>,https://mediamatters.org

without success. Any insight is apreciated.

https and http -- even if the host is the same -- are considered different domains.

The way you can deal with that when your site can be viewed with both https and http, is instead of referencing files
https:// or http://
just use //
It will defer to the protocol that you are on.

The only time this would cause problems would be if a certain resource only got served up under secure or insecure. But this does not sound like it would be a problem for you in this instance.

EDIT:
In order to change existing content, which it sounds like doing by hand is impossible. You could try a module like https://www.drupal.org/project/scanner -- being careful to backup, test, and make sure you are only looking at the correct URLs (you don't want to change the urls where changing the protocol would be).

One other possible way to make it work is to just make your path references root relative -- strip out http://yourdomain.com - and just leave /your/path/to/file

The other thing to do is just cherry pick the content that people are looking at most.


new content type permission I created a content type called: Spreed Sheets. Then in /admin/people/permissions I make sure I checked these 3 permissions for authenticated users :

  Spreed Sheets: Create new content

  Spreed Sheets: Edit own content

  Spreed Sheets: Delete own content

then I loged in with an authenticated user (not admin) and I only have access to node/add/spreedsheets but when I'm login with admin and want to add another content type such as article from admin/content/add content it always redirect me to node/add/spreedsheets !!what should i do to give back the full permission to admin?

If you want to create content-type (not content) then this is link admin/structure/types where all content types are listed (in drupal7). But If you are talking about create content then you can add content node/add here all types will be listed.


How to automatically generate a random url for a views rss feed? I have an administrative RSS feed generated by views in a feature that needs to generate a random/unique URL so that non-admins can't easily stumble upon it. I know that after installing the feature, the user can easily manually create the URL, but this will override the feature and put it in the DB, making updates troublesome. Thoughts?

Just configure the menu path for the page/feed display of your view to include a "random" token. You can set them to be whatever you want.

Users will require the token to trigger the menu item and therefore view. You can rotate the token by simply updating the view (though it's a manual process).

If you need to automate rotating the token, you could build a module that hook_menu_alter's  access callbacks (yourmodule_access) onto the desired paths that checks the token (variable_get) that a hook_cron periodically updates (variable_set) and mails out to appropriate admins (users with some role). This has added benefit that it's not limited to use with Views. Though that's a bit complex for providing obscurity.

Also, many RSS readers support HTTP basic auth (via adding username:password@hostname to the feed URL), so you could install a contrib module that adds support for logging in via HTTP Basic.


Add AJAX popup multistep form I am trying to build an AJAX popup for my custom built multi-step form using the form API. I have examined the module "Modal forms" and wondering if i should use that module or just create the AJAX functionality from scratch. Could someone one please give me an example of how I can add AJAX popup functionality to my form?

Here is an illustration of what I would like to achieve:

I have been looking at the Chaos tool suite module example:

ctools_include('ajax');
ctools_include('modal');

// Add CTools' javascript to the page.
ctools_modal_add_js();

// Create our own javascript that will be used to theme a modal.

I have found this code snippet. I am trying to get it to work in my module.

Here is the code I found

function redirect_custom_reg_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array(
      'redirect_custom_reg_user_register_form'
    );
  }
}

function redirect_custom_reg_user_register_form() {
  $form = array();
  // Add the form fields for the registration form.
  // ....
  $form['name']['formtype'] = array(
    '#type' => 'radios',
    '#title' => t('form type'),
    '#options' => array(
       t('one form'),
       t('two form'),
       t('three form')
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );

  return $form;
}

function redirect_custom_reg_user_register_form_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. personal="@username"', array('@username' => $form_state['values']['username'])));
}

Here is the code from the modal example in Chaos tool suite module:

switch ($option) {
  case 0:
    drupal_set_message('patient');
    $form_state['redirect'] = 'patient/form';
    break;

  case 1:
    drupal_set_message('student');
    break;

  case 2:
    drupal_set_message('doctor');
    break;
}

Here is the example from the Chaos tools which creates a custom modal display:

Here is the code that I have extracted from the tutorial.
From the comment this seems to be used to theme the custom modal:

function ctools_ajax_sample_page() {
  $sample_style = array(
    'ctools-sample-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 500,
        'height' => 400,
        'addWidth' => 20,
        'addHeight' => 15
      ),
      'modalOptions' => array(
        'opacity' => .5,
        'background-color' => '#246'
      ),
      'animation' => 'fadeIn',
      'modalTheme' => 'CToolsSampleModal',
      'throbber' => theme('image', array(
        'path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'),
        'alt' => t('Loading...'),
        'title' => t('Loading')
      )),
    ),
  );

  drupal_add_js($sample_style, 'setting');

  // .....................
  // .....................

  // This displays the widget.
  $button_form  = ctools_ajax_sample_ajax_button_form();
  $links[] = l(t('Wizard (no modal)'), 'ctools_ajax_sample/nojs/animal');
  $links[] = ctools_modal_text_button(t('Wizard (default modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'));
  // .....................
  // .....................
}

Here is the answer to my question by using the chaos tools:

// this creates the url that can be entered to reach this form
function ctools_ajax_sample_menu() {
  $items['ctools_ajax_sample/simple_form'] = array(
    'title' => 'Simple Form',
    'page callback' => 'regone_form',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function regone_form() {
  global $user;

  ctools_include('ajax');
  ctools_include('modal');

  // Add Ctools' JavaScript to the page.
  ctools_modal_add_js();

  $sample_style = array(
    'ctools-sample-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 500,
        'height' => 400,
        'addWidth' => 20,
        'addHeight' => 15
      ),
      'modalOptions' => array(
        'opacity' => .5,
        'background-color' => '#246'
      ),
      'animation' => 'fadeIn',
      'modalTheme' => 'CToolsSampleModal',
      'throbber' => theme('image', array(
        'path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'),
        'alt' => t('Loading...'),
        'title' => t('Loading')
      )),
    ),
  );

  drupal_add_js($sample_style, 'setting');

  ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
  ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');

  $links = array();
  $links[] = ctools_modal_text_button(t('Wizard (custom alex modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'), 'ctools-modal-ctools-sample-style');

  $output  = theme('item_list', array('items' => $links, 'title' => t('Actions')));

  // This deals with theming of the modal box.
  $output .= theme('ctools_ajax_sample_container', array('content' => '<h1>' . t('Sample Content') . '</h1>'));

  return array('markup' => array('#markup' => $output));
}


How to set DB log only to log CRON TYPE and SEVERITY NOTICE message? I want to log only CRON TYPE and SEVERITY NOTICE message in db log , want to exclude all other types like notice, alert, critical, info, debug etc.,
Is there any way to prevent this, or should i write any custom coding for this?
if custom coding for where i can prevent logging other types in DBLOG.

The Drupal error handler _drupal_error_handler_real() utilized PHP's error_reporting() to determine what gets logged to the DB. By setting the PHP error_reporting to E_ERROR it will only PHP errors.

This PHP setting can be set in many places: the system php.ini, a php.ini/.user.ini instance in webroot, .htaccess in Apache. The Drupal centric way to do this, is to use ini_set() function in settings.php:

ini_set('error_reporting', E_ERROR);

See PHPs error constant page for other values to set error_reporting.


How can I change the title of the site on Google search? I have changed the site name to HoNESt, but when I search for the website on Google, the site name results HoNESt: Front Page.

How can I change this?

Meta Tag

The Metatag module allows you to automatically provide structured
metadata, aka "meta tags", about a website. In the context of search
engine optimization, when people refer to meta tags they are usually
referring to the meta description tag and the meta keywords tag that
may help improve the rankings and display of a site in search engine
results.

Basically it allows you to format your title and description that gets indexed by search engines.
Once you install it, you need to override the Global: Front Page and remove the [site:name] token.
Here is a Video Tutorial
PS: You will need to wait until Google crawls your site again to see changes.


how to enable comments only to subscribed users I'm creating a site for events where people can subscribe themselves to a single one.
Now, I'm using Node Registration module to allow users to subscribe. I would like to know if it is possible to enable comments of a particular event only to users who are members of it. Is there a module to do this? I tried with rules module but i couldn't...

Here is a programmatic way to do this, add this code to your custom module

NOTE:

In the following code my content type name is article, change it to yours.

Also this code can not handle functionality for anonymous user as I couldn find a way to track if anonymous user is already registered or not.

/**
  * Helper function to check if user is registered to a given event node or node.
 */
function check_if_user_is_registered($node, $uid) {
   $return = FALSE;
   $registrations = node_registration_load_multiple(FALSE, array(
      'uid' => $uid,
      'nid' => $node->nid,
      'cancelled' => 0,
    ));
  if(is_array($registrations)) {
    foreach($registrations as $registration) {
      if($registration->author_uid == $uid) {
        $return = TRUE;
      }
    }
  }
  return $return;
}

/**
  *  Implements hook_node_load().
 */
function MYMODULENAME_node_load($nodes, $types) {
  global $user;
  foreach ($nodes as $node) {
    if($node->type == "article") {
      $access = check_if_user_is_registered($node,$user->uid);
      if(!$access) {
       $node->comment = 0; // to close comments
      }
    }
  }
}


Views filter by type and taxonomy I have two types of content every one with two taxonomies:

TYPE A with Taxonomy 1 (multiple)

TYPE B with Taxonomy 2 (multiple)

Now I created a view with 3 filters exposed:

Node type: A or B or both

Taxonomy 1

Taxonomy 2

Now if I choose, all the nodes A and B with the term x (taxonomy 1) and the term y (taxonomy 2) does not return nothing.

I tried to change the AND and OR, but nothing comes out from the query.

Do you think it is possible a query like this with views filters?

Use group filters

First views filters group

Type A AND taxonomy 1

Condition between groups

OR

Second views filters group

Type B AND taxonomy 2


How do I pass parameters to the URL? I want to pass parameters to the URL. With node/1/param1/param2, it works. If node/1 has the contenu/accueil path alias, contenu/accueil/param1/param2 returns a 404 error.

How do I pass parameters to the URL even when there is a path alias defined for the URL?

The Pathauto module is disabled.

You need the Sub-pathauto (Sub-path URL Aliases) module for that. Here is a quote about it (from the module's project page):

The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


Why all core services cannot be registered in core.services.yaml? DrupalKernel
  Building of Dependency Injection Container and registration of Service Providers Core provides the CoreServiceProvider, which, in addition to registering any core services that cannot be registered in the core.services.yaml file, adds any compiler passes needed by core, e.g. for processing tagged services. Each module can add its own service provider, i.e. a class implementing Drupal\Core\DependencyInjection\ServiceProvider, to register services to the container, or modify existing services.

Why cannot all the core services be registered in core.services.yaml?
 Why do we need a service provider class to register services or modify existing services, when we can register services in module.services.yml?

Why cannot all the core services be registered in core.services.yaml?
Why do we need a service provider class to register services or modify existing services, when we can register services in module.services.yml?

I think the answer to both these questions is that likely some of the services are dynamic. Yaml files can only be used for static registration of services.


Using Varnish with multiple vhosts I have varnish configured and "working" on port 80.  I have apache running a few instances of Drupal 6 on port 8080.  One for dev, review and one for production.  I used the four kitchens vcl file as a guide in setting things up.  But I'm wondering if I need to do more configuration in the VCL to separate these environments?  Perhaps separate backends?  I'm not sure when this is necessary.

In addition to this, I am not getting any (or very few) hits, mostly misses which indicates something isn't working correctly.

For reference, my vhosts looks like this...

NameVirtualHost *:8080
<VirtualHost *:8080>
        ServerAdmin info@mysite.com
        ServerName www.mysite.com
        ServerAlias mysite.com
        DocumentRoot /var/www/prod/httpdocs
        ErrorLog /var/www/logs/prod_error.log
        CustomLog /var/www/logs/prod_access.log combined

        <directory "/var/www/prod/httpdocs/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </directory>

</VirtualHost>

<VirtualHost *:8080>
        ServerAdmin info@mysite.com
        ServerName test.mysite.com
        DocumentRoot /var/www/test/httpdocs
        ErrorLog /var/www/logs/test_error.log
        CustomLog /var/www/logs/test_access.log combined

        <directory "/var/www/test/httpdocs/">
                Options Indexes MultiViews FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </directory>

</VirtualHost>

Feel free to call out anything else you see wrong with how I have configured things in apache.

Additionally, what can I do if I want my dev environment to skip caching all together?

Thanks

You may setup different VCL configurations for your environments.

It can be easily done with wrapping them by host condition:

sub vcl_recv {
if (req.http.Host ~ "^example.com")
 {
 ...
  if (req.url ~ "^/something") {
   return(pass);
  }
 ...
}
}

Please, take a look on my blog post http://blog.tenya.me/blog/2011/12/19/varnish-simple-virtual-hosts/, it describes how to do configuration separation.


Remove the "Please wait" text on Ajax Call I am trying to remove the text "please wait" that happen on every Drupal Ajax call. Could anyways one point me the way to achieve this in an elegant manner (without any module or CSS hack)?

Thanks

You should be able to do this with hook_form_alter() by changing the Ajax settings that control the form's Ajax. There is a 'progress' property in Ajax that will allow you to set or change the 'Please wait...' text. From the API docs:

#ajax['progress']['message'] String. An optional message to the user; should be wrapped with t().

A sample hook_form_alter() that will accomplish this:

function mymodule_form_FORM_ID_alter($form, &$form_state) {
  unset($form['element']['#ajax']['progress']['message']);
  // or:
  $form['element']['#ajax']['progress']['message'] = '';
}

You should be able to use print_r($form); or dsm($form) (with Devel module) to locate the form element with Ajax properties set. Use that to locate the proper element and replace my $form['element'] above with the actual element in question.


Update Drupal Core from 6.26 to 6.36 using update.php gave no errors, but Drupal still reports that it is on version 6.26 I've followed all of the steps on https://www.drupal.org/upgrade/running-update-php to upgrade my Drupal Core.

I put the site into maintenance mode.
I disabled all modules except the core required modules.
I used FTP to delete all of the folders associated with the upgrade.
I copied the entire directory of contents except .htaccess and robots.txt and part of my sites directory
I navigated to subsite.site.com/update.php
I ran the update
The update indicated that it performed 0 / 0 tasks and said it completed
I navigated to the administration page
I cleared cache
I reenabled modules
I checked the current upgrade status

Result: It still read that I was on 6.26
Expected result: It reads that I'm on 6.36

Quite confused about this. I have successfully upgraded my modules using the update.php script with no problems.  Any thoughts?

Thanks!

Have you manually brought your codebase up to version 6.36 by overlaying 6.24 with 6.36?

The update.php will only update the database to the latest version of Drupal installed.  So if it's still 6.24, it makes sense to me that it is applying 0 of 0.

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


PreExistingConfigException: Configuration objects provided by progweb_migration already exist in active I'm playing with migrations from D7 to D8 and I've found that, when you register a module with a migration, if you disable it, next time you enable the module gets stuck on this:

[vagrant@devbox] /[...]/default $ drush en progweb_migration -y
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
The following extensions will be enabled: progweb_migration
Do you really want to continue? (y/n): y
exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects[error]
(migrate.migration.custom_user) provided by progweb_migration already exist in active
configuration' in /www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70
Stack trace:
#0 /www/drupal8/core/lib/Drupal/Core/Extension/ModuleInstaller.php(162):
Drupal\Core\Config\PreExistingConfigException::create('progweb_migrati...', Array)
#1 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(129):
Drupal\Core\Extension\ModuleInstaller->install(Array, true)
#2 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(196):
drush_module_install(Array)
#3 /opt/drush7/vendor/drush/drush/commands/pm/pm.drush.inc(1120): drush_module_enable(Array)
#4 [internal function]: drush_pm_enable('progweb_migrati...')
#5 /opt/drush7/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_pm_enable', Array)
#6 /opt/drush7/vendor/drush/drush/includes/command.inc(210): _drush_invoke_hooks(Array,
Array)
#7 [internal function]: drush_command('progweb_migrati...')
#8 /opt/drush7/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#9 /opt/drush7/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php(46): drush_dispatch(Array)
#10 /opt/drush7/vendor/drush/drush/drush.php(76):
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
#11 /opt/drush7/vendor/drush/drush/drush.php(16): drush_main()
#12 {main}

It's like the migration is being registered but not de-registered. In D7 there is a method for that, but no luck so far trying in D8:

function progweb_migration_enable() {
  Migration::registerMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::registerMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');
}

function progweb_migration_disable() {
  Migration::deregisterMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::deregisterMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');

}

Any ideas?

This is a core issue, not specific to Migrate. The problem is, config entities are copied into the active store when you enable your module but not deleted when you remove your module. This is what causes the errors when re-enabling your module.

I would highly suggest Config Devel for developing migrations. It will allow you to synchronise your migrations back into the active store without re-installing.


How can I get a user's language from their e-mail address in PHP? I'm using the Mime Mail module to send HTML e-mails to my users.  I have created a template, mimemail-message.tpl.php, and placed it in my theme's directory.  This template defines header and footer links and is applied to every outgoing e-mail.

However, I have a multilingual site and I want to customize these footers per language.  My PHP skills are limited but I'm fairly confident I can do this with a switch statement if I can get the e-mail recipient's language.

I'm having trouble figuring out how to get the user's language.  The Mime Mail module provides a variable, $recipient, which is set to the e-mail address of the user.  Is it possible to load a user based on the e-mail address and then get the user's language?

I don't think there's an API function to do exactly that, but a single database query would get you that information:

// Query the database
$args = array(':email' => $email_address);
$lang = db_query('SELECT language FROM {users} WHERE mail = :email', $args)->fetchField();

// If there's no language string use LANGUAGE_UNDEFINED instead.
// This is also a fallback method to use the default language
// if the user is not found in the database.
if (!$lang || empty($lang)) {
  $lang = LANGUAGE_UNDEFINED; // Or whatever your default language is
}

If you need the user object itself for whatever reason, you can use a slight variation on the above:

$args = array(':email' => $email_address);
$uid = db_query('SELECT uid FROM {users} WHERE mail = :email', $args)->fetchField();

if ($uid) {
  $account = user_load($uid);
  $lang = $account->language;
}

You could also take advantage of the $conditions parameter of user_load_multiple(), but this method has been deprecated so it might not be the best idea to use it:

$users = user_load_multiple(array(), array('mail' => $email_address));
if (!empty($users)) {
  $account = array_shift($users);
  $lang = $account->language;
}

Last but not least, you could use an EntityFieldQuery, although this would probably be overkill for this particular task. It is a useful thing to know though:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('mail', $email_address);

$results = $query->execute();
if (isset($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
  if (!empty($users)) {
    $account = array_shift($users);
    $lang = $account->language;
  }
}


Best way to register a new Drupal user via a 3rd party application We have a Java application on our server, when users provide their email and username to it I want it to send the username and email to our Drupal site to register them for an account. And I'd like them to still receive Drupal's welcome email containing their password.

What's the best way to achieve this, I was thinking possibly the services module? But wasn't sure if there'd be a better solution because the Java code and Drupal site are on the same server and therefore we could have some pretty direct integration.

I may be biased b/c I am the Services module maintainer, but, You don't want to be directly inserting things into the database.

You could REALLY break Drupal by doing this.

If you didn't want to use services module(which why wouldn't you?) you should really use Drupal's apis to put things in the database, like, node_save, or drupal_form_submit(which is what services does).

This ensures that Drupal actually enters the data and will lead to a cleaner overall integration with less problems.

In Drupal 6.x this json actually creates a user when POSTed to SERVER/ENDPOINT/user.

{"uid":"1","name":"admin","pass":"1a1dc91c907325c69271ddf0c944bc72","mail":"kyle@workhabit.com","mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1286571725","access":"1294792121","login":"1293782855","status":"1","timezone":null,"language":"","picture":"","init":"kyle@workhabit.com","data":"a:0:{}","roles":{"2":"authenticated user"}}


Getting Feed Aggregator to ignore certain incoming data EDIT: So originally I posted the below, but I've found other issues and I have some more information. I noticed today that sometimes the links are wrong as well but correct when I view the feed. I looked at the XML being sent by the feed we're bringing in and for one thing, the extra timestamp is being sent in a tag called <updated>. I'm not sure why it's being appended to the body text though. Similarly, other tags are being interpreted/appended in such a way as to mess up some other things.

So my new question is: is there any way to have more control over how feed aggregator is arranging this incoming stuff? I want to get rid of that stuff from <updated> and a couple of other tags and tell it to link the header with the appropriate link (right now it doesn't always do that).

Previous Post text:

In Drupal 7 I've got a view to show some news items that another developer set up through aggregator. The fields are Link, Title, Timestamp, and Body (although Link is hidden; long story that doesn't seem to affect this). Everything looks good except there's an extra timestamp at the end of the body text. Here's an example:

  Orange County (CA) Register SEILER: Legislature could ignite rush to smuggle cigarettes

  Wednesday, August 19, 2015 - 11:19

  But higher taxes here would push us in the direction of New York City, meaning more smuggling, more crime and less policing... California already has the nation’s second-lowest rate of tobacco use, after Utah. It should leave higher taxes and other nann 2015-08-19T15:19:16+0000

The '2015-08-19T15:19:16+0000' is what I want to get rid of. I have looked all around but I'm not able to figure out what's causing this. I thought maybe it had something to do with the feed we're using but I looked at the link (http://www.tobacco.org/tagged/new-york.atom) and it doesn't seem to include this.

I'm fairly new to Drupal but I did try to figure this out on my own and I'm at a loss. After extensive Googling I can't even find another example of this happening so I know I'm missing something. Any help is greatly appreciated; thanks.

OK, so I'm considering deleting this but it was such a source of frustration for me I guess I'll leave it up in case someone else ever comes across this. This answer, to me, seems like more a workaround (mainly because I am still lacking a basic understanding of why it's happening) so if anyone else has a better answer or more information please do post your own answer.

It seems like you can't have complete control over how Views or Aggregator arranges elements from the XML feed. It also seems (from my fruitless Googling) that this isn't usually a problem. I don't really know if this is an issue with how the RSS feed we have to use is configured or if it's a Drupal thing but I know the answer is in gaining control over where and when the different XML elements appear.

Most people seem to use a module called Feeds to gain control over this type of thing (and do other stuff). From superficially looking into it, it seems like it could fix my problem but it creates a separate node for each incoming item, which is not ideal for my special case. The feed on the site I'm working on just keeps up with the latest 20 items and then discards them so I didn't want to have to deal with a separate node for each thing.

I've decided to try a different module called Views RSS which sounds like it can simply solve my problem (here's some more info). I haven't tried it yet but it looks promising. Thanks to anyone who read this and to anyone who might be able to contribute in the future.


What's the proper (seo safe) way to blackout a site (e.g. for SOPA)? I want to safely blackout my Drupal site to raise the awareness of SOPA. What's the SEO friendly way to do that?

I'm thinking of putting my site into maintenance mode and just changing the maintenance message.

I found this post on the Drupal Google+ page. It says:

  Black out your #Drupal site against #SOPA on Wednesday. Drupal's maintenance mode is 503 status so it won't hurt your SEO.


How do I theme the user profile page? What is the best / easiest way to theme the user profile page? I'm building a talk radio website and registered members will provide news articles publically avail. eventually there will be thousands of registered users.

I'm worried that I will figure out an answer that works but isn't correct and will force me to go back and rewrite later on.

I don't know if I should use views or just straight code the page-user.tpl - if I straight code,  what function gets the uid from the /user/xx url? if I use views how do I assign the view to the pages in /user/xx

For some reason I cannot find any complete info on this; either it's a great secret or I'm missing something really simple. thank you!

I would suggest you to use Panels and Views modules and optionally Profile2.

You will add some fields to user account or to the user profile if you installed Profile2. Then enable the 'User profile template' page under admin/structure/pages and add a panel variant, select a layout and place the content or fields. If you have Profile2, then you need to add it as a relationship 'Profile2 from user' under the 'Contexts' menu of the panel page. I'm not going into details about how to use panels.

To display the summary of user's recent activity, you should setup a view with a contextual filter of user id, preferably a 'Content pane' display, then you need to place this content pane into you user panel.

It is not a great secret how to build a user profile page, but it's completely dependent of what you want to have. If you have any difficulties implementing the steps I wrote, you can update your question or post another more specific question.


Hide node title on front page using template.php not css I'm building a drupal 7 bootstrap sub theme and want to hide the title of the nodes if there on the home page. I don't want to use css as its only hiding it I want to have the titles not render at all.

i have tried hook_preprocess_page() but didnt work:

function mytheme_preprocess_page(&$vars) {
    if ($vars['is_front']) {
        $vars['title'] = '';
    }
}

Your close with hook_preprocess_page() but as you want to hide the node title (and not the page title) you need to use hook_preprocess_node() instead.


How to create a custom context by using Drupal's context API? I can access current node context in my block plugin by adding:

 *  context_definitions = {
 *    "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required=FALSE)
 *  }

to its annotation. And then access node object by using:

$context = $this->getContext('node');

/** @var NodeInterface $node */
$node = $context->getContextData()->getValue();

Provided it's available. But let's say I want to create context that is active only if node has specific field.

I'm currently trying to reverse engineer this, because there are literally no resources on context API that I could find, but maybe someone have some working example to share?

Ok, I figured it out and I'm describing it here. It's really surprising for me that it's not explained anywhere else as of now.

Let's say we have a content type news that have a field field_section storing reference to the term from the sections vocabulary. Now, everytime we are on the node's page, and this node is referencing a section, we want to trigger the context, that will give as a Term object representing our section. Moreover we have a block plugin, that depends on the availability of this section, and should be visible only if section is available on the current page.

We could do this with the node context, but then we would have to add logic checking the content of the field_section of our node, in every context aware plugin that needs this information, and we want to have this simplified to just having context active when section is available on the current page - that's the whole point.

So first off, we have to provide a service that implements Drupal\Core\Plugin\Context\ContextProviderInterface, and tag it with context_provider tag, like that:

  mymodule.section_context:
    class: Drupal\mymodule\ContextProvider\SectionContextProvider
    arguments: ['@context.repository']
    tags:
      - { name: context_provider }

Note that we are injecting @context.repository service, we will be able to extract the node context from it. We are dependent on the node being available in the first place, so we can as well reuse this context. We could also inject here @node.node_route_context service directly and have more explicit dependency, but I felt that it would be more clean to do this trough the repository service. It's up to you.

Now the code of our context provider:

namespace Drupal\mymodule\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextInterface;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class SectionContextProvider
 */
class SectionContextProvider implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * @var ContextRepositoryInterface
   */
  private $contextRepository;

  /**
   * @param ContextRepositoryInterface $contextRepository
   */
  public function __construct(ContextRepositoryInterface $contextRepository) {
    $this->contextRepository = $contextRepository;
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {

    $nodeContextId = '@node.node_route_context:node';

    /** @var ContextInterface $nodeContext */
    $nodeContext = $this->contextRepository->getRuntimeContexts([$nodeContextId])[$nodeContextId];
    $value = NULL;

    /** @var NodeInterface $node */
    $node = $nodeContext->getContextData()->getValue();
    if ($node && $node->hasField('field_section')) {
      $value = $node->get('field_section')->entity;
    }

    // We are reusing cache contexts.
    $cacheContexts = $nodeContext->getCacheContexts();
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts($cacheContexts);

    $contextDefinition = EntityContextDefinition::create('taxonomy_term');

    $context = new Context($contextDefinition, $value);
    $context->addCacheableDependency($cacheability);
    $result['mymodule_section'] = $context;

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    $context = EntityContext::fromEntityTypeId('taxonomy_term', $this->t('Mywebsite Section from Node'));
    return ['mymodule_section' => $context];
  }

}

Basically will are getting the current node from the node context, and then extract section data if it's available.

But that's not all.

We want to make our plugin block dependent on the context, so we are are adding to its annotation:

 *  context_definitions = {
 *    "mymodule_section" = @ContextDefinition("entity:taxonomy_term:sections", label = @Translation("Mywebsite Section"))
 *  }

But it still won't work, and that's the tricky part. We also have to configure the context mapping of our plugin block. We can do this by providing it as a part of default configuration like that:

  /**
   * @return array
   */
  public function defaultConfiguration() {
    return [
      'context_mapping' => [
        'mymodule_section' => '@mymodule.section_context:mymodule_section',
      ],
    ] + parent::defaultConfiguration();
  }

And ONLY THEN it will work. The block wont be rendered if context is not available, and if it is, we can access the term referenced by node's field_section field by:

$sectionTerm = $this->getContext('mymodule_section')->getContextData()->getValue();

That's way too complicated for this to not have any documentation, but I hope this description will help someone.

And if anyone know, where on the drupal.org website I could write up a documentation for that, please let me know, we have to improve that stuff.


Search through a specific field - Drupal 7 Is it possible with Drupal to create a seperate search field to search in a custom field for a specific content type?

For example I have a text field in a content type with the name keywords. I gave some important keywords for that specific node.

What I want is that a user can search through these words with a custom search field, that is displayed on a specific page.

I know I could use something like exposed filters in views, but it is not working in my case. The reason is the nodes are having a relationship with a taxonomy list. The nodes are showing based on the taxonomy term ID in the URL.

For example, my taxonomy list called 'Jobs'. The terms in the list are
'sanitary', 'interior' and 'garden'.

When I'm on the page with the sanitair, there is a search field. If I search in this field it should take a look for all the nodes not only the nodes that are related with the 'sanitair' term. If I used exposed filters the filter is only searching on the current term, so only the kind of jobs for 'sanitair' are showing up.

Is there a way to do this with or without views and is it also possible to create this search field in a block, so I can use it on different places?

Thanks!

You could:

create a new separate view for searching across all nodes and display it in a block on the taxonomy term page, or
use solr search and set up facets (requires a lot of setup)


Add #ajax callback to an entity_autocomplete field I have an entity_autocomplete field in a form.

$element['content'] = array(
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#title' => t('Content'),
  '#title_display' => 'hidden',
  '#default_value' => $content_default,
  '#selection_handler' => 'default',
  '#selection_settings' => array(
    'target_bundles' => $selected_bundles,
  ),
  '#prefix' => '<div class="container-inline">'
);

I would like to add an #ajax callback to run after someone has selected a piece of content from the autocomplete drop-down, but I can't seem to find out how to attach it.

I have tried as follows which works for select boxes.

   $element['content']['#ajax'] = array(
      'callback' => 'Drupal\MODULE\Plugin\Field\FieldWidget\WIDGET::METHOD',
      'wrapper' => $id,
      'method' => 'replace',
      'progress' => array(
        'type' => 'throbber',
        'message' => "shuffling",
      ),
    );

However, it does not fire. Is it possible to do what i need?

It actually fires if you tab out of the field, but I need it to fire after a selection is made.

You can adjust the behavior with

'#ajax' => array(
  'event' => 'change',

This can be any javascript event. The default for a select is on 'change', for a normal field this is on 'blur'. But you can try any other event.

Reference: https://developer.mozilla.org/en-US/docs/Web/Events


Problem with migration from Apache to IIS I run a website with Drupal in Linux/Cpanel/Apache/MySql and it worked perfect.
I want to put this site in Windows/plesk/IIS/MySql. I backed up and restore database in the new host and copied Drupal files.

My website run in new host with some problem.

I can't see administrative page; this page is white.
My links don't work with clean URLs and I should add (?q=) to links.
My images with ImageCache are not shown. The URLs for images are not correct and have a space.

You need to translate the Apache server's rewrite rules into their IIS equivalents, in the root web.config.

For reference, see what is reported in the Windows Download Instructions.

  IIS7: Create/modify web.config file. Drupal distributions come with .htaccess files for *nix use; IIS7 users should convert this file to a web.config file for their site. If you have used the IIS Manager to create a new site, a basic web.config file will exist in your site's root directory.


How can I change the order of the list of countries provided by the Countries module? I have a Drupal 7 site that uses the Countries module.  I would like to show the United States first in the list and the rest of the countries then in alphabetical order (by default, the module displays all countries in alphabetical order).  This is a common feature on many sites so I'm hoping there's an easy way to do this.

It's a shame Sumeet didn't continue his answer, as he got so close, but here is the alter hook:

function HOOK_countries_alter(&$countries) {
  $US = $countries['US'];
  unset($countries['US']);
  array_unshift($countries, $US);
}

It copies US, removes it from the list, and attaches the copy back to the top.

You don't say in what context you use the module. I verified that it does what it should on a country-field.


Differences from dpm and dsm for devel module for debugging objects? What are the differences of dpm and dsm for the devel module? I mainly use dsm for the devel module. What are some other common debugging functions that are useful in the devel module?

From the documentation:

Legacy function that was poorly named.
Use dpm() instead, since the 'p' maps to 'print_r'.
Code
function dsm($input, $name = NULL) {
  return dpm($input, $name);
}

So there is no real difference, except the function you are using is left there for developers that failed to switch when it was renamed.


How to print a string for flagged nodes? I have a flag called "Mark as SOLD" which can be flagged only by node author. When he flags it as "Sold", I want the node teaser to print a translatable string t('SOLD'), so that everyone else (even anonymous) can see that this item is now sold.

In my corolla template.php I already have custom function that gives classes to different flags:

    function corolla_preprocess_node(&$variables) {
  $flag = flag_get_flag('sold'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-sold';
  }
$flag = flag_get_flag('withdraw'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-withdraw';
  }
}

But I know that I need to modify this function and/or node--type.tpl.php to actually print a string t('SOLD').

How can I achieve this?

You can set a new variable in your preprocess function and print it in your node--type.tpl.php as follows:

In template.php

function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'YOUR_CONTENT_TYPE') {
    $flag = flag_get_flag('sold');
    if ($flag && $flag->is_flagged($node->nid)) {
      $variables['classes_array'][] = 'node-flag-sold';
      $variables['flagged_text'] = t('Sold');
    }
  }
}

And in your node--YOUR-CONTENT-TYPE.tpl.php, put simply this snippet wherever you want to print the string:

<?php if ($flagged_text): ?>
  <?php print $flagged_text; ?>
<?php endif; ?>

or the same code shorter:

<?php if ($flagged_text) print $flagged_text; ?>

But the first one is better for readability and follows the Drupal's coding standards for template files.


Limit the reviews on "Product" content type I want to limit the users' review of my "Product" content type to only one, and I tried to implement a code from this link in Drupal 7 as a simple module named "review_limit." I saw this module in my module list and installed it without an error.

This is my code:

function review_limit_form_alter($form_id, &$form) {
    // If the form is a "product_review" node form
    if ($form_id == 'product_review_node_form') {
        // Add an extra validation function //
        $form['#validate'][] = 'review_limit_user_node_limit';
    }
}

// Validation function
function review_limit_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    $result = db_query("SELECT n.uid, n.nid
    FROM {field_data_field_product_review_pr}
    Inner Join {node} n ON field_data_field_product_review_pr.entity_id = :nid
    Inner Join {users} ON n.uid = :uid", array(':nid' => $node->nid,':uid' => $user->uid))->fetchfield();
    //if founded referenced field from the logged user, drupal show error message
    if ($result) {
        // Throw error
        //drupal_set_message('You have already submitted a review of this item.', 'error');
        form_error($element['title'], t('You have already submitted a review of this item.'));
        die;
    }
}

and i have prepare a template named product--review.tpl.php, page--node--add--product_review.tpl.php and call it from my template.php using

function bartik_theme() {
  return array(
    'product-review_node_form' => array(
      'arguments' => array(
          'form' => NULL,
      ),
      'template' => 'product_review-node-form',
      'render element' => 'form',
    ),
  );
}

This module does not work, every user is still can to create a product review node as much as they want.
Did I miss anything? Can anyone help me to solve this problem?

The error is that you use die; the hook should simply return to the calling function. If you use die, you are avoiding that the code calling the validation handler is called back, which means the code that checks if there are any validation errors, and shows them to the users is never executed.

If you look at the code used by a Drupal validation handler, such as user_pass_validate(), you will notice it doesn't use die, which is never used from any form validation handler.

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}


Form filter by field on entity_autocomplete I have a form with this field.
the user can save one or more results.
I want to filter by the foreign key who is on the user table but i don't know how to do this.

My code :

$form['referent_business'] = [
  '#title' => 'Référent',
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#tags' => TRUE,
  '#validate_reference ' => TRUE,
  '#autocreate' => false
 ]

So I tried another solution :

$form['referent_business'] = [
  '#title' => 'Référent',
  '#type' => 'textfield',
  '#autocomplete_route_name' => 'jds.autocomplete_referent_ce',
  '#autocomplete_route_parameters' => [
    'business' => $entity->id()
  ],
  '#required' => TRUE,
  '#tags' => TRUE,
  '#validate_reference ' => TRUE,
  '#autocreate' => false,
  '#access' => $user->hasRole('administrator') ? TRUE : FALSE,
];

With the function

public function autocompleteReferentCE(Request $request, $business)
{
    $matches = [];
    if($string = $request->query->get('q')) {
        $query = \Drupal::entityQuery('user')
            ->condition('status', 1)
            ->condition('id_business', $business)
            ->condition('last_name', '%'.db_like($string).'%', 'LIKE');
        $idUsers = $query->execute();
        $users = User::loadMultiple($idUsers);
        foreach($users as $user) {
            $matches[] = [
                'value' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value,
                'label' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value
            ];
        }
    }
    return new JsonResponse($matches);
}

The custom entity_autocomplete function works. When the user saves several results, the return isn't an array, but a string.

So, someone knows how to filter with the first solution or return an array of result with the second solution ? Or another solution ?

Thanks in advance

The core autocomplete feature expects the label of the returned matches contain the id of the referenced entity like Superuser (8) which is parsed by the drupal.autocomplete behavior and submitted through the actual form input. The easy solution its to ensure that your response returns the expected values. But you can always implement your own. See Drupal\entity_reference\EntityReferenceController to see how the core implenents it.


How do I move the "Login or Register to Post Comments" links? I would like to move the "Login or Register to Post Comments" link from above the comments to below the comments, yet above the comment form.

I have the link variable available in the preprocess_node hook and I can unset it there, but when I try to add it as a variable with another name, it's not available in comment-wrapper.tpl.php.

I guess I'm asking what the Drupal way is to pass this variable from the node to comment-wrapper.tpl.php. It's important that we copy the variable value instead of manually creating the links in so we have the same value for the login and register links regardless of whether another module has acted/changed them.

The "Login or Register to Post Comments" link is created via:

theme('comment_post_forbidden', array('node' => $node));

so I'd create a variable with that in the appropriate preprocess hook that has  $node available.


How to show nodes of a content type using contextual filters as filters? I have a profile page for each user where it will show all nodes he has created for each content type.

For instance, Autos content type will only list all autos he has authored. I'd like to be able for the user to access it using this path : http://localhost/mysite/myreports/autos and will show his autos, .../myreports/jobs will show his job postings, .../myreports/events for events etc...

I have tried doing it in views using page views with path ..../myreports/% (where argument is the name of the content type) and added a views contextual filter for 'content type' but i cannot get it to work.

I had read this : Drupal 7 Views Contextual Filter to show only nodes of the same type but it's not working.

I can set up each unique view to a content type without using contextual filters so I can specifiy a permanent url for say ...myreports/autos but then that would be inefficient.

Any suggestions?

After hours of tinkering here is my solution to the above. If anyone has the same requirement this will help:

Drupal 7.16, views-7.x-3.5

The View Setup :

The result (sample 1):

Sample 2:

No other settings required. Even in the section "WHEN THE FILTER VALUE IS NOT IN THE URL" does not matter, what seems to be important is you set the validation to always return TRUE regardless.

The path of this view is set to /myreports/%

Perhaps, the filter value in the URL that was found will be validated to always true. Then resolves to using this as a normal filter, as is the case with the normal filter setting. Hence, Filter content type = events (or jobs).


Children of children not appearing in book navigation menu UPDATE: I should mention that this is concerning the Book Navigation Block

I'm using the book module to display children of a book in a side menu. It displays the title of the book and it's children just fine. However the children of the children don't appear even after clicking on the parent page.

I searched in the module settings for book navigation however I can't seem to find a way to display them.

Is there anything that could possibly affect what sub items are displayed in a book?

book_children(), which is used in the preprocessor for the "book_nagivation" theme hook (template_preprocess_book_navigation()) only retrieves the immediate children of the current book item, so you wouldn't expect the default "Book navigation" block provided by the Book module to show all children of the current book item recursively.

If you wanted to modify the behavior of this block in your theme, you could clone the template_preprocess_book_navigation() from book.module, placing the function in the template.php file for your theme and renaming it to yourthemename_preprocess_book_navigation(), and then create and call a modified clone of book_children() that recursively collected all links in the book beneath the passed link.

If the behavior you wanted was to display the standard tree for all interior book pages, but display book's entire outline only when you are viewing main page of the book, you could alter your yourthemename_preprocess_book_navigation() function so that it only calls the "get recursive tree" function when the $book_link doesn't have a parent ($book_link['plid'] == 0), and call book_children() for all other cases.


#states in add node form How to use #states in add node form?
I don't experience any problems when use them with exposed filters (on user side), but cannot do the same when additing new nodes.
I tried the following code:

function custom_module_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_coordinate']['und'][0]['#default_value'] = t('1');
    $form['field_name_tag']['und']['0']['#states'] = array(
      'invisible' => array('select[id="edit-field-location-tag-und"]' => array('value' => '1')),
    );
  };
}

Where is my mistake?

You need to set the state in the "value" key, so one level deeper as you tried.
E.g.:

$form['field_yourfieldname'][LANGUAGE_NONE][0]['value']['#states'] =
  array('visible' =>
    array('input[id="edit-field-otherfieldname"]' => array('checked' => TRUE))
  );


How to remove the name of the language? Menu Language Icons How to remove the name of the language? Use the module Language Icon, I want to make only the flags.

On the configuration page of the Language Icons module, admin/config/regional/language/icons, you should set the option 'Icon placement' to 'Replace link'. If I'm not mistaken, choosing this option ensures only the flags are shown.


Checkboxes in exposed form in block aren't checked in initial state I have views with exposed form.

In filter criteria I have filter category which has 4 checkboxes.

If I choose to display exposed form in block, in initial state checkboxes aren't checked but results appears for each of them. It seems like a bug, user is not selected nothing but results are there. I want to these checkboxes be checked in initial state when the page is opened.

If exposed form isn't displayed in block, the checkboxes are checked in initial state.

I also try to change with form alter but without success, I couldn't print anything

function module_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'views_exposed_form':
            krumo($form);
        break;
    }
}

To do so you might have to checkboxes when you expose the form and save the view.


How to check node table for entry by current date before inserting new node? How can I check the database table for specific node entries by date before inserting a new node?

I want to check the node table for any node with the current date, if found, I want to delete the old one and insert a new node.

How can I achieve this.

This should do the trick:

Make a module and insert following code, switch "foo" with your module name.

    /**
    * Implements hook_node_presave($node).
    */
    function foo_node_presave($node) {
      // Lets search for nodes on the current date.
      $somedate = strtotime(date('Y-m-d'));

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('created', $somedate, '>=');
      $query->propertyCondition('created', $somedate + (60 * 60 * 24), '<');
      $result = $query->execute();

      if (!empty($result)) {
        node_delete_multiple(array_keys($result['node']));
      }
    }

Obviously you might want to do some additional checks before deleting the nodes:

// Nodes of the same type
$query->propertyCondition('type', $node->type);

//Only delete published nodes
$query->propertyCondition('status', 1);


Issues with PSR-0 in hook_cron after hours trying to solve this issue by myself and searching for solutions in Google I thought that maybe someone may already faced this.

Scenario:
I am running drush site-install
The installation goes well until it hits a hook_cron (don't really know why) and tries to instantiate a a class. If I run drush cron on an installed site it works as a charm as is only when I am installing the site that this happens.

I use PSR-0 to bootstrap the namespaces and the implementation looks much like this:

/**
 * Implements hook_boot().
 */
function MY_MODULE_boot() {
  //Autoload classes PSR-0
  $namespaces = array(
    'COMPANY\MY_MODULE'     => array(__DIR__ . '/lib'),
  );
  MY_MODULE_register_class_namespace($namespaces);
}

/**
 * Registers a class namespace with the Composer autoloader
 *
 * @param  array  $namespaces
 */
function MY_MODULE_register_class_namespace(array $namespaces = array()){
  static $loader = null;
  if (!$loader) {
    $loader = require_once realpath('.') . '/vendor/autoload.php';
  }

  foreach ($namespaces as $namespace => $namespace_path) {
    $loader->add($namespace, $namespace_path);
  }
}

This is the error I get in the console:

Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Class 'COMPANY\MY_MODULE\Repository\MYCLASSRepository' not found in
<path to module>, line 588

I would really appreciate any help with this one.
Thanks in advance and sorry about my English.

Apparently there is an issue with the way Drupal bootstraps when doing a fresh install. I solved the issue by adding a call to:

module_invoke_all('boot');

Hope it helps you if you come up with the same issue.


Use hook_views_pre_render() to change field to url link I want to use hook_views_pre_render() to read in a view and change a field output to a clickable link.

Here is code:

function sbn_views_pre_render(ViewExecutable $view) {
    // https://drupal.stackexchange.com/questions/272495/how-to-get-views-field-names-values-for-hook-views-pre-render
    if ($view->id() == 'find_paragraphs') {
      foreach ($view->result as $key => $value) {
        $parent_id_value =  $value->_entity->parent_id->getValue()[0]['value'];
        $parent_type_value =  $value->_entity->parent_type->getValue()[0]['value'];
        $private_files = $value->_entity->field_private_files->getValue()[0]['value'];
        if ($parent_type_value == 'node') {
          $link = ''.$parent_id_value.'';
          // $value->_entity->set('parent_id', $link);
        }
        if ($parent_type_value == 'paragraph') {
        }
      }
    }
}

Formatting the $link value using standard html coding does not work.  Any ideas on how to format the link from within this hook so that the rendered field is a clickable link?

I have not been able to figure out how to conditionally change field to link using hook_views_pre_render(), but I did figure out how to do it within the Views UI:

Fields->Parent ID->Rewrite results->Override the output of this field with custom text:

{% if parent_type == 'paragraph' %}
{{ parent_id }}
{% else %}
{{ parent_id }}
{% endif %}


Calling user/token and system/connect through CORS returns anonymous user I have two Drupal sites set up. On site A, I'd like to authenticate myself as the currently logged-in user on site B (the remote site) so that I can view and edit nodes on the remote site using the Services module.

The two sites are on different domains, so I'm using the CORS module on the remote site. My CORS config is as follows:

*|http://MY-SITE-URL|*|Content-Type,X-CSRF-Token,Authentication, Origin, Cookie|true

Calling user/token against the remote site gets me a valid X-CSRF-Token. However, when I send the X-CSRF-Token with system/connect, the remote server returns the anonymous user.

I'm trying to authenticate against the remote server with the following code:

$base_url_api = variable_get('tnb_sync_base_url'); //URL of the remote server

            $options = array(
              'headers' => array(
                'Content-Type' => 'application/json',
              ),
              'method' => 'POST',
            );
            //Step 1: grab the authentication token from the remote server
            $response = drupal_http_request($base_url_api . '/user/token', $options);
            $data = json_decode($response->data);

            // Check if login was successful
            if ($response->code == 200) {
              // Add the token to the request headers:
              $options['headers']['X-CSRF-Token'] = $data->token;

              //Step 2: pass along the token and check who we're logged in as
              $response = drupal_http_request($base_url_api . '/system/connect', $options);
              $data = json_decode($response->data);

              kpr($response);

              return $options;

            }

            else {
                return NULL;
            }

The response for the system/connect call looks like:

stdClass Object
(
    [request] => POST /sync/system/connect HTTP/1.0
Content-Type: application/json
X-CSRF-Token: 74xWvd5I5l1ad1WmrIjqZoACo9r7f30YtJx_uCFot_g
X-NewRelic-ID: VQQAU1JbChACUldTBgUFVw==
X-NewRelic-Transaction: PxQBVFRUXQJUUVQGVQkFBVIEFB8EBw8RVU4aVA0KA1cCAQxUVQMLUAcAAkNKQQgKVVAEUgEEFTs=
User-Agent: Drupal (+http://drupal.org/)
Host: dev.tnb.plus
Content-Length: 0

    [data] => {"sessid":"7u8CZ98Gvb1P3ZuKSnK85g2FMkyu8OlqbOp8mnsy7OM","session_name":"SSESS4be586c0dc3085a3ca4f49c7acb4e7d1","user":{"uid":0,"hostname":"2001:4801:7827:0104:be76:4eff:fe11:ccd8","roles":{"1":"anonymous user"},"cache":0,"timestamp":1492095786}}
    [protocol] => HTTP/1.1
    [status_message] => OK
    [headers] => Array
        (
            [date] => Thu, 13 Apr 2017 15:03:06 GMT
            [content-type] => application/json
            [connection] => close
            [set-cookie] => __cfduid=dc62becfa48db03b7f5e40b426d0f587c1492095786; expires=Fri, 13-Apr-18 15:03:06 GMT; path=/; domain=.tnb.plus; HttpOnly
            [access-control-allow-credentials] => true
            [access-control-allow-origin] => http://dan-northern-portal.pantheonsite.io
            [cache-control] => no-cache, must-revalidate
            [expires] => Sun, 19 Nov 1978 05:00:00 GMT
            [surrogate-key] => AuKS06yStxtoXZf2mZvq kFG3DJ+3z7Lu2WK6wNkS
            [surrogate-key-raw] =>
            [vary] => Accept-Encoding, Accept
            [x-content-type-options] => nosniff
            [x-drupal-cache] => MISS
            [x-pantheon-endpoint] => a9463df4-67b3-47b9-ad41-148336613222
            [x-pantheon-styx-hostname] => styx94699a92
            [x-styx-req-id] => styx-e58976d158f4a1f2e669efc5205db167
            [x-styx-version] => StyxGo
            [xkey] => AuKS06yStxtoXZf2mZvq kFG3DJ+3z7Lu2WK6wNkS
            [x-varnish] => 952125076
            [age] => 0
            [via] => 1.1 varnish-v4
            [server] => cloudflare-nginx
            [cf-ray] => 34ef4f698acf2513-ORD
        )

    [code] => 200
)

How can I properly authenticate myself on the remote site using Services and CORS?

You just haven't logged in to the remote site yet; you can do that with something like:

$options['headers']['X-CSRF-Token'] = $data->token;
$options['method'] = 'POST';

$post_data = ['username' => 'foo', 'password' => 'bar'];
$options['data'] = drupal_http_build_query($post_data);

$response = drupal_http_request($base_url_api . '/user/login', $options);
$data = json_decode($response->data);

Assuming a successful login, subsequent requests within the session timeout will be made in the context of that user.


Change template of Drag & Drop module on node add form I am using Drag & Drop Upload module for multiple images uploading.

But the template I see on node add form (FRONTEND) is this :

And I want to change it to this :

I don't know where can I find the HTML for this template, so I can change it.

Thank you so much for your help!

You can do this by updating css into that module.

Or once try to use HTML5 Drag & Drop File module. Hope this module provided that you want.

  HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to
  drag & drop files into a Image/File Field and uploads it immediately
  behind the scenes. In theory it should work for as many files as the
  field allows.


How to add js to H5P embed.php file? H5P module creates iframes and shows content in the iframe. I need to add a js file in the iframe, but I'm not able to do it.

In the documentation there is an example how to add js to h5p:

/**
 * Add scripts to h5ps
 *
 * @param array $scripts
 *  Array of objects with properties path and version. Version is on the form
 *  ?ver=1.0.2 and is used as a cache buster
 * @param array $libraries
 *  Array of libraries indexed by the library's machineName and with an array
 *  as value. The value has the properties majorVersion and minorVersion
 * @param string $mode
 *  What mode are we in? Possible values are "editor", "div", "iframe" and "external"
 */
function hook_h5p_scripts_alter(&$scripts, $libraries, $mode) {
  if (isset($libraries['H5P.MultiChoice']) && $libraries['H5P.MultiChoice']['majorVersion'] == '1') {
    $scripts[] = (object) array(
      // Path relative to drupal root
      'path' => drupal_get_path('module', 'mymodule') . '/h5p-overrides.js',
      // Cache buster
      'version' => '?ver=1',
    );
  }
}

I have created a module, added that script in the .module file and created the overrides.js. But I am not able to get it working, the js file is not added.
What else should I add in the .module file than this script above?

You need to replace HOOK with your module name. As well as MYMODULE.


User email being deleted when submitting Profile 2 form i'm debugging a site that I haven't made.  The issue is that the users email address is being deleted.

I've found which form it's happening on; and by using hook_form_FORM_ID_alter I can see that $form has this information at before sending and not after it's been sent.

I've written a patch that writes it back in but my question is what the best way is to backtrace where the bug actually is.  I'm using phpstorm as my IDE and have put breakpoints in modules I think could be at fault but without joy.

Any other tips on this one ?

Much appreciated.

You will have to check that hook_form_FORM_ID_alter  and the callbacks inside that hook, at least at the end you can check if the $form still have all the previously data


How do you disable the CSS from a core module in Drupal 8 using libraries-override? I'm trying to disable the CSS styles from the layout discovery module in my theme.info.yml file. I've tried several options, but I can't seem to get it to work. This is what I have now.

libraries-override:
  core/layout_discovery:
    css:
      theme:
        core/modules/layout_discovery/layouts/twocol/twocol.css: false

The CSS styles can be removed using stylesheets-remove at the moment, but that property has been deprecated. It does seem work at the moment, though.

I would like to find the proper way to remove the CSS stules using libraries-override, if I can.

stylesheets-remove:
  - core/modules/layout_discovery/layouts/onecol/onecol.css

Seems you are missing a starting / on the full path. And the name of the overriding library looks wrong as well. There's no library core/layout_discovery. It must be layout_discovery/twocol instead.

libraries-override:
  layout_discovery/twocol:
    css:
      theme:
        /core/modules/layout_discovery/layouts/twocol/twocol.css: false

Source: Overriding and extending libraries

Alternatively, unsetting libraries via hook_page_attachments_alter() does the trick as well. Here comes a working code snippet to be placed in your theme's *.theme file. Replacy MYTHEME with the machine name of your theme.

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME_page_attachments_alter(array &$attachments) {

  foreach ($attachments['#attached']['library'] as $key => $library) {

    // Install the Devel submodule Kint for debugging.
    // Check all libs:
    // ksm($attachments['#attached']['library']);

    // Here I disable the core base library.
    // Looks pretty ugly afterwards.
    if ($library == 'system/base') {
      unset($attachments['#attached']['library'][$key]);
    }

    // So for you it must be like following.
    // Simply try to find the right name via ksm($library);
    // or the other ksm() command from above.
    if ($library == 'layout_discovery/twocol') {
      unset($attachments['#attached']['library'][$key]);
    }
  }
}


Views 'OR' Operator acting as an 'AND' This should be very easy, but I cannot figure out why this is not working?

I have 2 different content types: Type1 & Type2
I currently have a view which displays all nodes of content Type1.
I would then like to manually add specific occurrences of Type2.
So far, I have done this with a Taxonomy term reference field called TaxType (terms: Tax1 & Tax2)

I have set the view to filter by content Type1, which displays all fine.
I then add filter for the Taxonomy Field with the operator of 'OR' but as soon as I add this, it stops showing content Type1?

I would expect this to happen if I left the operator as 'AND'. But with 'OR' it should keep showing Type1 or any occurrences of Tax2.

Drupal 7
Views 3.11

I'm not sure if i can help you out with out a screenshot cause i'm also new to Drupal. But my guess is the filters work in a different way from what you think. It might be something like this...

  Type1 AND (TAX2 OR xxx OR yyy .. etc.)

Hope this helps. Cheers!


How to specify which form mode to use for a content type I created a new_form_mode for a content type in D8 and removed some fields in that form mode from Manage form display tab of the content type by selecting that new_form_mode . But how can i select that form should be displayed for that content type instead of default form mode?

Unlike view modes you can't select form modes out of the box. To manage form modes you need a module. You can try one of these:

https://www.drupal.org/project/form_mode_control

https://www.drupal.org/project/form_mode_manager


Different approval for different user accounts I would like user account A to require approval before granting access, and user account B not to require any approval.

How can this be achieved?

I have not used any module that can provide this kind of control.  What you can do is for the  second option create your own form and from backend create the user on form submit after proper validation.


URL alias to call function in short I want the same functionality as the taxonomy module where you can have an URL like "localhost/drupal/admin/structure/taxonomy/occupational_fields/edit"
where occupational_fields was the aliased part.

The menu entry in taxonomy for the page callback looks like this:

$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
  'title' => 'Edit',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('taxonomy_form_vocabulary', 3),
  'access arguments' => array('administer taxonomy'),
  'type' => MENU_LOCAL_TASK,
  'weight' => -10,
  'file' => 'taxonomy.admin.inc',
);

The function declaration looks like this:

function taxonomy_form_vocabulary($form, &$form_state, $edit = array())

Now my implementation looks like this:

$items['admin/config/mapper/%tid/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

And respectively:

function mapper_form_mappings($form, &$form_state, $edit = array())

But when an URL like "localhost/drupal/admin/config/mapper/11/edit" is opened
the function above is not called.

I tried googling a good URL alias tutorial for module programming, but couldn't find one. Maybe I searched for the wrong thing?

edit: I can imagine that I need some type of handler, but I couldn't find one in the taxonomy files and the tutorials didn't mention them either.

Okay, here is a proper answer to a tricky question.
Documentation
First of all, you should read the following two documents, if you haven't already:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
https://www.drupal.org/node/224170

Simple Wildcards
By using % as a path wildcard you are instructing the menu_router matching algorithm to use the path argument as it is (used mostly for numerical arguments). So, following from your comment, yes, it does have a significance. If you write your code like this:
$items['admin/config/mapper/%/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

you are going to get the 3rd part of your path as an argument to your mapper_form_mappings function. Exactly as it occurs in the path.
Auto-Loader Wildcards
Now, if you would use a %NAME type of wildcard, like taxonomy does, you would be triggering the 'Autoloader Wildcards' (a.k.a. 'Wildcard Loader Arguments') functionality. Drupal will try to load an object through a function called NAME_load. In the case of the %taxonomy_vocabulary_machine_name Drupal will try to load a vocabulary using the specified machine name as an argument to the taxonomy_vocabulary_machine_name_load function. The loaded object will then be passed as an argument to drupal_get_form (or any other function defined in your path definition).
Current problem
In your case, your original code:
$items['admin/config/mapper/%tid/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

implies there is a tid_load function that will receive the %tid argument from the URL and should return some object to drupal_get_form. This is however not working, since such a function does not exist.
Alternatives using wildcard loaders
If you want to use the 'Auto-Loader Wildcards' functionality, you should do one of the following:

Use an existing _load function, e.g. taxonomy_term_load. Your wildcard should be called %taxonomy_term in this case and the final argument passed to drupal_get_form would be an taxonomy term object.
Use a custom _load function, e.g. mapper_load. Your wildcard should be called %mapper in this case and the final argument passed to drupal_get_form would be whatever your mapper_load function returns.

Best of luck!


get url() to translate the alias Ok, I have my own menu on my multilingual site. I have a page with the alias "about" in english. And english is my default language. So, when I am browsing the site in spanish I would like the spanish alias. I have tried all combinations I can think of to get the url() fucntion to translate "about" to "acercade",as it is in the system. What would be the correct way? Is it even working?

  url('about',array=("absolute"=>TRUE, "alias"=>TRUE)) ;

thats my best guess.

Thanks for any hint,
Michael

No need for $options['alias'] = TRUE, that will prevent alias lookup.

  If you provide an internal path and $options['alias'] is set to TRUE,
  the path is assumed already to be the correct path alias, and the
  alias is not looked up.

Use the node/$nid path and let Drupal find the correct alias.

If that doesn't work, you could try manually passing the $options['language'] parameter

  'language': An optional language object. If the path being linked to
  is internal to the site, $options['language'] is used to look up the
  alias for the URL. If $options['language'] is omitted, the global
  $language_url will be used.

https://api.drupal.org/api/drupal/includes%21common.inc/function/url/7


Make blog available to authenticated users only I have a site which lists some events in a block using the agenda module.  I have this set to be the main content (eg taking up the center of the page).  This is the only content I would like general visitor to see.

I would like to use the same site to have a private blog which is only available to logged in users.

Is there a  way I can restrict viewing of the blog pages to anyone not logged in?

I have tried simply removing the view content permission but this causes other issues!

Would the 'Content Access' module be what you are looking for?

http://drupal.org/project/content_access

Using this you would be able to set your Blog content type to be viewable only by registered users.


When do hook_views_data() and hook_views_data_alter() get called? I'm working on a site I inherited that has a functioning hook_views_data_alter() implementation. I can see things in the Views editor that it has added. However, I cannot figure out how on earth to get that function to be called again so I can change the data. I am running xdebug with a breakpoint in the function body, and nothing I do, from editing a view, to adding a relationship, to clearing the cache or rebuilding the registry, trips that breakpoint. Not even putting module_invoke_all('views_data_alter'); in index.php. What do I need to do to get Drupal to run that hook again?

In case anyone else is making the same mistake I was, here's the answer.

First of all, hook_views_data() will not ever, ever be called if you put it in yourmodule.module. It has to be in yourmodule.views.inc.
You should probably implement hook_views_api() to tell Drupal where your yourmodule.views.inc file resides. Do so like this:

function yourmodule_views_api($module = NULL, $api = NULL) {
  return array(
    'api' => '3.0',
    'path' => drupal_get_path('module', 'yourmodule') . '/includes/views',
  );
}

This tells Drupal that yourmodule.views.inc can be found at /yourmodule/includes/views/yourmodule.views.inc. If you don't use hook_views_api(), put the .inc file in the same folder as your .module file.

Once you have this set up, yourmodule_views_data() will be called when you clear the caches.


How to get user current location and display node attached with current location? I am developing a deal based site in drupal 7. I am using addressfield, geocoder, leaflet and views module to display deals node on leaflet map.

I am able to attach exposed filter "city" so that use can search deals on specific city but I want it like groupon site, where they recognize visitor city and displaying all deals related to visitor current city.

How can I get user current city and display all content related to user city on leaflet map and node view.

Thanks

You might want to use SmartIP to get the ip/location of the visitor. Or enter a location in the user profile.

Then in the leaflet view, as filter use proximity. This way you can select the distance from the user to the node you want to filter on.


How to render mini panel in custom template programatically? I have a minipanel and I have a custom template. How can I render minipanel in my custom template programatically?

Mini Panels are available as blocks. So you'd be rendering it in the same way you render any block programmatically in Drupal 7.

Use

$block = module_invoke('panels_mini', 'block_view', 'machine_name_of_mini_panel');
print $block['content'];