Redirecting from example.com to example.com/drupal I have Drupal 7 installed in a ./drupal directory in my web server (shared host).

I would like www.mysite.net to be redirect to www.mysite.net/drupal in a transparent way for visitors. They should see in their navigation bar www.mysite.net instead of www.mysite.net/drupal.

I also want clean URLs to work. To make clean URLs work, I have edited my drupal/.htaccess file and uncomment this line:

RewriteBase /drupal

I read a lot of posts about having Drupal in a subdirectory, but the suggested solutions don't work (they cause an internal server error, or problems with CSS and images). Most of these tutorials are based in 2 htaccess file, one in the root directory and one in the directory where Drupal is installed. They also required to change $base_url in settings.php.

Try in .htaccess and make sure RewriteEngine On

RewriteRule !^drupal/ drupal/%{REQUEST_URI}

Then try example.com if this maps to example.com/drupal/

I think RewriteBase /drupal will not produce the result.

It should be either RewriteBase / or commented in the case above.

I have gone through this issues deeply and fixed on my end.

Put following rule to your .htaccess on root.

RewriteEngine On
RewriteRule !^drupal/ drupal/index.php?q=%{REQUEST_URI}

The default .htaccess of Drupal is restored to original.

After this setup css and image will fail those are depending on $base_path.
I then override $base_path value from /drupal/ to / using hook_init()

function my_custom_module_init(){
   global $base_path;
   $base_path = '/';
}

And this is fixed.


How can anonymous users be allowed to post while still maintaining content integrity? A little background: As you see on http://charlotte.ebayclassifieds.com, if you click 'post an ad' and then choose a category, you can fill out the form and submit content without having to sign up.  This is all done and managed by sending validation emails to the email address field which, when clicked, allow a user to manipulate their content.

Can similar functionality be achieved in Drupal. I don't mind writing a module, but before I do, I want to make sure I am not reinventing the wheel.

I have a Drupal based local classifieds site for my community at http://www.gastonia.com.  The site is growing in anonymous traffic, but few users are signing up to post. After a couple feedback loops with the community, almost everyone is saying that the one barrier to entry is having to sign up for an account, check email, validate, figure out how to navigate to post an ad, etc - indeed there are 7 steps necessary to go through before an ad actually gets published.  It's too much..

We have reworked the architecture to be able to get it down to two clicks - click to post, then click to save. More specifically, a user clicks on 'Add content' and the node/add form pops up (there is now only one content type in the new architecture); Then, when they are done, they click save.

Originally I thought about the Inline Registration module, but it is still in DEV and the logic really is not there to support if the user comes back to post again with the same email address (without loggin in). I could alter it, but then we are back to writing a module.

I also thought about Rules - could rules handle similar functionality as the ebayclassifieds site or what I am trying to do? It would all be based on an email filed in the node/add form (CRUD functionality).

What direction or recipe would you suggest to achieve the functionality? Of course the ultimate goal here is to allow anon users to post; create an account behind the scenes for future use; allow use of the anon form even for users with emails that already have accounts (and assign content accordingly.) all while maintaining the security (from spam, bots) that is afforded by having a user sign up and authenticate an account.

EDIT: 4/1/2013
Gisle Hannemyr has revived the Anonymous Publishing module which is very close to achieving the goals described here and in other posts. Please take part in the the thread to provide some community feedback as to how to make the module bug free and better:
http://drupal.org/node/1957644

I don't think this is possible with rules alone.

You need to alter the submission form in order to capture the verification email address, and you also need some logic to ban spammers and recognise returning visitors.

I am the maintainer of a project named Anonymous Publishing. It looks as if this module does what you want.

It still in development, but a Drupal 7 version has been used at several of my production sites without any issues. Please check it out.

You may also want to look at the answers under this question.


CleanURL issues even after disabling it So I recently transferred my site to a new server and disabled cleanURLs because of facing many errors. But due to this, I'm facing multiple issues:

Sometimes (not all the time)- when I save a form in the admin (editing user profiles/nodes/content etc.), the page redirects to a cleanurl (even though it's disabled) - for example www.example.com/admin/people instaed of www.example.com/?q=admin/people - I have no idea why this randomly keeps happening
When I upload user pictures for users and set Image style as thumbnail, the original image gets uploaded properly, but the thumbnail never gets generated adding to the fact that the image path generated for the user is absurdly as follows: www.example.com/?q=sites/default/files/styles/thumbnail/public/pictures/example.jpg - Is this because of cleanURLs again?
Moreover, I can't even re-enable cleanURLs since it gives me a negative test result.

I tried replacing the .htaccess file and it didn't solve the issue. Maybe it's my server configuration?

Even yet, I don't want cleanURLs enabled at all. So how do I fully disable it? Or is disabled anyway and this is some other issue?

Please help! Thanks.

You can force clean urls to be Off with the following line in your settings.php file. Add the following to the end -- this settings overrides even whatever is in your database; be sure to remove it later.

/* Turn off clean urls */
$conf['clean_url'] = 0;

Whether or not your webserver supports Clean Urls depends on its' configuration. I recommend reviewing the Getting Started with Clean URLs Guide.


responsive tabs (tab to accordion on small screen width) I have a task of building a responsive website with custom theme and all that good stuff. One thing I stumbled across is using tabs to display data.

Tabs are a requirement in the site but they are not responsive. I have seen some wordpress sites that have this nice feature of turning tabs into accordion when the screen width is small.

Unfortunately I could not find a way to implement that in Drupal so far. The only way that I thought of is loading to view blocks (1 tabs and 1 accordion) and show/hide one of the two based on screen width using JS but this solution is not an efficient one.

Please let me know if there is a way in which I can accomplish this task.

Short way : download Easy Responsive Tabs to Accordion Jquery plugin, add it to your theme and call the easyResponsiveTabs function for your HTML tabs markup.

Drupal Solution with Panels : use Panels responsive tabs to accordion, a sandbox project which provides a Responsive Tabs to Accordion Panel style.

Install Panels module.
Install the sandbox project. This was a quick done project (no time to develop the admin options) so you may have to modify a few lines in responsive_tabs.inc to set up the paths to css or js files and/or HTML markup in responsive_tabstoaccordion_panels.js.
Go to  your region Panel style and choose the new style Responsive Tabs to Accordion


Correct way to use hook_menu_alter What is the correct way of using hook_menu_later.

I did this in my module to redirect (see also redirect in hook_init makes body text disappear):

function MYMODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'citykidz_node_page_view';
}

function MYMODULE_node_page_view($node) {
  if ($node->type == 'event') {
    if ($items = field_get_items('node', $node, 'field_event_date')) {
      $date = date_create($items[0]['value']);
      drupal_goto('news/events/day/' . date_format($date, 'Y-m-d'));
    }
  }
  else {
    return node_page_view($node);
  }
}

And this got me wondering: what if other modules are also overriding hook_menu_alter and setting their own page callbacks on 'node/%node'? Or even on access or whatever. This is the standard Drupal way of doing things, but surely it will lead to problems (that can be hard to detect). I see there is a module Chain Menu Access API that addresses this. Has anyone had success using this module? And has this issue been addressed in Drupal 8?

If two modules are altering the same menu item / form / page etc, last one will "win".

If you need some control over this, and are expecting collisions, you need to implement hook_module_implements_alter:

  This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

Do your best to have your hook fire last, and if menu item you are altering does not look like the one you are expecting (it was altered already), write a warning message to watchdog.


Dynamically change the "access denied page" title and body This is not a question about changing or preprocessing the twig template of the 403 page.
I have a controller with an access function called by the _custom_access key of my route.
In some circumstance, this function is returning AccessResult::forbidden("a good reason"); which lead to my default 403 page.
Most of the case, this is the behavior I would like to have, but in few cases, I would like to have another title and another message for this page like "You can not access because you eat too much chocolate"
Should I create a new custom error route and send a new response to this route from my access function? (hint: I tried without success)
Any idea?
Edit to add: Thanks to 4k4, I have added a custom ExceptionHtmlSubscriber extending DefaultExceptionHtmlSubscriber in order to override the on403() method.
Here is my code:
class TXSExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber {
  /**
   * {@inheritdoc}
   */
  public function on403(ExceptionEvent $event) {
    $my_condition=extract_from_event($event);
    if($my_condition){
      // I am not sure it is what should be done here
      $this->makeSubrequest($event, '/my_custom_error_path/my_custom_error_code', Response::HTTP_FORBIDDEN);
    }else {
      parent::$this->on403($event);
    }
  }
  /**
   * {@inheritdoc}
   */
  protected static function getPriority() {
    return 1000;
  }
}

So far, I have 2 questions:
1-Unfortunately my custom on403() method is never called (on the other hand, the on403() method DefaultExceptionHtmlSubscriber is called): What I am missing?
2-Let say that my custom on403() method is called: what should be the code to redirect the user on my custom 403 page containing my custom message (ie: it could be nice to display the reason of the AccessResult AccessResult::forbidden("a good reason");

Access functions are only for calculating access results. You can't do anything else because this function is called multiple times, not only for incoming routes but also for outbound links.
To set a response use on403() of an ExceptionHtmlSubscriber. You can also set the result of a sub-request if you want a themed 403 message. See How can we catch the acces denied exception?
Edit: Answering further questions

1-Unfortunately my custom on403() method is never called (on the other
hand, the on403() method DefaultExceptionHtmlSubscriber is called):
What I am missing?

You need to register the service in mymodule.services.yml:
services:
  mymodule.exception_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleExceptionHtmlSubscriber
    tags:
      - { name: event_subscriber }

2-Let say that my custom on403() method is called: what should be the
code to redirect the user on my custom 403 page containing my custom
message (ie: it could be nice to display the reason of the
AccessResult AccessResult::forbidden("a good reason");

You find the message in the exception object:
public function on403(ExceptionEvent $event) {
  // ...
  if ($my_condition) {
    $message = $event->getThrowable()->getMessage();
    $event->setResponse(new Response($message, 403));
  }
}

BTW you don't need to call parent::on403($event) because the parent registered with a lower priority will be called automatically when your event subscriber doesn't set a response.


Provide name for Entity Reference Is there any way referenced entities could be named in a meaningful way?

Currently when I am creating a custom view and need to reference some entity, I have tens of entities that are named exactly the same: Entity Referenced: Referenced Entity (see the picture below).

In such setup there is no way to tell what the referenced entity is before using it. Is there any better way to have referenced entities on the system and still know what they are before using them?

You can read a little bit more info in the Description text: A bridge to the Content entity that is referenced via field_entityref so if you're using different fields you can discern them by the field machine name.

Your theme seems to have the Description text hidden behind an icon. Can you see it when you click on the icon?


Why is the "Recent log entries" report missing? I have a weird problem. I have the same website on two servers, live and staging, and on one server I can access the "Recent log entries" page, but on the other one, it doesn't exists.

On admin/reports/settings, the "Enable access log" is enabled, but the page admin/reports/dblog shows the same page as admin/reports

Any ideas what might be causing this?

Check to make sure you have the module "Database logging" turned on.

THis is sometimes turned off for performance reasons.


How to make a page visible only to users with permission to use the administration theme? I have created a basic page which I only want to be viewable by people who have access to the administration theme.

I have given the page a path of admin/shipping-help but to my surprise the page is visible to anonymous visitors, nor does the page display in the admin theme.

What am I doing wrong?

There are some modules that can help with this: like Content Acess, or Node Access

Node Access
Content Access


Rendered node display for anonymous users? I would like to use a view field (node reference to an og group, configured to display a teaser) as rendered node inside a view and display the view to anonymous users.
Do you know how to achieve this result ?

PS. Currently I can display it for admin user but for non-admin users the view field doesn't appear.

If it is working for admins, but not for non admins, you problem is most likely permission. Do the users have permission to see the node? Maybe they need a special permission to see nodes via relationships?

To fix this, you need to tweak your permissions.

If you want to change the way a field is rendered, either on an entity or in a view, you need to create what's called a field formatter, which essentially is a theming function for fields.


Tag every value of a single multi-value field I have a photo contest website where every participant can upload up to 3 photos. I created a participant node type with a multiple file upload with max 3 entries.

How can I tag/edit/flag individual photos to filter/choose the best ones while they belong to a single node? How can I accomplish this? Is there any contributed module to help me, or do I need to change the logic?
I thought that a solution could be that every photo needs to be a separate node linked to participant's node through entity reference, but how do I create 3 separate photo nodes on a single form submit?

Thanx

you could create a form with multiple file upload fields, and on submit have it create three nodes, adding the file information to a file field in the new node

Form API

you could take a look at Multi Node Add Module:

  This module provides a new interface for creating nodes where the
  users are able to select the fields what they want to use for creating
  the nodes. It is designed to create multiple nodes in one round, it's
  possible to add more node input rows on-the-fly.

I have never used it, but it appears to do the first suggestion automatically for you. Even if it wasn't perfect, you could modify it into a custom module using it as a framework to build upon

using a temp content type that is only used as a form (for simplicity), or creating a custom form via code or module, you could create a Rule acting upon submit to create three of the actual image nodes, using the field values from the temp content type. If Multi Node Add doesn't work, this has an advantage of the easiest (though probably least performance) way of accomplishing it of these options

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.


Exposed proximity filter in geofield required, but still gives result I've made a view with geofield proximity search. The user needs to fill in a location before I want to show result. So I made the exposed filter required:

But the view gives result, even when nothing is filled in. This is the query created:

SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language, 'node' AS field_data_field_adres_node_entity_type, 'node' AS field_data_field_location_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_location} field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('dealer')) ))
LIMIT 2 OFFSET 0

How can I make sure the query doesn't run if nothing is filled in?

Hope you are using Better exposed filter module and configured as this image.


"Cannot redeclare i18n_variable_set()" I have made multilingual site. When we redirect users to another domain, I see the following error:

  [Sun Feb 02 13:03:40 2014] [error] [client 192.168.1.80] PHP Fatal error:  Cannot redeclare i18n_variable_set() (previously declared in /var/www/html/UNI01JO2012031/sites/all/modules/contrib/i18n/i18n_variable/i18n_variable.module:116) in /var/www/html/UNI01JO2012031/sites/all/modules/i18n/i18n.module on line 894

Please note I am not changing any configuration.

The issue here appears to be that you have installed the same module in two directories:

sites/all/modules/contrib/i18n

and

sites/all/modules/i18n

and drupal is picking them both up.  If this is the case, I would disable the module, uninstall it, delete one of the directories above, and then re-enable the module.  That should clear this up.

If you can't access your site's admin UI at all, then you will have to go in and remove one of the directories directly; I would suggest removing sites/all/modules/i18n as the other directory appears to be being searched first.

ADDITION:  From some line number searching, the Drupal 6 version of i18n.module declares i18n_variable_set() from lines 881 to 894 and the Drupal 7 version doesn't even get that long--ending at line 610.  This coupled with the fact that the i18n_variable submodule isn't even included with the Drupal 6 version has me thinking you have a sorts of module mish mash going on here.

ADDITION 2:

I just installed the Drupal 7 i18n module on a clean install in:

sites/all/modules/i18n

and enabled it and the i18n variable module.  ALL good.

I then copied the Drupal 6 i18n module's code into:

sites/all/modules/contrib/i18n

and....

  PHP Fatal error:  Cannot redeclare i18n_variable_set() (previously declared in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/i18n/i18n_variable/i18n_variable.module:116) in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/contrib/i18n/i18n.module on line 894

so, I would check to see if the same thing is happening on your site and if so, remove the errant Drupal 6 version.  A quick check of the .info files will show you what core version of Drupal they are for.  (And, oops, yes, here I put the Drupal 6 version in sites/all/modules/contrib/i18n and the Drupal 7 one in sites/all/modules/i18n which appears to be opposite of what's happening on your site, but I tried to be as similar as possible :)


Views-based search not returning expected results I've got a Views-based search interface for my Drupal 7 site. I'm noticing when I do a text-based search using the 'search terms' (Search: search terms) field it's only returning partial results.

I've already ensured the search index was rebuilt and cron was run.

My View is set to show all records by default. My other drop-down filters work fine.

It's just the search terms field that only returns partial results. Specifically if you search for a phrase it returns only results from one value of a field list...

Example: if I type 'the grantsmanship center' (without single quotes) it does NOT return all the correct results. However, if I type just 'grantsmanship' (without quotes) it does return the results correctly. Also if I type 'grantsmanship center' without quotes it returns the correct results. If I type "the grantsmanship center" (with quotes) it returns the correct results but puts only 2 items per page (for some reason I don't understand)...it's set to return 10 items per page. All the others return those results paged correctly.

Anyone know what might be going on here?

May depend on your version of Views, as there appear to be some known issues, depending on the Drupal Views version.

Drupal 7: Views search not returning correct results for multiple term searches
https://www.drupal.org/node/1615438
https://www.drupal.org/node/1948510


Create a view in D7 that displays and links the taxanomy term and displays and links nodes associated with the term I'm trying to build out a HTML list menu of taxonomy term followed by nodes associated to that term as a sub HTML list. All items should be linked as well. Can this be done?

Example below:

Taxonomy Term 1

Associated Node 1
Associated Node 2
Associated Node 3

Taxonomy Term 2

Associated Node 4
Associated Node 5
Associated Node 6
Associated Node 7
Associated Node 8
Associated Node 9

Taxonomy Term 3

Associated Node 10
Associated Node 11

Taxonomy Term 4

Views tree

This module provides a tree-based style plugin for Views. It is
equivalent to the tree-based style template from Views 1.
It is based off of the list style. Although it generates a nested
view, there is still only a single query run for the view making it
quite performant.
Compatibility
This module has been tested and used with the following
relationship-oriented modules:

Taxonomy (in core) - parent/child relationships References - node and
user references Relation
references between any entities (D7 only)
Entity reference - references between any entities (D7 only)
Organic Groups (D7 only)

Example:


Routes node.add.CONTENT_TYPE are no longer available starting from Drupal 8.4 in hook_menu_links_discovered_alter()? If you implement the hook_menu_links_discovered_alter() hook in Drupal 8.3 you have access to change the links with a code like this:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function onlyone_menu_links_discovered_alter(&$links) {
    $links['node.add.article']['title'] = t('New name');
}

This code comes from the issue Improve the Add content page for the Allow a content type only once (Only One) module. But starting from Drupal 8.4 the same code gives an error like this:

  Notice: Undefined index: node.add.article in
  onlyone_menu_links_discovered_alter()

I searched inside the Drupal change records but I don't find anything talking about this change.

Now in Drupal 8.4 how you can change a link title?

There are several things I notice here:

An undefined index error shouldn't result just from this code - you're not referencing the array index; just setting it. Does the actual code have a more complex expression which references $links['node.add.article']?
This is not quite correct for this hook (and the linked issue is for 7.x, so it can't be compared). The hook documentation says that the menu item must be an associative array - it should be altered with $links['node.add.page']['title'] = '...';
The array key is not guaranteed to be fixed:

  Since the machine name may be arbitrary, you should never write code that assumes it is identical to the route name.

Therefore you should probably iterate and identify the menu link by the route name instead.

From what I can tell, core doesn't (and never did) define menu links for the node.add.{type} routes. The links on the /node/add page are dynamically generated, and don't actually show up in any menu.

So it doesn't seem to be possible to alter the links on the /node/add page by altering the menu. As you can see from the function below, these links are actually generated in a template preprocessor:

function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = [];
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = [
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', ['node_type' => $type->id()])),
        'description' => [
          '#markup' => $type->getDescription(),
        ],
      ];
    }
  }
}

The only way to modify the link text would be to replace the links in another preprocess function.

Edit: This other answer actually explains how to do that in detail: How to modify the link titles shown in /node/add page?


How to unset field in views conditionally I'm using hook_views_pre_render() in a module to make sure an image field 'field_field_company_logo' is removed for a certain content type 'job_listing'. I have the following code, which works, but produces warnings:

function hideviewsfields_views_pre_render(&$view) {
  if ( ($view->name == 'job_search') && ($view->current_display == 'job_search_results') ) {
    $result = $view->result;
    foreach ($result as $row) {
      $type = $row->_field_data['nid']['entity']->type;
      if ( $type == 'job_listing' ) {
        unset ( $row->field_field_company_logo );
      }
    }
  }
}

It works, in as much as the correct images are omitted, but I get the following warnings:

Notice: Undefined property: stdClass::$field_field_company_logo in views_handler_field_field->get_items() (line 715 of /public_html/sites/all/modules/views/modules/field/views_handler_field_field.inc).
Warning: Invalid argument supplied for foreach() in views_handler_field->advanced_render() (line 1053 of /public_html/sites/all/modules/views/handlers/views_handler_field.inc).
Notice: Undefined property: stdClass::$field_field_company_logo in views_handler_field_field->get_items() (line 715 of /public_html/sites/all/modules/views/modules/field/views_handler_field_field.inc).
Warning: Invalid argument supplied for foreach() in views_handler_field->advanced_render() (line 1053 of /public_html/sites/all/modules/views/handlers/views_handler_field.inc).

I've seen elsewhere people writing code similar to the following:

unset($view->field[$field_name]);
unset($view->display_handler->handlers['field'][$field_name]);

where the first line seems similar to the unset I am executing, but I believe it was acting upon a different variable (i.e. not $views -- maybe $data?) and I can't find any other reference to the image field within the $view object that can be unset without it removing it altogether from the display.

Drill down in the field_field_company_logo field to its ['rendered']['#access'] property and set it's value to FALSE.


How can I create a node in a PHPUnit Test without having to create the node type in PHPUnit I have a node type already created on my site.  I want to create a node with this node type in my PHP Unit test since I am using my database but I am getting errors.  It seems like I may have to recreate the node type in the PHP Unit test first and then create it.

Is it possible to create a node without creating the node type in PHP Unit?

Here is the command I am running to run a PHP Unit test:

php ./core/scripts/run-tests.sh --verbose --php /usr/local/bin/php —-dburl mysql://drupal:drupal@mariadb/drupal --url http://nginx --class "Drupal\my_module\Tests\ExpenseTest"

This is the error:

    Status    Group      Filename          Line Function
    --------------------------------------------------------------------------------
    Fail      Completion ExpenseTest.php     64 Drupal\my_module\Tests\ExpenseTes
        The test did not complete due to a fatal error.
    Pass      Other      ExpenseTest.php     55 Drupal\my_module\Tests\ExpenseTes
        Enabled modules: node, paragraphs
    Fail      run-tests. Unknown              0 Unknown
        FATAL Drupal\my_module\Tests\ExpenseTest: test runner returned a non-zero
        error code (255).
    Fail      Fatal erro Unknown              0 Unknown
        [17-Feb-2018 17:36:34 Australia/Sydney] PHP Fatal error:  Uncaught Error:
        Call to a member function referencedEntities() on null in
        /var/www/html/web/modules/custom/my_module/src/Expense.php:116
    Fail      Fatal erro Unknown              0 Unknown
        Stack trace:
    Fail      Fatal erro Unknown              0 Unknown
        #0
        /var/www/html/web/modules/custom/my_module/src/Tests/ExpenseTest.php(65):
        Drupal\my_module\Expense->__construct(Object(Drupal\node\Entity\Node))
    Fail      Fatal erro Unknown              0 Unknown
        #1 /var/www/html/web/core/modules/simpletest/src/TestBase.php(963):
        Drupal\my_module\Tests\ExpenseTest->testValidation()
    Fail      Fatal erro Unknown              0 Unknown
        #2 /var/www/html/web/core/scripts/run-tests.sh(804):
        Drupal\simpletest\TestBase->run(Array)
    Fail      Fatal erro Unknown              0 Unknown
        #3 /var/www/html/web/core/scripts/run-tests.sh(67):
        simpletest_script_run_one_test('44', 'Drupal\\reo_expe...')
    Fail      Fatal erro Unknown              0 Unknown
        #4 {main}
    Fail      Fatal erro Unknown              0 Unknown
        thrown in /var/www/html/web/modules/custom/my_module/src/Expense.php on
        line 116
    /var/www/html/web $

This is my code:

<?php

namespace Drupal\my_module\Tests;

use Drupal\simpletest\WebTestBase;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\my_module\Expense;

/**
 * Tests views contextual links on nodes.
 *
 * @group reo_expense
 */
class ExpenseTest extends WebTestBase {

  /**
   * Node object
   *
   * @var /Drupal\node\Entity\Node
   */
  protected $node;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node', 'paragraphs'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->node = $this->createMyNode();
  }

  /**
   * Tests contextual links.
   */
  public function testValidation() {
    $expense = new Expense($this->node);
    $this->assertEqual($expense->getRegionId(), 4);
  }

  /**
   * Create Expense node.
   */
  public function createMyNode() {
    // Populate defaults array.
    $settings = [
      'title' => 'asdfasdf',
      'type' => 'expense',
      'uid' => \Drupal::currentUser()->id(),
    ];
    $node = Node::create($settings);
    return $node;
  }
}

When you create a node, you need to reference a bundle that already exists. In your case, you are referencing a bundle (expense) that is created from a custom module, but that module is not installed.

If you look at the tests for the Node module, you will notice they always install the Node module. In the test classes that expand the NodeTestBase class, that is done from that class. In other test classes, for example the NodeFieldAccessTest class (a Kernel test), that is done directly by that test class.

In your case, changing the list of modules to install to the following one would solve the issue.

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node', 'paragraphs', 'my_module'];

From the error messages, I take the machine name of the module creating the content type is my_module. If that is not correct, replace my_module with the correct machine name.


Inline Entity Form Order by field value I'm attempting to sort the form table generated by IEF by the value of a specific field - but running into a stumbling block (in other words - it's not working). Has anyone else used the hook_inline_entity_form_table_alter and sorted by a field value successfully?

I did it using hook_form_alter().

If you have a field with an inline entity form:

$form['field_newsletter_content'][LANGUAGE_NONE]['entities'];

Then you can change the '#weight' property on the individual entities.

So, to change the weight of element 0 to 1, do this.

$form['field_newsletter_content'][LANGUAGE_NONE]['entities'][0]['#weight'] = 1;

And if you change the weight of element 1 to 0, then they will have traded places in the inline entity form.


How do I change the uploaded file name after the node has been saved? How can I change the name of an uploaded file after the node has been saved?
I know there is the FileField Paths module for this purpose, but it's still buggy for Drupal 7. I looked at the source of the module, but I can't extract the necessary code.

The only thing I know is that I  should use hook_node_update() and field_attach_update(), but I don't know how to use them.

Perhaps this will help you.  Last night I wrote a code which is meant to auto-generate a file and attach it to the node.  When the node is about to be saved, the function removes the uploaded file from the node and creates and attaches the new file.

In your case, you might be able to just update the file name with file_copy and resetting the filefield.

    function MODULE_node_presave($node) {
    /*
    *  Out with the old - detach file object
    */

    if (isset($node->field_filefieldname['und'][0]['fid'])) {
     file_delete(file_load($node->field_filefieldname['und'][0]['fid']));
    }
    unset($node->field_filefieldname['und'][0]);  //just for good measure

    /*
    *  In with the new
    */

    $filename = 'newfilename.dot';
    $filepath = conf_path().'/files/yourpath/';
    $touchout = $node->title;

    $tempFile = file_directory_temp().'/'.$filename;

    file_put_contents($tempFile, $touchout);

    $file = (object) array(
        'uid' => 1,
        'uri' => $tempFile,
        'filemime' => file_get_mimetype($tempFile),
        'status' => 1,
        'display' => 1,
      );

   /*
   *  File save operation, puts file in /sites/default/files and records update in db
   */

    if (file_prepare_directory($filepath, FILE_CREATE_DIRECTORY)) {
     $file = file_copy($file, 'public://path/'.$filename, FILE_EXISTS_REPLACE);
    }

   /*
   *  Reattaches our severed file, good as new.
   */

    $node->field_filefieldname['und'][0] = (array)$file;
    }
    ?>


Record video clip from webcam in Drupal 7 custom module I want to capture the video clip from webcam in my own Drupal 7 custom module. Is there any way to capture the webcam and record the video clips in Drupal 7? Please, anyone can help me on this?

Thanks in advance.

There is Media: Webcam

  This project (still under active development) will add a Webcam
  capture tool for video and images to FileField. Video requires a Red5
  or Flash Media server to also be available; documentation for this
  coming soon enough.

Browse the SOURCE to get some inspiration.


How to access entity from EntityReferenceItem? I have the attached array below and need help figuring out how to access the 'entity' attribute that is under the protected "properties" array (see screenshot).

I am using the Viewfield module

background:
field_name is an entity reference field. I need to get the EntityReference so that I can call getTarget() to get the EntityAdapter and then call EntityAdapter->getValue().

I have tried the following but they all give errors. The idea is to get the EntityReference which is the 'entity' value. How can i do this?

mytheme_preprocess_viewfield_item(&vars) {

  $element = $vars['element'];
  $results = $element['#content']['#view']->result;

  foreach($results as $row) {
    $entity = $row->_entity
    $offset = $entity->get('field_name')->offsetGet(0)

kint($entity->get($video_field_name)) /* result of screenshot */

    $entityReference = $offset->get('entity') /* failed */
    $entityReference = $offset->getProperties() /* failed */
    $entityReference = $offset->getEntity() /* failed */
    $entityReference = $offset->getValue() /* failed */
  }//end foreach
}//end theme_preprocesss

The error message is: replace getValue() with any of the above

Call to a member function getValue() on null

If entity in the foreach loop is not empty you should be able to do

$entity->field_name->entity
//or perhaps
$entity->field_name->referencedEntities();


How can I send an e-mail to the admin when use of a view results in an error? I have a large number of complicated views on a site, some of which, when searched with certain options or by certain users, give the following error:

  An illegal choice has been detected. Please contact the site
  administrator.

Is it possible to somehow catch this error and email the admin?  Ideally, I would be able to include the URL of the view causing the problem and the UID of the user accessing the view for troubleshooting purposes.

You are describing hook_watchdog(array $log_entry):

  This hook allows modules to route log events to custom destinations, such as SMS, Email, pager, syslog, ...etc.

emphasis mine.

Inside it, you can use $log_entry array to get UID and request URL, and you can also use global $user, and you can call current_path(), so both your requirements seems doable.

$log_entry array is defined as:

  $log_entry: An associative array containing the following keys:

  type: The type of message for this entry.
  user: The user object for the user who was logged in when the event happened.
  uid: The user ID for the user who was logged in when the event happened.
  request_uri: The request URI for the page the event happened in.
  referer: The page that referred the user to the page where the event occurred.
  ip: The IP address where the request for the page came from.
  timestamp: The UNIX timestamp of the date/time the event occurred.
  severity: The severity of the message; one of the following values as defined in RFC 3164:

  WATCHDOG_EMERGENCY: Emergency, system is unusable.
  WATCHDOG_ALERT: Alert, action must be taken immediately.
  WATCHDOG_CRITICAL: Critical conditions.
  WATCHDOG_ERROR: Error conditions.
  WATCHDOG_WARNING: Warning conditions.
  WATCHDOG_NOTICE: Normal but significant conditions.
  WATCHDOG_INFO: Informational messages.
  WATCHDOG_DEBUG: Debug-level messages.

  link: An optional link provided by the module that called the watchdog() function.
  message: The text of the message to be logged. Variables in the message are indicated by using placeholder strings alongside the variables argument to declare the value of the placeholders. See t() for documentation on how the message and variable parameters interact.
  variables: An array of variables to be inserted into the message on display. Will be NULL or missing if a message is already translated or if the message is not possible to translate.

There is no way I know to get form ID of a form that created your error, I don't think it is in ['variables'], so the best you can do is to parse ['message'] for "illegal choice", and test ['request_uri'] and ['referer'] for pages that are your suspects.


Setting up a date field to require an end date I'm attempting to create a custom content type for a module via hook_install. When I create a date type (from Date module), I want it to require an end date (there's a checkbox when you're setting up the field via the gui). This is the settings array for the field:

'settings' => array(
    'enddate_get' => 1,
    'enddate_required' => 1,
),

This isn't working (the widget is still only asking for one date), so I'm guess that I have the wrong settings. Does anyone know how to properly set this up?

I believe you would need to setup the requirement on the form you are building for the custom content type so you would add this to the date_end form entry:

$form['CUSTOM_CONTENT_TYPE']['DATE_END'] = array(
...
  '#required' => TRUE,
...
),


How to filter 1 view with two fields based on 1 contextual filter? I having a view which result in a table with three fields like:

                 field1, field2,field3
row1 with values 100,    110,   503
row2 with values 200,    520,   110
row3 with values 300,    530,   210

All numbers are nid. All fields are in different node types.
I'm calling /foo?nodeid=110.

I'm trying to setup a view so that row3 is not displayed anymore and I can eventually have a table with row1 and row2 with the values of field1.

I tried a lot but do not get it. If I have one contextual filter I can filter the table on field2 and if I have another contextual filter I can filter on field3. But I cannot combine them like a normal filter like and/or.

Any suggestion how to solve this?

Note: For now my view is a table but in the end I will use it under webform so it then will be a webform display with a webform selection list.

Try Views Argument Substitutions. It lets you use contextual filter values in the regular filters.

Add a Global: Null contextual filter to get your default value. It's very important to use Global: Null so the view isn't filtered.
In your regular filters, you can add that value with * * * 1 * * * (no spaces) so that you can add AND / OR stuff. Use a different number if your Global: Null isn't at the top of the contextual filter list.


Drupal 7.36 configuration error: Call to undefined function field_attach_load() I tried to configure Drupal 7.36 with WAMP and result back with the below error after clicking "configure site". I am using Window7. Please help!

Fatal error: Call to undefined function field_attach_load() in C:\wamp\www\sdg\includes\entity.inc on line 320

It looks like this issue has cropped up because of a myriad of potential causes, and some have been fixed while others have not.
The first step, assuming this is an installation from scratch, would be to empty your database and try again.  I've had the initial install go wrong once and just trying again went fine.
There is an extensive list of fixes at https://www.drupal.org/node/481758.  In the unlikely case of Drupal's issue queue going away, here is the main text.  I'd recommend going to the link and reading through the (extensive) comments to see if specifics match your situation.

In certain circumstances, the following error (or something similar) may be displayed during the installation process:

Fatal error: Call to undefined function field_attach_load() in ~\modules\user\user.module on line 270

This error seems to be caused by a problem during the Drupal system installation, causes installation to fail after only creating 31 database tables, and will make requests to the front page of the site display a 'Page not found' error. This seems to happen as a result of various different configuration problems, browser issues, etc. Some of the things you should try to change before throwing your hands up in frustration:
7: Make sure you're not reaching the configured max_execution_time for PHP is not being reached.
25: Switch back to the default php.ini, restart Apache, and see if install works.
27: Make sure dependencies[] = field is defined in your install profile's .info file.
34: Using a different browser (e.g. use Chrome instead of Safari) during installation may help.
36: Switching the bundled jQuery to version 1.7.1 might fix the problem, at least for Safari users.
37, 42, 54: Dropping the entire database and installing again might fix the problem.
45, 141: Limiting the database name length to < 8 characters may fix the problem.
57: Make sure the database user Drupal is using has all permissions for the database (GRANT ALL ON [db]).
59: Make sure your browser's cookies are enabled when performing an installation.
61: Restarting php-fpm fixed the problem.
66: Setting the $cookie_domain variable in settings.php fixed the problem.
82: The problem could be related to install.php not loading field.attach.inc at whatever bootstrap level it is running at.
88: Make sure the $base_url variable in settings.php is correct.
92: Ensuring the database name had only lowercase ASCII characters fixed the problem.
108: Make sure your Apache configuration doesn't do anything that might cause cookies to be dropped.
135: If it's an install in an existing Drupal directory, temporarily move all the modules in sites/all/modules out of the Drupal tree while installing.
137: Disable the php opcache module before proceeding with installation As you can see, there are a TON of different things that can cause this issue. The root cause is installation
fails during module installation, and won't ever continue past that point until the database is dropped and recreated again.


Page title unable to overwrite default title admin/config/search/page-title - Global default title is abc

admin/config/search/page-title - Content type BOOK -> title is def

meta tag -> Content -> page title is ghi

meta tag -> Content -> BOOK -> page title is jkl

content type BOOK -> create new node -> page title -> mno

In the website(Content type Book), the title always shows abc.

I want to edit title, may I know how?

Many Thanks.

function mytheme_preprocess_page(&$variables) {

  if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'form_id') {
    if (arg(0) == 'node' && arg(2) == 'node-type') {
    drupal_set_title(t('Your title'));
    }
   }
 }

you can use dpm($variables) to find form id. This for changing page title.

For changing header title i.e the title displaying in tab, below code can be used

function mytheme_preprocess_html(&$vars) {
  if (!empty($vars['page']['content']['system_main']['#form_id']) && $vars['page']['content']['system_main']['#form_id'] == 'your_form_id') {
    $vars['head_title'] = t('title');
  }
}


Token for email includes name of field Ok, so I've got this webform sending an email upon correct submission.

I'm trying to format the email so that it can send to a user who submits a form.

This email would say something like "Hi, Name, thanks for submission!"

I am trying to use the following:

Hi %email[name]

And the email is coming out like this:

Hi

name:

PersonNameHere

Why is this happening? Shouldn't the name come out without the field name?


Show what views a node is in I have created views called 'Awards' and in these award views they reference 'food item' nodes. Within the view a food item can be 1st, 2nd, 3rd, depending on certain filters/reasoning to create this list.

So, if a food item is 1st in an Awards view, how can I automatically put this on a 'food item' node to show that this food item has won an award?

More info on the views

They are created and sorted/filtered by specific things, one view might be 'Most calorific meal' and then it just lists meals by calories in them. Then I get a 1st, 2nd, 3rd. So if hamburger comes up as 1st, I want to put a badge on the hamburger food item node saying it's 1st in the Awards section for: Most calorific food item.

You could probably do that with Views, clone your Views into three Block Displays, one for each prize (1st, 2nd, 3rd).

Limit the Pager to show only one result, but for 2nd and 3rd set the Offset value to 1 and 2 respectively.

Use Contextual filters to pull node info into the View (node that the Block will be displayed on, basically all food item nodes). Set the Contextual filter settings to Hide View if there's nothing to see, in other places possibly as well.

Then display all 3 Blocks on food item nodes. If there's a "hit" for any prizes the relevant Block will be displayed on that node. If not, then the hiding should take care of it.

I don't think there's a contextual filter for Views counter, that goes a bit reverse, context from Views. It might be useful here, but alas no go.

All that said, depending on your project structure, there are probably better ways of solving this. Flag and Rules modules come to mind. You could create 3 flags, and use Rules to programmatically assign flags based on criteria (they wouldn't be flags that users use).


URL path settings not supporting more than one level I'm trying to edit and create content on my inherited Drupal site and when I enter an address into the "URL Path Settings' URL Alias" field, it will not save the first part of the desired URL.
For example if I enter "firstpart/contentname"
it just saves "contentname" instead of the full hierarchy.

That's strange. If you edit the URL alias manually, it shouldn't be automatically changed unless you bulk delete and update your URL aliases in Pathauto.

Have you checked your Pathauto pattern settings (/admin/config/search/path/patterns) to see if there is something overriding your changes?

You said that you inherited the site. Are there any URL/path-related modules that your predecessor has enabled?


How to modify an existing view join? I am trying to modify an existing views join.

Let's say I am trying to remove the 'langcode' condition.

What I have so far:

function mymodule_views_query_alter(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\query\Sql $query) {
    $joindata = $query->getJoinData("node__field_joined_whatever", "node_field_data");

//$joindata contains the join I need, so far so good

    foreach($joindata->extra as $ix=>$val) {
      if (isset($val['field']) && $val['field'] == 'langcode') {
        unset($joindata->extra[$ix]);
      }
    }
//here I have modified join object, but there is nothing like '$query->setJoinData()'
...
}

Does anybody know how to put my modified join back to the query?

Usually, you should control join type using views Advance relationship options. By enabling "Require this relationship" you are telling Views to use "INNER" Join instead of using "LEFT" Join. If this option is somehow not working here is how I would solve this problem.

use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\query\QueryPluginBase;

function hook_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   // check your view ID:
if ($view->id() === 'id') {
 //Get your table info object;
  $table = $query->getTableInfo('table');
if (isset($table['join']->type) && $table['join']->type === "INNER") {
//Change your Join type;
 $table['join']->type = 'LEFT';
   }
 }
}


How to style the default upload button? Problem

I want to style the default upload buttons. How should I go about doing this?

Since this was a bit of pain to work through I thought I'd post a solution for everyone.

The base of the solution comes from this post:

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

There are is another solution to CSS only styling for upload buttons, but it involves wrapping the input element in a label, which is difficult
with how Drupal handles the markup.

1. Add CSS

First we add the following two chunks to our CSS file, you can read through the explanation at the post above basically we're making the file input button transparent and styling the area behind it.

Then when you try to click on the area behind it, you actually click on the invisible input button.

.form-type-managed-file {
  position: relative;
  overflow: hidden;
}

input.form-file {
  position: absolute;
    top: 25px;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}

Now you may have noticed that we want to style the area behind it. To that we're going to need to add an HTML element to the managed file output which we can then style:

2. Change HTML output

Copy the image file function into our template file (for this example we'll be changing the image upload style) and then add two divs after

function MY_THEME_image_widget($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '
';

  if (isset($element['preview'])) {
    $output .= '
';
    $output .= drupal_render($element['preview']);
    $output .= '
';
  }

  $output .= '

Choose File

No File Selected
';
  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' (' . format_size($element['#file']->filesize) . ') ';
  }
  $output .= drupal_render_children($element);
  $output .= '
';
  $output .= '
';

  return $output;
}

If you don't care about the filename of the uploaded file remove the second div and you're done. (You'll need to alter the CSS to make the invisible button sit above your added upload div.)

However if you want the name of the file then leave it in and we move onto a little JS.

3. Add JS

It's impossible the get the name of the file without JS so we add a quick JS script to get it to run, first we call it in the template file:

function MY_THEME_preprocess_page (&$vars) {
    drupal_add_js('sites/all/themes/MY_THEME/js/file_upload.js', 'file');
}

Then we add the following script:

(function ($) {
  Drupal.behaviors.uploadfunctionAddClass = {
    attach: function (context, settings) {
      $(":file").change(function(){
        $(this).prev().text($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    }
  };
})(jQuery);

It looks for any changes to elements of type file, which in the output for a drupal managed file field is one.

Grabs the element directly before it (the second div we added in step 2) and changes the text in it to it's new value. The path will have C:\fakepath\ added to it, so we remove that as well.

The reason we use Drupal Behaviors rather than document ready, is because we need the script to apply after an AJAX call. If someone uploads a picture, removes it and adds a different one then the script won't have applied to the new elements because they've been added with AJAX. The Drupal Behaviors wrapper causes them to be called every time.

Congrats we're all done.


Customizing menu html How do you set an id for the menu's root <ul> tag?

I know about the module "Menu Attributes" but that doesn't let me add an ID to the root <ul>, or at least I do not know how.

Also, I've seen a solution which uses theme_menu_tree() and a regex check, but that's just too hacky for my taste.

In D7 default theme bartik, you can see the main menu is rendered using a theme hook links__system_main_menu:

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

links__system_main_menu is a theme hook pattern of the form [base hook]__[context].
When links are themed with theme('links__system_main_menu', $vars), theme() will search for and use theme_links__system_main_menu() if it has been defined. If not, it will use theme_links().

Drupal will use MYTHEME_links__system_main_menu(), if you define it in your theme.
Thus, you could implement the hook_links__system_main_menu as follows. Probably you will do that in the template.php file in your theme folder.:

function mytheme_links__system_main_menu($variables) {
  $html = "
\n";
  $html .= "
\n";
  foreach ($variables['links'] as $key => $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "
\n";
  $html .= "
\n";

  return $html;
}

This will override the links__system_main_menu theme and customize HTML output for the main menu.

[Edit]

If you are looking for the quickest way, you just need to tweak your page.tpl.php by adding an extra wrapper to the menu ul.
For example, in the Bartik theme,

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>

Then, you can access it using #your-id ul{ } in CSS or $('#your-id ul') in JS.
But, the above code is just for example, you should not hack the core themes or modules.
I assume you have your own theme.


How do I change the views ajax URL? I build a view page and have exposed filter, when I change any filters I use ajax to fetch data and re-build the content area. The ajax URL looks like

  views/ajax

I want to change the above URL to some external middleware something like below

  http://www.example.com/getData

with the existing post data. Is it possible?

You can try changing the settings data on the ajaxSend event.

$(document).ajaxSend(function(event, request, settings) {
  settings.url = '/views/ajax';
});


Which SQL query should I use? I want to get the number of rows where the "value" field is equal to 1, and output its number  and all the content_id where  value_type is option in table votingapi_vote.
the following is my code, but it doesn't work.

$result = db_query("SELECT content_id,count(value=1) FROM {votingapi_vote} WHERE value_type = '%s'" , "option");

while ($obj = db_fetch_object ($result)) {
  return $obj->content_id.'<br>'.'$obj->count';
}

it showed an error.  when i delete the filed value in the query. it only output one result of $obj->content_id/ why? i want to output all the results of $obj->content_id

ps: now, if i want to get this result.

1,get the content_id and descending  it according to the value(the count of each content_id 's value=1 substract the count of  each content_id 's value=0 ,each content_id has many value=0 or value=1)

how to write the query.

First, that condition syntax is just wrong, you need to add that as a WHERE condition. Second, if you want the count per content id, you need to group by that.

And third, you need to collect the output in a variable instead of returning it directly.

Something like this:

$result = db_query("SELECT content_id, COUNT(*) AS count FROM {votingapi_vote} WHERE value_type = '%s'"  AND value = 1 GROUP BY content_id, "option");

$output = '';
while ($obj = db_fetch_object ($result)) {
  $output .= $obj->content_id.'<br>' . $obj->count;
}
return $output;


How to prevent pager_default_initialize from getting initialized? I'm calling this function pager_default_initialize on a certain condition. But once this function gets called, it initializes default pager everywhere I return theme('pager').

What I want is

if(condition == TRUE)
pager_default_initialize($total, $limit, $element = 0) get executed
theme('pager') works!
if(condition == FALSE)
pager_default_initialize($total, $limit, $element = 0) not get executed
theme('pager') should stop work. I don't want pager when condition is FALSE.

but problem is once condition == TRUE gets satisfied, I got pager everywhere.

Any  way to uninitialize this pager function on certain condition?

The easiest way would be to override theme_pager():

function MYTHEME_pager($variables) {
  if (!pager_is_disabled()) {
    return theme_pager($variables);
  }
  return '';
}

Where pager_is_disabled() is a function you write that determines the current status. You could store that info in static vars, a Drupal variable, database, cache, whatever makes most sense for your use case.


Keep modules enabled/installed? I used node_export and UUID to export and then import content from one Drupal 6 site to another.

Do I need to keep these modules enabled for any reason after the import?

On Drupal 6, as per your question, you most likely do NOT need to keep node_export around after your content import/export is done.  It doesn't create any database tables and will only remove config settings variables when you uninstall.

As for UUID it is (depending on  your settings) probably a good idea to keep it around.  It adds/alters some db tables adding its UUID to your content, etc. It would probably be less trouble to keep it rather than remove it and it shouldn't have an impact on the performance of your site.


Receive the error PDOException: SQLSTATE[23000] when trying to update some content text I get the following error when I try to update a static page's content as an Administrator:

"The website encountered an unexpected error. Please try again later."

In the logs, there is an error for type 'node' and type 'php':

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '3' for key 'PRIMARY': INSERT INTO {pinit} (nid,
  description, image, pincount) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3); Array ( [:db_insert_placeholder_0] => 3
  [:db_insert_placeholder_1] => [:db_insert_placeholder_2] =>
  /sites/default/files/Steve155.jpg [:db_insert_placeholder_3] =>
  horizontal ) in drupal_write_record() (line 7166 of
  /home/diversif/public_html/includes/common.inc).

I just updated to the latest version of Drupal, and ran the update script on the database. I also created an authenticated user, and confirmed that they are experiencing the same issue.

I'm not modifying anything in the content other than some text. Are there other logs that I can look into to find the source of the problem, or the solution.?

Looks like an error with the module

pinit

It's inserting a duplicate row for nid into it's database table.

It should probably use db_merge instead.

You may need to raise a bug report with the module maintainer.


View is rendered as "empty" even though the query returns results I've got a Drupal View that I expect to return some results, but when I look at it (logged in as user 1), the empty result message is displayed. I turned on the setting which tells Views to output SQL in the preview. When I run the query directly against the database I get the expected result.

The View uses CiviCRM fields. I checked watchdog and the CiviCRM log for errors and found none.

The query looks like this:

SELECT DISTINCT <long list>
FROM {civicrm_contact} civicrm_contact
LEFT JOIN {civicrm_address} civicrm_address
  ON civicrm_contact.id = civicrm_address.contact_id
LEFT JOIN {civicrm_phone} civicrm_phone
  ON civicrm_contact.id = civicrm_phone.contact_id
LEFT JOIN {civicrm_value_agency_details_5} civicrm_value_agency_details_5
  ON civicrm_contact.id = civicrm_value_agency_details_5.entity_id
LEFT JOIN {civicrm_phone} civicrm_phone2
  ON civicrm_contact.id = civicrm_phone2.contact_id
WHERE ((
  (civicrm_contact.contact_sub_type IN  ('Agency'))
  AND (civicrm_address.city LIKE '%Brooklyn%' ESCAPE '\\')
  AND (civicrm_phone.is_primary <> '0')
  AND (civicrm_address.is_primary = '0')
  AND (civicrm_contact.is_deleted = '0')
  AND (civicrm_value_agency_details_5.accepts_food_donations_144 <> '0')
))
GROUP BY id

I am a little surprised it works at all; the id in the GROUP BY clause seems ambiguous.

Has anyone run into anything like this before? I am not too familiar with the Views codebase. Can anyone recommend where to throw in some debugging code to get a better sense of what's going on? Does Views do any post-query processing -- could it decide not to output what the query returns?

This might work:

Goto Query Settings under Advanced options and disable SQL rewriting.

OR

Try providing the view a default value for the contextual filter under "When filter value is not available option."


How to add a default Field when creating a Content Type? I use to add a image field every time I create any content type. Just wondering if is there any way to add this field by default when the content type is created.

I found the http://drupal.org/project/content_type_extras module which provides some additional features to content types, but it doesn't include this feature.

Not fully what you're asking. But once you have defined your image field you can easily reuse it in any content type. Since defining new content types is not something you do every day, this shouldn't be to much of extra work.


How to setup birthdate field with optional values I want to have a "birthdate" field for my users. It should be optional to enter a year or a date.
If a year is selected I want to display the age. If a date is entered I want to show the birthdate.

If I use the date field and make it optional I can have empty default values. However, as soon as I enter a year it requires the date and month too and vise versa.

Any solutions?

I would define 3 optional selects:
 - Year (now() to now() - 100)
 - Month (1-12)
 - Day (1-31)

Then in a hook_node_validate() I would check if only the year is provided or a full date. Also don't forget to verify if the date is valid (like Feb, 31...) using checkdate( int $month , int $day , int $year ).

Then create a field template to either display the age or a birthdate.


Latest Saved Content keeps appearing on the front-page despite being configured in "content" and "content type" Latest saved content without the title, always appears on the front page even thought in "Content" and "Content Type" it is configured not to show up on the front-page.  The content is also disabled in the blocks, but it still appears on the front page.

By default drupal's frontage shows latest content published on site. In drupal this is a /node path which is a view in drupal 8 and a page in drupal 7. If you are using drupal 8 it will be as easy as justmodifying the view. In drupal 7 you can set a different front page in the system configurations and the latest published won't appear any more.


height of block with view containing exposed filter I have created a block with a view containing an exposed filter (drop downbox, auto submit).
Based on the selection in the dropdown, the visitor will see a short or long list of results. This block is located in the content region of one particular node.

The height of the block does adapt to this result, but unfortunately all elements below this block (i.e. the footer region) do not go below this block. They just remain on the initial height as when the page loaded.

How can I tell the footer to go below the block with the view automatically each time the filter is changed?

Your step-by-step help is highly appreciated!

Regards,
Hans

Some html element wrapping the block has a fixed height. This height gets set the first time you load the page and thereafter it does not change (it could be done by a jQuery script). You will need to hunt it down in your web dev tools and alter it with a CSS rule that sets the height to auto, or you might even have to do it via jQuery.

Try with another theme (bartik) and see if it also happens. If it does not then it is theme related.

If you cant get it fixed then I suggest you create a custom region just below the content region that is used solely for the block. Just use a div for the custom region and only set the width if need be. On a block level element the height should by default be auto.

Look here how to add custom region.


Drupal 7 Views: Align text with image Hello Drupal Stack Exchange crowd.  I am working on building a view for a content type that has several fields and an image. I am using an "Unformulated list"

Using Drupal 7 core and the most recent update of views.

My goal is to align the field image to the right so the text is right next to it.

I have put the text field and image "Inline" in field settings and "remove HTML" formatting and changed the text to "Plain Text". This places the text starting at the bottom right corner of the image but I'm wanting the text to align starting at the top right. I have tried rewriting the field to do this but have had no luck.

It seems like something like this would be very simple without .css (since I'm not the best at it).

My Questions are:

If I use .css, what style sheet should I insert the code into (Views, Theme, ??)?
Is there a way to get around using a .css to accomplish what I want to do?

Thank you in advance for your time.
WO

Addition info 10/22/15 - in response to argiepiano: I already use and love display suite and have never noticed the "Display Suite" option in Views. THANK YOU. I have gone through the first 5 videos but:  I still have trouble getting text/images to align correctly in Display Suite (css), do you mayhap know of any good videos or articles on that?

Thanks Again,
WO

I would suggest you use Display Suite. This module allows you to define a layout for the entry form and/or the display of any content type. If you want to use Views to create a list of nodes, you can use the layout you created to display each of the nodes in the View by selecting Unformatted list of Full posts in the Display format dropdown lists in the Views wizard.

There are several excellent video tutorials for Display Suite, but I'd recommend the ones its author created.


How activate Privatemsg Module to all users? I just enabled the Privatemsg Module in my Drupal 6. I would like to enable this module to all users, who join in the website. But the registered users cannot see the "Write new message and Messages" link.

Why the  Privatemsg is not active in users section ?

You should change permissions for the Privatemsg module for authenticated users or whatever role you want in the permissions page(admin/user/permissions)

See http://drupal.org/getting-started/6/admin/user/permissions


Theme settings not getting saved I created custom settings for my theme for storing email, fb url, twitter url
and g+ url. Everything is coming properly but the settings are not getting saved.
I have no idea whats wrong. All the code and screenshots are below.

.info file content

settings[z_email] = mail@zed.com
settings[z_facebook] = fb/url
settings[z_twitter] = twitter/url
settings[z_gplus] = gplus/url

theme-settings.php file content

function z_form_system_theme_settings_alter(&$form, $form_state) {
  $form['z_email'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Email'),
    '#default_value' => theme_get_setting('mail@zealind.com'),
    '#description'   => t("Global Email Id for ZealInd site."),
  );

  $form['z_facebook'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Facebook'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Facebook Url."),
  );

  $form['z_twitter'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Twitter'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Twitter Url."),
  );

  $form['z_gplus'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Google+'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Google+ Url."),
  );

}

The theme setting page:

You're not using theme_get_setting() quite right at the moment; the first argument should be the name of the setting, not a default value.

For example, your element defined as $form['z_email'] should look like this:

$form['z_email'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Email'),
  '#default_value' => theme_get_setting('z_email'),
  '#description'   => t("Global Email Id for ZealInd site."),
);


My form does not show any action on clicking the submit button I have create custom module with hook_block , inside the block i want form but the problem (
my from does not take any action of submit ). This is my code

function loan_calculator_block_info() {
  // This example comes from node.module.
  $blocks['loan_calculator'] = array(
    'info' => t('Loan Calculator'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}
function loan_calculator_block_view($delta = '') {
    switch ($delta) {
        case 'loan_calculator':
        $block['subject'] = t('Loan Calculator');
        $block['content'] = drupal_get_form('loanCalculator_form');
    return $block;
    break;
  }
}

function loanCalculator_form(){
  $month = range(1 , 12);
  $form['amount'] = array(
    '#title' => t('Amount'),
    '#required' => TRUE,
    '#type' => 'textfield'
  );
  $form['duration'] = array(
    '#title' => t('Duration (Months)'),
    '#required' => TRUE,
    '#type' => 'select',
    '#options' => $month
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('calculator_loan_form_submit')
  );
  return $form;
}

function loanCalculator_form_validate($form, &$form_state) {
  $amount = $form_state['values']['amount'];
  if ($amount == '') {
    form_set_error('amount', t('You must select Amount.'));
  }
  elseif (!is_numeric($amount)) {
    form_set_error('name', t('The Amount must be numeric.'));
  }
}
function calculator_loan_form_submit($form, &$form_state) {
  var_dump($form_state['values']);
  $mount = $form_state['values']['amount'];
  if(!is_numeric($form_state['values']['amount'])) {
    return '
'.t('Please Enter numaric value').'
';
  }
  return $mount;
}

How I can fix this problem?

Something like this should work:

/**
 * Implements hook_block_info
 */
function loan_calculator_block_info() {
  // This example comes from node.module.
  $blocks['loan_calculator'] = array(
    'info' => t('Loan Calculator'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

/**
 * Implements hook_block_view
 */
function loan_calculator_block_view($delta = '') {
    switch ($delta) {
      case 'loan_calculator':
        $block['subject'] = t('Loan Calculator');
        $block['content'] = drupal_get_form('loan_calculator_calculator_form');
    return $block;
    break;
  }
}

/**
 * Form builder
 */
function loan_calculator_calculator_form(){
  $month = range(1 , 12);
  $form['amount'] = array(
    '#title' => t('Amount'),
    '#required' => TRUE,
    '#type' => 'textfield',
    '#element_validate' => array('element_validate_number'),
  );
  $form['duration'] = array(
    '#title' => t('Duration (Months)'),
    '#required' => TRUE,
    '#type' => 'select',
    '#options' => $month
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * Form submit handler
 */
function loan_calculator_calculator_form_submit($form, &$form_state) {
  drupal_set_message('<pre>'.print_r($form_state['values'],1).'</pre>');
}

Note, the renamed functions are per Drupal convention, (avoiding hook_form namespace collision), including using default submit handler. Also, no need for validate handler if amount element is required and set to numeric element validator. Tidied up a bit, should be fine but needs testing.


Add Bootstrap into Zen sub-theme Right now, I am using Zen theme as basic theme for my website. I want to add Bootstrap into my theme because I don't want to use new theme and setup everything.
Does anyone know if I can only add these two lines of code to setting instead of downloading every single bootstrap file?

settings[bootstrap_source] = bootstrapcdn
settings[bootstrap_version] = 2.3.2

I found the above code in someone's theme setting, but I didn't find the meaning of them. So, I am not sure whether this can be worked.

Thank you very much.

Does anyone know if I can only add these two lines of code to setting instead of downloading every single bootstrap file?

No, you can't do that. That's a setting from, I would guess, the Bootstrap theme itself. It allows you to choose which version of the framework to use for that theme. The Zen theme would have no reason to add Bootstrap, so no reason to use those settings.

Continuing to use Zen as a theme/sub-theme, and replacing its framework with Bootstrap, doesn't sound like a great idea. You'll have problems/headaches upgrading, and plenty of Zen-isms to remove/re-implement to get it to play nicely with the new framework.

Given that all of that work, and more, has already been done for you, setting up a new theme based on Bootstrap is worth re-considering IMO.


Print Main Menu inside a block Very new to Drupal--trying to understand building a dynamic navigation menu for end users to handle. Is it possible to print the Main Menu inside a block I'm using for the header? e.g.

<nav id="main-menu" role="navigation" tabindex="-1">
<?php
      print theme('links__system_main_menu', array(
        'links' => $main_menu,
        'attributes' => array(
          'class' => array('links', 'inline', 'clearfix'),
        ),
        'heading' => array(
          'text' => t('Main menu'),
          'level' => 'h2',
          'class' => array('element-invisible'),
        ),
      )); ?>
</nav>

Pages render the <nav> tag, but nothing inside such as the content (basic pages) that Main Menu definitely contains so far as I can see in /admin/structure/menu/manage/main-menu.

I'm using my own sub-theme (derived from Zen, but most regions removed,) so I've been trying the code above (and variations) in a block added to the Header region. Is this not the Drupal convention?

In a custom zen sub-theme I currently use the following code:

$menu = menu_navigation_links('main-menu');
print theme('links__main-menu', array('links' => $menu, 'attributes' => array('class'=> 'menu')));

This is appliable to any manu – just change the name accordingly. And it's easiely printable wherever I need it (page.tpl.php). It prints a `ul´ like this:

Link 1

Link 2

Link 3


Use createFilter to build an advanced query using AND and OR with the search API I have a search index of about 15 fields (profile2 fields) build with the search API indexer (mysql) and I need to build an advanced query. All fields are fulltext. The query input form would have about 6 fields:

name, postal code, zip, city, keywords

The complete sql query (pseudo code), conditionally based on what the user entered in the form fields, would look like this

SELECT
  *
FROM
  {index}
WHERE
  (field_last_name = 'name' OR field_first_name = 'name')
AND
  field_postal_code = 'zip'
AND
  field_city = 'city'
AND
  (field_interests = 'keywords' OR field_hobbies = 'keywords' OR ...)
ORDER BY ...

Is this possible at all to build a filter like this?

I try to find a way to build an advanced search and I first tried Views using the filter criteria but I can not build an exposed form like I want. Also as a next step I need to integrate a proximity search on the postal code field. After some reading and hours of using google I thought the search API would give me a go to get a solution on that problem.

To completely understand my problem please refer to this question I asked yesterday: Views 3 Custom filter for Profile2 data

I would really appreciate some hints if I am on the right track or if I have to code a completely distinct module to build that kind of search engine.

Thanks to you all for your help!

This should be possible:

<?php
$or1 = $query->createFilter('OR');
$or1->condition('field_last_name', 'name');
$or1->condition('field_first_name', 'name');
$query->filter($or1);

$query->condition('field_postal_code', 'zip');
$query->condition('field_city', 'city');

$or2 = $query->createFilter('OR');
$or2->condition('field_interests', 'keywords');
// if field is fulltext, the default '=' operator is interpreted as 'contains'.
// to search over all fulltext fields: $query->keys('keywords')
$or2->condition('field_hobbies', 'keywords');
//...
$query->filter($or2);
$query->sort('field', 'ASC');
$query->execute();

But IMHO and unfortunately you won’t be able to further nest queries/filters like AND ((field1 = 1 AND field2 = 1) OR (field1 = 2 AND field2 = 2)). I’m going to open another thread for this problem.


When rendering paragraphs in a theme, is there a way to look at the last rendered paragraph while rendering the current one? I have about two dozen paragraph types. One of them inserts an h2, and generates a jump menu at the top of the page (I am generating that myself).

The pattern lab has the content that comes next (whatever the next Paragraph inserted may be) with a special CSS class on the container, because of the particular aforementioned type being used.

Is there a way in theme_preprocess_paragraph or theme_preprocess_field to 'look back' and add the CSS class if the current one is a certain paragraph type?

Yes, you can do something like this in preprocess:

    <?php
    // Get entity reference revision item that points to this paragraph.
    /** @var \Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem $item_reference */
    $item_reference = $paragraph->_referringItem;

    // Get entity reference revision field items list that holds all
    // paragraphs.
    /** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $items_list */
    $items_list = $item_reference->getParent();

    // Get next index position of current paragraph in entity ref. revision
    // field items list.
    $next_delta = $item_reference->getName() + 1;

    // Check if there is a paragraph on the next delta.
    if ($items_list->offsetExists($next_delta) && $items_list->get($next_delta)->entity) {

That special property is set in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView(). And because paragraphs themself are not render cached on their own and not used in multiple places means that you can actually rely on it. (It would also be set on a node, but due to render caching, you can not rely on it being there, at least not by default).


AWS RDS and Multiple Database Installation Does anyone have experience with setting up a Drupal Multi-Site with multiple Databases onto one RDS instance in AWS?

I was looking into this link below but I was not familiar with the exact formatting: https://www.drupal.org/node/18429

Here is my format:

$databases = array (
'default' =>  // main drupal db starts from here
array (
'default' =>
array (
  'database' => 'PubDB',
  'username' => 'PubUser',
  'password' => 'PASSWORD',
  'host' => 'pubtest.amazonaws.com',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
),
),'careers' =>  // additional database starts here
array (
'default' =>
array (
  'database' => 'careers', // additional database name
  'username' => 'PubUser', // additional database username
  'password' => 'PASSWORD', // additional database password
  'host' => 'pubtest.amazonaws.com',
  'port' => '3306',
  'driver' => 'sql', //the file is in sql format
  'prefix' => '',
)
),
);

And on my database.inc file I have:

function db_set_active($key = 'careers') {
return Database::setActiveConnection($key);
}
db_set_active();

Finally got it. :)

Here are the steps I took on a RDS under a VPC:

Created each Database individually on MySQL and then dumped each DB.

To log into your RDS MySQL:

mysql -h RDSEndPoint.rds.amazonaws.com -P 3306 -u MasterUser -p

To dump

mysql -u MasterUser -p -h RDSEndPoint.rds.amazonaws.com DB_Name_on_MySQL < /my/file/location/SQL_FILE.sql (You might need to change the .sql to .mysql)

Once you have your DB's set up and ready to go, change your /var/www/html/MySiteFolder/sites/default/settings.php file

To

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB_Name_on_MySQL',
      'username' => 'MasterUser',
      'password' => 'PASSWORD',
      'host' => 'RDSEndPoint.rds.amazonaws.com',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You might receive this error (https://www.drupal.org/node/2394349):

Command updatedb needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.       [error]

The drush command 'updatedb' could not be executed.                  [error]

A Drupal installation directory could not be found                   [error]

You can run the following two commands on where each of your sites index.php file is located:

drush dl rules
drush updatedb

You should be able to see your site now! If I'm missing something I would be glad to add it for future reference.


Trouble enabling view modes for content types I have a custom view mode and need to enable it for a node type.  I need to enable it through my module, and it seemed like hook_entity_info_alter() is the way to go, but it's not working.  Am I missing something?

My code:

function mymod_entity_info_alter(&$entity_info) {
    $entity_info['node']['view modes']['vm_mid_box'] = array(
        'custom settings' => TRUE,
        'label' => 'Mid Box'
    );
}

EDIT: I create the displays in Display Suite, and am using the export data dumped into DS hooks.

Late answer, but for anyone else looking, to get your view mode to display try either visiting the module page or disabling then re-enabling your module. Afterwards clear the cache.


Detect front page in Drupal 6 with javascript Using javascript in Drupal 6, is there a way to detect whether the present page is the front page? I have a custom Drupal 6 module that outputs different javascript codes based on whether the present page is front page or not. It adds a single javascript file to drupal, so I need to put the check in the javascript.

The site will be served through Varnish cache, so I don't want to add the check in PHP, though I know that would have been way easier with drupal_is_front_page().

Is there any Drupal-native way to do this? jQuery based suggestions will be highly appreciated.

Thanks.

Generally Drupal adds a "front" class to the body element of whatever page is acting as the front page. If your theme's page.tpl.php is printing the body classes (i.e <body class="<?php echo $classes; ?>"), which it most likely is (it should), then your javascript can check if the body element has the "front" class.

So, assuming jQuery (because Drupal includes it) then you'd do:

if ($('body').hasClass('front')) { // do stuff...}


How to use the Signup module Can anyone show me how to use the Signup Module? I don't see anything in Structure or Add Content. I'm sure I just missed the link somewhere but I just can't figure out where.

admin/config/people/signup is where the settings page is located.

admin/content/signup displays "all signup-enabled posts, and open or close signups on them"


How to use "replacement tokens" created for a Message type in Views? In my case a user with the role ("team member") flags a node created by normal user. I want to display "@team member_id flagged @node_id created by @user_id". Maybe later on I would like to add profile pics of both user/team member or the email or any information in the view about them.

Is this possible?

Here is an export of the Message type (created with the Message module):

{
  "name" : "utilisateur_finalise_intervention",
  "description" : "Utilisateur finalise intervention",
  "argument_keys" : [ "@utilisateur", "@equipier" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "fr",
  "arguments" : null,
  "message_text" : { "fr" : [
      {
        "value" : "@utilisateur a finalis\u00e9 une intervention avec @equipier",
        "format" : "filtered_html"
      }
    ]
  },
  "rdf_mapping" : []
}

And the rule I created looks like so:

{ "rules_link_set_finaliser_une_intervention" : {
    "LABEL" : "Rules link: Finaliser une intervention rules set",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "user" : { "label" : "user", "type" : "user" },
      "node_id" : { "label" : "node_id", "type" : "node" }
    },
    "RULES" : [
      { "RULE" : {
          "PROVIDE" : { "entity_created" : { "log_fin_intervention" : "log_fin_intervention" } },
          "DO" : [
            { "flag_unflagnode" : {
                "flag" : "accepter_invitation",
                "node" : [ "node-id" ],
                "flagging_user" : [ "user" ],
                "permission_check" : "1"
              }
            },
            { "flag_flagnode" : {
                "flag" : "fin_intervention",
                "node" : [ "node-id" ],
                "flagging_user" : [ "user" ],
                "permission_check" : "1"
              }
            },
            { "entity_create" : {
                "USING" : {
                  "type" : "message",
                  "param_type" : "utilisateur_finalise_intervention",
                  "param_user" : [ "node-id:author" ]
                },
                "PROVIDE" : { "entity_created" : { "log_fin_intervention" : "log_fin_intervention" } }
              }
            },
            { "data_set" : {
                "data" : [ "log-fin-intervention:arguments:utilisateur" ],
                "value" : [ "node-id:author:uid" ]
              }
            },
            { "data_set" : {
                "data" : [ "log-fin-intervention:arguments:equipier" ],
                "value" : [ "user:uid" ]
              }
            },
            { "mail" : {
                "to" : [ "user:mail" ],
                "subject" : "Votre collaboration sur [node-id:title] est termin\u00e9e",
                "message" : "Votre collaboration avec [node-id:author:field-prenom] [node-id:author:field-nom] sur le projet  [node-id:title] est maintenant termin\u00e9e",
                "from" : [ "" ],
                "language" : [ "" ]
              }
            },
            { "drupal_message" : { "message" : "Votre collaboration avec  [user:field-prenom] [user:field-nom]  est maintenant termin\u00e9e" } },
            { "redirect" : { "url" : [ "node-id:url" ] } }
          ],
          "LABEL" : "Finaliser intervention"
        }
      }
    ]
  }
}

And also the view I created:

I also have an error displayed above the view

Notice : Undefined variable: table dans ViewsUiBaseViewsWizard->default_display_filters_user()

"To add profile pics of both user/team member or the email or any information in the view ..." (as in your question), you cannot use the replacement tokens (= @utilisateur and @equipier in your case). These tokens can only be used as part of your Message Text (as you are already doing), as indicated also via  ... which the message text makes use of ... on the Message Types form where you enter those tokens.

However, Messages are fieldable entities. So what you can do is like detailed in the steps below ...

Step 1:

Define a field in your Message Type corresponding to each of those tokens. As an example, add fields similar to these (for equipier and for utilisateur), with machine names like so:

field_equipier_user_name.
field_equipier_user_id.
field_utilisateur_user_name.
field_utilisateur_user_id.

Your replacement tokens appear to be uid values, note that I'm using a similar uid, but also the name as an alternative (it could as well be an eMail field, etc).

Step 2:

Extend your rule to also perform a Rules Action like "Set a data value" (for each of your fields you added in the previous step). To continue the example, add these actions in your existing rule:

 ,
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-id" ],
    "value" : [ "user:uid" ]
  },
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-id" ],
    "value" : [ "user:uid" ]
  }

Step 3:

Extend your view to also add those extra Message Type fields to your view (as extra fields of your view. Be aware: if later on you add more fields to your Message Type (and rule and view afterwards also), you'll only have actual values in the corresponding columns of the Views results for message that were created after you added those extra fields.

BTW, the Views error near the end of your question seems like a different question (not addressed in this answer ...).

PS: this answer applies to D7 ...


Which are the steps to make Locale language switcher block appear at selected area? After this question on which module to use to handle interface translation I was expecting the setup of Locale to be pretty straightforward. I guess it is not.

Well, my backend and navigation menus got translated right away but the main objective (as you can see by reading the other question) was to allow any user to change language as needed.

So the goal is to setup the language switcher block in order that it is available to everyone.
Steps performed:

Enable module Locale
Setup language switcher block to appear at some area
Configured block to appear to all roles on every page
Added a new language and imported the .po file
Checked all locale permissions (except anonymous user -> translation)

Am I missing something?

You need to set the language negotiation.


entity_autocomplete field thats added by ajax is not working I have a field im adding to a node-edit form by ajax. the field is a simple taxonomy auto-complete field.

when I add it directly in my form_alter it works, but when it's added by ajax, The autocomplete is not there - the field looks and behaves as a simple text field.

I have edited my question and added my code.

 use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
        $element['display_id']['#ajax'] = [
          'callback' => 'getAjaxArgumentsFields',
          'wrapper' => $id . 'arguments',
          'method' => 'replace',
          'event' => 'change',
        ];
        $display_id = $element['display_id']['#default_value'];
        $element['options']['arguments'] = get_argument_fields($display_id); //Works, with entity_autocomplete working

}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
      $display_id = $form_state->getTriggeringElement()['#value'];
      $fields = get_argument_fields($display_id);
      NestedArray::setValue($form, $array_parents, $fields);
      return  NestedArray::getValue($form, $array_parents); //Returns the exact same fields, but no autocomplete functionality- they appeare and behave like a regular text field
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
              '#type' => 'entity_autocomplete',
              '#title' => $argument_definition['title'],//Taxonomy term
              '#target_type' => $argument_definition['type'],//taxonomy_term
              '#default_value' => '',
              '#selection_settings' = [
                     'target_bundles' => $argument_definition['bundles'],//voc_name
               ],
      ];
     $args_field['#prefix'] = '
';
     $args_field['#suffix'] = '
';
     return $args_field;
}

What do you guys think could be the reason?
Thank you!

Ok, So thanks to 4k4 I now understand what i was doing wrong, and for the favour of everyone that will meet this issue again:

The form_alter is invoked as well when ajax callback is invoked.
by the time the execution got to my ajax callback (getAjaxArgumentsFields) the form_alter has already altered my form, so all i had to do was return the fields without changing them.
Here is the code that worked for me:

use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
    $element['display_id']['#ajax'] = [
      'callback' => 'getAjaxArgumentsFields',
      'wrapper' => $id . 'arguments',
      'method' => 'replace',
      'event' => 'change',
    ];
    $display_id = $element['display_id']['#default_value'];
    $element['options']['arguments'] = get_argument_fields($display_id); //here I change my field, both on load of the page and also before ajax
}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
    $array_parents =  clac the path to the wanted field
    return  NestedArray::getValue($form, $array_parents);
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
          '#type' => 'entity_autocomplete',
          '#title' => $argument_definition['title'],//Taxonomy term
          '#target_type' => $argument_definition['type'],//taxonomy_term
          '#default_value' => '',
          '#selection_settings' = [
                 'target_bundles' =>
           $argument_definition['bundles'],//voc_name
           ],
           ];
      $args_field['#prefix'] = '
';
      $args_field['#suffix'] = '
';
      return $args_field;
}


How do I restrict a content type to a subset of vocabulary? I have a hierarchical general taxonomy vocabulary called tags. Some of the terms are only relevant to particular content types; e.g., the "Apples" content type might have a sub-tree in the vocabulary with Cox, Granny Smith, and the "Oranges" content type might have Seville in its vocabulary sub-tree.
When editing an Apple node, I don't want users to be able to select Seville as this doesn't make sense.

I have put the terms into one vocabulary because other content types (e.g. blog articles) might want to tag against any of these.

I think http://drupal.org/project/term_reference_tree together with views will handle this for you. You will need to set up different views for each content type and then use term_reference_tree together with that view on each content type. As quoted from the module:

  If you want to filter by a view, make sure the view includes the
  taxonomy term ID, and that the items per page is set to unlimited, as
  the widget will only display the items from the first page of results.

Summarised module usage for reference:

Create a view to filter for the terms you want.

Choose Taxonomy for the content, and work on the Master display (not Page or Block)
Add the Name field
Add the Taxonomy term: Term ID field BUT check the "exclude from display" option.
Turn off the pager
For this specific case, add relationship: Parent term; create OR group in filter: (vocab=tags && (parent.tid={Apples's tid} || tid={Apples's tid}). This gives the Apples term itself and all its child terms.
Possibly needed if view does not work for non-admin users: change the  Disable SQL Rewriting option under Query settings, but beware that means there is zero access checks on your view.

Apply the view to the Term Reference field.

Go to the content type fields page.
On the Term Reference field in question, click the Edit link at the end of the row. You can now see the "Filter by view" option.  (If not, your view is wrong). Choose your view and save these options.
Now click the link to change the widget: choose Term Reference Tree.