table styles not applied by bootstrap sub-theme I'm writing a custom sub-theme of bootstrap with Drupal 9, and have noticed that table elements in my forums do not render properly:

This is despite me selecting "Bordered Table" in the configuration settings:

The next thing I tried was using Chrome's "inspect" feature to manually add class = "table" to the table element, which caused it render much more nicely;

I don't see any options to apply that class to table elements, either in the forum settings nor in the bootstrap settings.
I have a few questions to help me (and hopefully others) understand what's happening here;

Is adding the class = "table" to table elements the right approach?
Assuming it is, what's the right way to apply this class to table elements? (I've not averse to writing php code, I've just never written a theme before so I don't know where to start)
What's the point of those bootstrap table settings - they don't seem to do anything?

EDIT:
As per leymannx's suggestion, I've enabled twig debugging and looked at the resulting html:

      Forum
      Topics
      Posts
      Last post

            No new posts

General discussion

          0

        0

  n/a

leymannx suggested twig debugging, which was super helpful. The solution I came up with was to copy the core/modules/forum/templates/forum-list.html.twig file into mytheme/templates and then modify it to take the table theming elements from the system/table.html.twig file in bootstrap.
Here's the end result:
{#
/**
 * @file
 * Default theme implementation to display a list of forums and containers.
 *
 * Available variables:
 * - forums: A collection of forums and containers to display. It is keyed to
 *   the numeric IDs of all child forums and containers. Each forum in forums
 *   contains:
 *   - is_container: A flag indicating if the forum can contain other
 *     forums. Otherwise, the forum can only contain topics.
 *   - depth: How deep the forum is in the current hierarchy.
 *   - zebra: 'even' or 'odd', used for row class.
 *   - icon_class: 'default' or 'new', used for forum icon class.
 *   - icon_title: Text alternative for the forum icon.
 *   - name: The name of the forum.
 *   - link: The URL to link to this forum.
 *   - description: The description field for the forum, containing:
 *     - value: The descriptive text for the forum.
 *   - new_topics: A flag indicating if the forum contains unread posts.
 *   - new_url: A URL to the forum's unread posts.
 *   - new_text: Text for the above URL, which tells how many new posts.
 *   - old_topics: A count of posts that have already been read.
 *   - num_posts: The total number of posts in the forum.
 *   - last_reply: Text representing the last time a forum was posted or
 *     commented in.
 * - forum_id: Forum ID for the current forum. Parent to all items within the
 *   forums array.
 *
 * @see template_preprocess_forum_list()
 *
 * @ingroup themeable
 */
#}
{% if responsive %}

{% endif %}
{%
  set classes = [
    'table',
    bordered ? 'table-bordered',
    condensed ? 'table-condensed',
    hover ? 'table-hover',
    striped ? 'table-striped',
    sticky ? 'sticky-enabled',
  ]
%}

      {{ 'Forum'|t }}
      {{ 'Topics'|t }}
      {{ 'Posts'|t }}
      {{ 'Last post'|t }}

  {% for child_id, forum in forums %}

        {#
          Enclose the contents of this cell with X divs, where X is the
          depth this forum resides at. This will allow us to use CSS
          left-margin for indenting.
        #}
        {% if forum.depth > 0 %}{% for i in 1..forum.depth %}
{% endfor %}{% endif %}

            {{ forum.icon_title }}

{{ forum.label }}

          {% if forum.description.value %}

{{ forum.description.value }}

          {% endif %}
        {% if forum.depth > 0 %}{% for i in 1..forum.depth %}
{% endfor %}{% endif %}

      {% if forum.is_container == false %}

          {{ forum.num_topics }}
          {% if forum.new_topics == true %}

            {{ forum.new_text }}
          {% endif %}

        {{ forum.num_posts }}
        {{ forum.last_reply }}
      {% endif %}

  {% endfor %}

{% if responsive %}

{% endif %}

The table now seems to render sensibly;


Best approach to wrap rendered file field in a link? I have a file field from the File Entity   module (2.x-alpha2) attached to a content type. I'm trying to customize the output of this field so that it links to the main node (this is for a teaser display). I'm overriding the node template for the teaser display, so I have access to the renderable field array for the field as well as the node path.

I'm trying to find the best approach for wrapping the image in a link. I can easily create the link tag using the l() function. However, I can't just wrap that around the rendered file field because it renders with a lot of extra markup aside from just the image tag.

What is the best approach to handle this? Programmatically altering the theme functions that render the actual image tag? It's not clear to me if I can do that quite yet.

If it helps at all, I'm also using the Media module (2.x-alpha2).

I would create a custom field formatter for rendering the cck field itself. Look for hook_field_formatter_info, hook_field_formatter_view and implement your own custom module

There is also this module https://drupal.org/project/custom_formatters you might want to check out.


I can't import images I'm using the Feeds and Feeds XML XPath Parser modules on Drupal 7.
While there is no problem importing all other fields (Title, body, etc.), it does not populate the image field in my nodes.

Feeds debug mode shows all paths to be relative, so I'm using Feeds Tamper to rewrite the relative paths to absolute paths (all on the same domain). Still, no images are being saved.

There are no errors displayed on the import page, nor in Drupal logs.

UPDATE: After some more altering the image paths via Feeds Tamper, now the following error is shown in the logs:
    Invalid enclosure ""

Where should I start debugging this?

Thanks!

I had a similar issue while using Feeds, Feeds XLS and Feeds Tamper. I solved it by copying the images in the path mentioned before importing using Feeds.

I am not sure but I think you should first run a script that copies the images onto the path mentioned in the Image field and then import nodes using Feeds.

For example, if your path to images is 'sites/default/files/myimages', you should first copy the images to 'myimages' folder and then run Feeds because Feeds/Feeds Tamper simply populate the file path AFAIK. These modules do not actually save the images.

Let me know if this helps.

Regards,

Supriya Rajgopal


How to do recurring subscriptions with credit card and Drupal 7 I need to implement recurring payments properly for my site. The payment model I have in mind is that as in use by linode: you sign up, pay for a linode and it will be billed forever recurring to your credit card. If you choose to make that linode larger, or order another one, you'll still be billed only once at the first day of the month, except now with the new amount.

Is there a decent module to do this under Drupal 7? I'm looking at drupal commerce and the commerce_moneybookers module (since i already have a moneybookers merchant account) but moneybookers only provides recurring payments if you sign up for an account with them. I'm not prepared to make my customers do that.

ideas?

Been doing a bunch of research, and it seems there are two main contenders for my scenario: http://www.fastspring.com and http://www.moneyscripts.net/drupal-membership-suite

I like the second one because it is pure drupal. But I like fastspring because it's very easy to use and pricing seems to be moderate. They also offer a great range of payment methods and they are PCI-DSS certified.

I'll do some more research and let you know my final choice


best WYSIWYG editor from the UX side? There are a bunch of WYSIWYG edirtors available. I've tried CKEditor so far (and tinyMCE with wordpress). CKEditor is a very fancy one but fairly complex and weights 6Mb including source files.

What is in your experience the most buggless and stable?

It needs to have a support for IMCE bridge module to be able to get images from disk.

I personally use tinyMCE on my sites, it's not heavy, and you can use the IMCEbridge.

This module will install the WYSIWYG API, then follow these instructions for adding TinyMCE or any other you want.

The IMCE Bridge module can be found here and is compatible with CKEditor, FCKeditor and TinyMCE.


Drupal 7 theme('pager') -> PDOException: SQLSTATE[42S02]: Base table or view not found first time i have asked for help on a forum for a very long time. Normally find what i need by viewing other posts... Well i'm really confused so need help.

I am trying to use theme('pager') in Drupal 7 to have pagination for my table results i get from a db_select query.

The below query produces an error when i include the line:

$output .= theme('pager');

If i leave this line out i get the expected limited 5 results from my table.

My code:

// Set external databse
db_set_active('nondrupal');

// build query to get desired results
$query = db_select('diary', 'n')
->fields('n', array('photo_id', 'photo'))
->orderBy('photo_id', 'DESC');

//Create a new object from extend. The reason for this is that extend() creates a
new object which wraps the current object (Decorator pattern).
$query = $query->extend('PagerDefault')->limit(5);

// Execute query and add to array
$result = $query->execute();

// empty output var
$output = NULL;

// Loop through results and output each row for chosen columns
foreach($result as $row) {
$output .= $row->photo_id.': '.$row->photo.'<br />';
}

// Show pagination in output
$output .= theme('pager');

// echo output to screen
echo $output;

// Set db connection back to default (drupal)
db_set_active();

The page renders fine without the theme('pager') line.

With it i get an error:

Additional uncaught exception thrown while handling exception.
Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table
&#039;dbMYDATABASENAME.semaphore&#039; doesn&#039;t exist: SELECT expire,
value FROM {semaphore} WHERE name = :name; Array ( [:name] =&gt;
theme_registry:runtime:garland:cache ) in lock_may_be_available() (line 167
of /homepages/28/d228752694/htdocs/drupal7/includes/lock.inc).

Base table or view not found seems to be the key but i cannot see why including the    theme function causes this error. I have a basic Drupal 7 install.

Your help is appreciated!

Madmilner

The error is down to the:

// Show pagination in output
$output .= theme('pager');
// echo output to screen
echo $output;

being above db_set_active();

Not sure why this is but it fixes the problem.

Thanks


What are efficient solutions to prevent a huge amount of panes in a Panel? Using Panels for some years I still have one question that I struggle with.

I have set up a Panel with a special layout, with a filter on a specific bundle type.

I have more than 10 views content panes that I want to show in that panel, but each one on its own entity.

So the obvious solution is to add Pane Visibility Rules to each of the panes, which filter by URL of the entity.

I think this is neither efficient nor userfriendly. It's hard to manage for more than 10 panes and have a clear insight about all the visibility rules of each pane.

I thought about using ViewField module for the entities showing a specific view, and still allow them to use the Panel. As far as I can see, that does not allow for the use of the Panel pane context tokens.

Suggestions are very welcome.

Panels have "varients" with selection rules.  You can set up which variant is triggered by which value in the url variable that you named in the path setup.  This way, you can have your pane layouts not get so cluttered with options that are only visible a fraction of the time, but still have the same capability.  Either way, the check for display is a growth order of O(1) so not that much of an efficiency concern.  The views would be a better place to increase efficiency, set a limit and a link to the full list in a footer.


Want to use exposed filters to pass arguments to a view The title explains a lot.

I have a view which shows everything of the content type and has exposed filters.(<-main view)

Now I made another view where I used the exposed form style because I want it to act as a "search block". It shares the same filters as the main view and I want this to pass its arguments to the main one.

For example: A user is on the main page, fills in the filters, submits-> Redirects to the main view where the filters the user filled in are now being used.

I looked for a lot of solutions but couldnt find any.
Thanks in advance!

In your view on right hand side there is "Advance" toggle under that "Expose form" is there click on Exposed form in block "No" to "Yes". Now you can find that expose filter in system block. You can place that block anywhere you want you will redirect to that main view.


Create And in contextual Filter I need to create AND in Contextual Filter, for instance:
I Want to Get All English Node AND Italian Node, with particular Taxonomy.
But I Can Have En and It, but even only en or only it, or even it, en ,de etc

Can I do it with Contextual Filters?

I'm not sure why you need an AND condition in the first place for this?

Should be enough to have a contextual filter for the taxonomy terms and a normal filter for the node language?

Note that translations are stored in a single node. I'm not sure what your expectations are about what exactly should be displayed. There are settings about which language should be used for display. You might have a problem with duplicates, though.


How to override a function inside of a Trait? My goal is to override the function isApprovalRequired() in a Trait for the module Social Auth (social_auth). The file:

modules/contrib/social_auth/src/SettingsTrait.php

has a function (along with variables and other functions):

namespace Drupal\social_auth;

use Drupal\Core\Url;
use Drupal\user\UserInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
* Helper methods for Social Auth and Drupal settings.
*/
trait SettingsTrait {
  ...
  protected $configFactory;
  ...
  protected function isApprovalRequired() {

that I would like to overwrite. How do I overwrite JUST that one function in my own module? I've done similar things with classes before, but not sure what to do with a Trait.

For those that may run across this. I could not find a way to override (don't think it's possible). I did eventually settle on modifying the line of the file myself, running a git diff, and adding my own patch to my composer.json. In this way, I can run updates and use composer correctly. It's not a patch others will need, but how it was solved might help others.


correct url() request I need to make a redirect after a customer added something to his cart so I write this:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  array_push($form['#submit'], '_MODULE_redirect_to_products');
}

function  _MODULE_redirect_to_products(&$form, &$form_state){
  global $language ;

  $form_state['redirect'] = url('prodotti', array('language' => $language));
}

but this code redirect me to

/dev/azzurra/?q=it//dev/azzurra/%3Fq%3Dit/prodotti

but I need to redirect to

/dev/azzurra/?q=it/prodotti

according to the language obviously.

UPDATE:
I'm try to use

 $form_state['redirect']

but if I display this field before modify it I can see this

Array
(
    [0] => prodotti
    [1] => Array
        (
            [language] => stdClass Object
                (
                    [language] => it
                    [name] => Italian
                    [native] => Italiano
                    [direction] => 0
                    [enabled] => 1
                    [plurals] => 2
                    [formula] => ($n!=1)
                    [domain] =>
                    [prefix] => it
                    [weight] => 0
                    [javascript] => a97-0F_JBbaSYaN4XQBbFbhCLCysRpSabTcDmQjB73E
                    [provider] => locale-url
                )

        )

    [2] => 302
)

but the form redirect me to 'it/testate/name' because the form 'add product' is displayed in a view so I think that the views module override the $form_state['redirect'] after me so the default redirect [and mine one..].

I think I can't use this kind of redirect..
How can I achieve this redirect correctly?

$form_state['redirect'] does not take full URL. It takes the same set of parameters url() does. In your case it should probably look like this:

$form_state['redirect'] = array(
  // $path
  'prodotti',
  // $options
  array('language' => $language),
  // $http_response_code
  302,
);


Create a draggable table and save weights I'm struggling a bit with creating a draggable table.

I want to have a table that lists node labels, where it's possible to rearrange the order of the nodes. The new weights shall be available when I submit the form.

This is my code so far:

$rows = [];
foreach ($nodes as $node) {
  $weight = $node->weight;

  $row = [
    'weight' => $weight,
    $node->label(),
  ];

  $rows[] = [
    'data' => $row,
    'class' => ['draggable'],
    '#weight' => $weight,
  ];

  $form['table'][$node->id()]['weight'] = [
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#title_display' => 'invisible',
    '#default_value' => $weight,
    '#attributes' => [
      'class' => [
        'draggable-weight'
      ]
    ],
  ];
}

$form['table'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Weight'),
    $this->t('Title'),
  ],
  '#rows' => $rows,
  '#attributes' => [
    'id' => 'my-module-table'
  ],
  '#tabledrag' => [[
    'action' => 'order',
    'relationship' => 'sibling',
    'group' => 'draggable-weight',
  ]],
];

When I kint($form_state->getValues()) in my submit handler table is equals to ''.

I feel like I'm missing something simple, but the lack of documentation for this makes it hard to find out.

With the help from @Leigh I found the problem. I was setting some keys on $form['table'][$node->id()] and then overriding $form['table'][$node->id()] at the bottom.

I have moved a bit around in the code and now it works perfectly.

$form['table'] = [
  '#type' => 'table',
  '#header' => [
    '',
    $this->t('Weight'),
    $this->t('Title'),
  ],
  '#attributes' => [
    'id' => 'my-module-table'
  ],
  '#tabledrag' => [[
    'action' => 'order',
    'relationship' => 'sibling',
    'group' => 'draggable-weight',
  ]],
];

foreach ($nodes as $node) {
  $weight = $node->weight;

  $form['table'][$node->id()] = [
    'data' => [],
  ];
  $form['table'][$node->id()]['#attributes']['class'] = ['draggable'];
  $form['table'][$node->id()]['weight'] = [
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#title_display' => 'invisible',
    '#default_value' => $weight,
    '#attributes' => [
      'class' => [
        'draggable-weight'
      ]
    ],
  ];
  $form['table'][$node->id()]['label'] = [
    '#markup' => $node->label(),
  ];
}


Why am I getting call to undefined function after splitting module functions to two files? Now my module has two main files:

menu_perm.module
menu_perm.admin.inc

I added second file to .info:

  files[] = menu_perm.admin.inc

I cleared the cache.

In my test class (PHPUnit) file I am bootrapping Drupal by:

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

and I call form submit function manually inside test function, ends with below error:

  Call to undefined function menu_perm_user_form_submit()

Function is in menu_perm.admin.inc.

Before this everything was ok.

What am I doing wrong here?

files[] only works for class/interface autoloading, it won't include arbitrary PHP files. The docs say

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file

You can get around it by adding a line like this to the top of your .module file:

require_once DRUPAL_ROOT . '/sites/all/modules/my_module/my_module.admin.inc';


ajax form element sometimes triggers submit I have found some strange behaviour of form ajax elements.

I have added #ajax to my form elements:

['#ajax'] = array(
  'callback' => 'mymodule_ajax_callback',
  'event' => 'change',
  'progress' => array('type' => 'none'),
);

and due to some other issues, i had to add ajax to my submit:

$form['actions']['submit']['#ajax'] = array(
  'callback' => 'mymodule_node_form_submit',
);

The issue is, when the form element ajax is triggered for "checkboxes" and "select" form field type at the same time, then submit callback is triggered but i never clicked submit.

Does anybody have any idea?

There is a quirk in the AJAX form api which causes the last button on the form to be submitted under certain circumstances.  Without seeing all of your code, it would be difficult to isolate the problem.


How to keep/access copy of original Feed file when using HTTP Fetcher? I've created Feeds importer to parse remote XML feed using HTTP Fetcher fetcher and I've created content type for that importer and Attached to it in Settings.

So my feed and import works fine after I've created importer node based on remote Feed URL.

However I would like to keep original remote XML feed file (fetched from the provided URL) similar as this happens for File upload fetcher to have a record/copy of it.

Is it possible? How?

I have a simple solution for you but in this time I have not enough time to test it by myself.

First find your importer form_id, then in your custom module add custom submit handler then get URL of uploaded file then save it in where you want with system_retrieve_file(), e.g.:

function yourmodule_form_alter(&form, &$form_state, $form_id){
  if ($form_id == "importer_form_id") {
    $form['actions']['submit']['#submit'][] = 'yourcustom_form_submit_handler';
  }
}

function yourcustom_form_submit_handler($form, $form_state){
  // dpm($form_state['values']);
  // find file url and put it in $url
  // then try to fetch it with system_retrieve_file
  system_retrieve_file($url);
}


How to update cart after deleting line items? I have an Application (app) node that when it gets created (hook_node_insert) I add line items (based on info in the app) to my cart. This works great.

Step 2 now is that when I add a new app, I would like to empty the cart (or remove the line items) before adding the new line item (so there is effectively only ever 1 item in the cart).

If I try to do $item->delete() or $cart->delete() before I add the new line item (in my node insert hook) then I get this error:

  Drupal\Core\Entity\EntityStorageException: A cart order for type
  default, store 1 and account 1 already exists. in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 847 of
  core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php).

If I delete the line items after I add the new line item; then the cart almost looks correct. It shows only my new line item and the subtotal is the amount of my new line item; but the Total shown is the combined Total of the new line item added to the old line items (which have been successfully deleted).

My guess is there is something I need to do to "refresh" the cart after adding and then deleting line items?

instead of using $item->delete() this works:

  $cart_manager = \Drupal::service('commerce_cart.cart_manager');
  foreach($items as $item) {
    //$item->delete();
    $cart_manager->removeOrderItem($cart, $item, TRUE);
  }

the 3rd parameter is 'save cart' and setting it to TRUE updates the cart Total.


Custom PHP code in Rules differs from Devel's one I'm facing an issue which is quite boring since the result displayed into Devel's PHP executer differs from the results of the Custom PHP code. What I want to do is sending private messages (thanks to privatemsg module) to certain users that I can't select with privatemsg Rules integration.

To send a new private_msg, we have to use the function "privatemsg_new_thread($recipients, $subject, $body)".

So I have to write a custom PHP code which is (I made it very simple) ; this one works in Devel but not in Rules.

$recipients = array(user_load(1));
$subject = 'hello';
$body = 'ok';
privatemsg_new_thread($recipients, $subject, $body);

When i write this ; it works with both modules

privatemsg_new_thread(array(user_load(1)), 'hello', 'ok');

Is there a problem with loading variables or sth ?
And i don't have any error log...

Any help would be highly appreciated !

Thanks in advance

I have finally suceeded by deleting and creating a new rule with the same PHP code ; I guess there must be a bug in there !


Cron has been running for more than an hour and is most likely stuck, problem is persisting I am getting this error each time I run the cron. When I saw the status report I found last time cron was run was about 8 weeks ago. It is same for all the 3 websties that I host with the same server, shored hosting. when I tried to run cron manually, it ended with a message cron failed. Somewhere I read it possible reason could be /tmp folder, so I created a tmp folder in installation directory for all the three websites. It did work for one of the websites, I am able to run cron manually in that website. But for other two websites it was the same error. A discussion in drupal.org told it could be problem with cron_semaphore variable. I tried deleting cron_semaphore variable using phpmyadmin and cleared the cache, but still it is same problem. Sometimes when I try it manually , it gives error message that MYSQL has gone away from query while inserting data into watchdog.  Is it because of the MySQL or file permissions problem ? Can it be cured if I update core to latest version? Or should I contact the hosting provider, is there is a problem with them?

There are too many factors that can stop the cron from being executed.

To see where exactly it breaks, open includes/module.inc and at the line 496 (function module_invoke_all()) add this:

foreach (module_implements($hook) as $module) {
  $function = $module .'_'. $hook;

  // This is the line you should add:
  if ($hook == 'cron') watchdog('cron debug', "Cron is processing module: $module");

Then run the cron from admin. The last module to be called is the one which breaks. Look further into the implementation of hook_cron() of that module and debug further.

This is inspired by this comment.

See this discussion.


Only allow specific roles to upload specific extension files How do I restrict users with specific roles to upload files with specific extensions on node edit pages. On my site I have two specific roles editor and animator.
Conditions are:

Editors can only upload .docx .doc .pdf files while Animators can upload .mp4 .mp3 .jpg files.

I added a validate function with hook_form_alter() and the validate does work but the user has to save the entire form before validation spits out an error about the wrong file extension. I want to get the file extension as soon as the user has finished uploading their file and display the error message before submitting the form but after uploading the file.

I have a quick solution for this using hook_form_alter.

So in your hook_form_alter you can check the user role and alter the validators key for that field. In my case the field was called field_material

global $user;
$valid_role = 'animator';

if(in_array($valid, $user->roles)) {
    //Change the extension in the validators key of that upload field
    $form['field_material']['und'][0]['#upload_validators']['file_validate_extensions'][0]  = 'mp4 mp3';
}

I am sure there are better solutions but this is quickest one so far for me to get going.


Multi-site setup outside public_html and add on domains So I have a Drupal site http://experiment-resources.com running on HostGator dedicated server. It's document root is the default public_html directory.

Now I need to setup a multisite environment outside public_html because I dont want to mess with existing website's functionality.

I already added http://arkivtjenesten.no as an Add-On domain and pointed it to /home/myaccount/arkivtjenesten as its document root. All works fine.

Now I need to add another domain , http://assistertselvhjelp.no . I added this as an add on domain and pointed its doc root to /home/myaccount/arkivtjenesten , same as the previous site. I also added its own settings.php so that it will have its own database. The problem now is if I type in http://assistertselvhjelp.no in the browser it only shows the Apache page.

Please help!

Thanks!

By the definition of multi-site: you use one Drupal installation (core) to host several sites. But according to your problem, you want a separate instance of Drupal installation and hence it's considered a "multi-site".

You need edit your virtual host file and point http://assitertselvh.no to the specific folder you're hosting to:

Please use the following guide to edit your virtual host.

http://drupal.org/node/111238


triggering email from custom module I have a module that uses hook_menu to create several pages that are populated with SQL query results.

I have been trying to configure drupal_mail and hook_mail to send these results via mail when the pages are visited, but so far I haven't succeeded.

I used the info I found here and indeed, the module works: whenever I run cron the sample mail is sent, but I haven't found the way to customize it in my module so when I load my custom pages the results are sent via mail.

Also, if my data is the result of:

function mystats_all() {

$header = array('Nombre', 'Status', 'Rol 5 = Alumno', 'Email' );

$query = "
SELECT name, status, rid, mail
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@example.com'
AND users_roles.rid =5
AND users.status =1
";

$result = db_query($query, $some_value);
    while ($row = db_fetch_object($result))
    {
        $rows[] = array(
                    array('data' => $row->name, 'align' =>'left'),
                    array('data' => $row->status, 'align' => 'left'),
                    array('data' => $row->rid, 'align' => 'center'),
                    array('data' => $row->mail, 'align' => 'left'),

        );
    }

    $table_attributes = array('id' => 'my_id_for_table', 'align' => 'center');
    $output .= theme('table', $header, $rows, $table_attributes);

    return $output;

how can I correctly send my table via mail? I don't know (and I would like to have the drupal_mail function working to make some tests) if I should use $query or $result.

Thanx in advance.

Any ideas or help, please?

You need to implement hook_mail() in your custom module and then call drupal_mail() in your page callback function to get the result you want. You should save your table html in the $params array that gets delivered to hook_mail() and then set it as the $message['body'] value there (with additional html/data if needed). The linked tutorial and API pages should give you enough information and examples to work out the rest of the details.


Term Reference field as checkboxes, not auto-complete? I have a brand new Drupal 8 installation (my first D8 site). I've created a new content type with a Term Reference field.

When adding content, it appears that the only way to select a term is via type ahead, auto-complete. Instead, I need a simple list of terms with checkboxes.

I can't recall struggling with this in D7 before. Is there a module I should install... or setting that I should configure?

To change the tag selection to check boxes configure the widget in the tab Manage form display:


drush migrate-status command not found I've installed both version of drush using composer, and trying to list migration within my newer drup8 installation, in order to migrate an older drupal 7 website .. then I feel really stucked because I can't follow the next commands to execute ..

composer global require drush/drush:dev-master --> migrate-status not found
composer global require drush/drush:7.* --> won't work with drupal8

Any ideas or enlightment would be greatly appreciated.

Try drush status and drush help to see if Drush is working with your Drupal 8 site.  Presumably, drush help will confirm that the migrate-status command is not available.  Try enabling the migrate module on your Drupal 8 site.


How do I add a minipanel to a panel page? In D7 I've created a new minipanel and would like to add it to a panel page.

However, when I go to add it I cannot find it. It's not under the category I've set it in and it's not under the Mini Panels category. I've tried clearing cache, rebuilding the registry and have ensured the minipanel has a unique machine name.

How can I add it?

I found the problem: It was because the Mini Panel contained a Block that was also contained on my Panel Page. Once I removed the block on the Panel Page I was able to add it.

I wish there was a way I could have the Block in both, but I guess not.


Field type that is an integer, but accept some strings that means no value is provided? I have a field named "Price" that should allow anything from 0 - no maximum value, so I set it as an Integer and set 0 for the minimum value (and put a suffix to show up for the price).

However, the field contented is generated by parsing a JSON feed, and the feed owner sometimes puts "on demand" for some items, meaning the price can be negotiated on demand or the price is private and only shared when a client shows enough interest to buy.
The Feeds JSONPath Parser module parses the text string and doesn't import the fields with text for the Price field as it's not an Integer. Therefore resulting in a blank field input.

Should I replace all empty values with a 0 and then on view results set 0 to be rewritten to the "on demand" text? Or is there another way that I should explore?

I need to keep the Price field as an Integer since I use it for a range filter in my view.

If you have only one possible non-integer value, leave it as integer, just make it optional (not required). As far as I understand Feeds JSONPath Parser, non-integer value will simply get omitted, giving you no value for this field - exactly consistent as in fact you don't have that price.

Then in your template files check if it's set. If it isn't, show "on demand" string, with a link to make a demand or, well, anything you need.


Metatag is not showing on front page whereas the front page is set from custom content type I have a custom content type "Community" and a page from this content type is selected as front page on the drupal 7 site (from system/siteinformation). i am using Metatag module. All other pages are showing the metatags but the front page does not.

I've also tried by overriding the metatags in admin/config/search/metatags/config/global:frontpage/edit, but still not showing up.

If your are using page--front.tpl.php add the below line and clear the cache.

  <?php print render($page['content']['metatags']); ?>

Meta tag will be added to the front page.


How do I clean up the sessions table? I need to delete entries about anonymous user login from the sessions table.

I read what reported in
https://techcommons.stanford.edu/topics/drupal/sessions-table-cleanup.

Which PHP setting in the page above ensures automatic removal of anonymous user login entries from the sessions table handled from Drupal? Do the suggested settings have any effect on that database table?

Go to your Drupal installation directory     /sites/default/settings.php and add the following line

ini_set('arg_separator.output',     '&amp;');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     10800);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  10800);
ini_set('session.gc_maxlifetime',   10800);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');
ini_set('session.gc_probability', 1);


Views: custom field for sort criteria My View has a " Global: Custom text"- Field that contains Integers (1,3, ..). The field is overwritten by a php-Template.

I want to add this field to "Sort criteria", so the view can be sorted - but how can I do this? the custom field does not show under "Sort criteria", how do i make it sortable?

You cannot sort by a global text field in views by default.

This is because global text field values are not populated until the view is being rendered, but the sorting of the view is done in the sql query, which is much before the global text field value exists.

One way to do it would be to add sorting ability with javascript.
Because this would happen on the front end it could work for any fields.
The views tablesorter module does this for drupal 6 table views but I have not yet found the time to make a drupal 7 version.

Another option is to make a custom views field handler that actually includes the data in the sql query or just making a custom sort handler.

For more information on creating handlers install the advanced help module and then go to the advanced help UI and look at the views help (advanced_help/views).


Display view nodes in lightbox? What would be the best way to show the nodes from a view in a lightbox, triggered by a single image?
The idea would be that a nice photo is shown on a frontpage. When users click on it, a view is opened in a lightbox/thickbox/colorbox/*box. This then shows all nodes in the view.

I currently manage to do this for only images with colorbox, but that's not sufficient as I would like to show captions etc.
I would like to use the full colorbox functionality, rather than just the image. I tried using an iframe, however this meant every node is shown with the full site theme (header, logo, footer etc) which is not what I want to do.

I managed in my project by using a custom page template and and an additional get parameter.

Template.php: (In active theme directory)

function phptemplate_preprocess_page(&$vars){
    if( isset($_GET['ajax']) && $_GET['ajax']=='true' ){
        $vars['template_files'][] = 'page-overajax'; # For Drupal 6
        $vars['theme_hook_suggestions'][] = 'page-overajax'; # For Drupal 7
    }
}

I then created a template file (page-overajax.tpl.php) in theme directory with following content:

<div id="overlay-content-wrapper">
   <?php print $content; ?>
</div>

After this (Clear all caches) you can use any path (page, view, node) with ?ajax=true to pass to your *box to load if it supports for AJAX content.

As using with fancybox:

$("a.overajax").fancybox({
    'width': 400,
    'height': 400,
    ajax: {
        type     : "GET",
        cache    : false,
        url      : "user/user-posts?ajax=true",
        success: function(data) {
              $.fancybox(data);
        }
    }
});


Send a regular reminder (or do other normally cron-dependent tasks) while in maintenance mode I recently had an episode where I put a site into maintenance mode to perform a security upgrade and forgot to go live again afterwards, resulting in almost a day of downtime before I caught the error.

I thought I could set up a rule to send me an e-mail whenever cron runs if it detects that the site is in maintenance mode, but I don't think that's going to work because cron can't execute when maintenance mode is on. A preliminary test seems to confirm that. I put the site in maintenance mode, attempted to run cron manually, and no e-mail was generated.

Is there another module or method I could use to send myself a reminder so this won't happen again?

I, personally, can think of a hamfisted, hacky way do do this, but I would prefer for someone else to provide a more elegant solution.

My web host doesn't allow SSH, but does have a "tasks" feature that essentially pulls a designated website URL at regular intervals; I'm currently using it to run Cron externally and get around Drupal 7's default Poormanscron implementation.

So I could bootstrap Drupal from a custom script and have it get pulled as an hourly task. It would variable_get('site_offline') and do nothing (or maybe redirect to index.php in case a 'bot discovers it) if false and invoke the Rule that sends the reminder e-mail if true.

Heck, if Rules or Drupal's e-mail abilities are also disabled while in maintenance mode, I can just generate the e-mail with straight PHP.


Drupal 7- "Users who bought this also bought that" module Does anyone know of a module for Drupal 7 that provides a "users who bought this also bought that" feature?

I found Ubercart Views but it only works for D6, not D7.

My site uses Drupal 7 and Ubercart.

There are two modules available for Ubercart; the first one is Ubercart Products Recommender which provides a View for:

  Users who ordered this product also ordered.

The second is easyrec for ubercart, which provides a block called:

  other users also bought

Either one should be fine for what you want, and both have a stable Drupal 7 version available.


Private 'My Files' in Drupal Commons I am using the latest release of Drupal Commons and I have Private Files configured and working.

I would like to allow users to upload files to their individual user profile, which only the individual user can view/download after upload. For example, a user may upload 3 files to their profile, but these should be private and not visible or accessible to any other site user.

With Private Files configured, I thought this may be possible via a File field on the user profile, but I have been unable to restrict view to the document owner.

Has anybody acheived a similar result with Commons (with or without addional modules)?

Thank you

I've done this before using the IMCE module. The description from the module page says:

  IMCE is an image/file uploader and browser that supports personal directories and quota.

So spot on for your needs.


How do I prevent Drupal raising a segmentation fault when using a Node.js theming workflow? Symptoms:
Some drush commands fail; Some Drupal pages are blank.
The failing drush commands report "Segmentation fault: 11"
The Apache log (e.g. php-error.log in MAMP) also shows the same error.
Background:
If you use a gulp or grunt workflow - to compile your theme's SASS etc. - you may run into a problem where drush commands throw a segmentation fault 11 as does Apache whilst serving Drupal pages as blanks (WSDs).
Probable cause
This is because files from your grunt or gulp workflow environment in  node_modules are erroneously being registered by Drupal itself as a bi-product of drush cache-clear all for example. There are dozens of these .js files and Drupal can't handle them ... it's possibly a PCRE regex that is the root cause as this is known elsewhere. Anyway ...
It doesn't always happen
It's not clear whether some modules (like Browser Sync for example) induce this error as a node.js style (i.e. gulp or grunt) workflow can work perfectly before failing in this way.

Here is the solution you're looking for. Much more elegant and less work:

"scripts": {
  "postinstall": "find node_modules/ -name '*.info' -type f -delete"
}

Just a slight alteration on @iamcarico's answer above.

note: you may need a .npmrc with just the following content:

unsafe-perm = true


Using ImageStyle with dependency injection Is there a way to use the ImageStyle class with dependency injection instead of a static call?

I am struggling to find an example.

At the moment I have a block which is importing the class with

use Drupal\image\Entity\ImageStyle;

And then calls the load method with

ImageStyle::load('machine_name')->buildUrl($path);

But I am wondering if there's a better way to do this?

Yes, inject the entity_type.manager service and load it that way:

$url = $this->entityTypeManager
  ->getStorage('image_style')
  ->load('machine_name')
  ->buildUrl($path);


Create relation N:N and specify properties for each relation I have two content types: "Car" and "Options".
My cars can have different options, so I could associate options to a car with References Module. But my problem is I'd like to specify the price of the option for each car/each relation.

Example:

Seat    - Airbag - 100 €
Citroen - Airbag - 88 €

The relation is not only a node reference, it has "metadatas".

For the moment, I plan to develop my own module, maybe "Relations" module will be the solution, but I tried it with no success.

How can I solve this problem?

If there is an existing contrib module for that, that would be Relation. It works at the level of Entities. It should provide a generic API/framework that can be used for what you describe.

If Relation doesn't fit your needs or is not ready for you, then writing a custom module would be the only option. For a custom module, I would work at the Entities level (with the help of the Entity API module), not directly in SQL. While Drupal doesn't provides scaffolding for Entities, it provide helper functions such as field_attach_form() or field_attach_insert() to deal with fields on entities. Unfortunately, the documentation on how to properly use entities is still scarce. The Model module is an attempt to help there since it aims to provide a model entity and entity administration interface to kick-start your entity development.


How can I get the taxonomy tree by the vocabulary ID? I want load all the taxonomy terms by their vocabulary ID in Drupal 8. In Drupal 7, I would use the following code.

$terms = taxonomy_get_tree($vid);

What code should I use in Drupal 8?

You can load terms using the entity query,

$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
     $term_data[] = array(
      "id" => $term->tid,
      "name" => $term->name
     );
    }


How to show a table depending on a drop down selection? Initially there is only drop down menu in the form, when a selection is made I want to display a table in the same form.

$form['blood_group'] = array(
    '#type' => 'select',
    '#title' => t('Blood Group'),
    '#options' => array(
        'a+' => 'a +ve',
        'b+' => 'b +ve',
        'ab+' => 'ab +ve',
        'o+' => 'o +ve',
        ),
    '#required' => TRUE,
);

suppose if the user selects a+ i have to show the table containing names of all the people with the same blood group.

You can take a look at the #ajax property of the Drupal Form API.

Here is a good start :

$form['blood_group_wrapper']['tables'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['blood_group_wrapper']['blood_group'] = array(
  '#type' => 'select',
  '#title' => t('Blood Group'),
  '#options' => array(
      'a+' => 'a +ve',
      'b+' => 'b +ve',
      'ab+' => 'ab +ve',
      'o+' => 'o +ve',
      ),
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_show_table',
    'wrapper' => 'table-wrapper',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

function ajax_show_table($form, $form_state) {
  $table = '

';
  $form['blood_group_wrapper']['tables']['#markup'] = $table;

  return $form['blood_group_wrapper']['tables'];

}


Implementing preprocess function for custom template In Drupal 7, I'm creating thank you page for a custom form and have following in my mymodule.module:

function mymodule_menu() {
  $items = array();

  $items['mymodule/thank_you/%'] = array(
    'title' => 'My Module Thank You Page',
    'description' => 'my module thank you page',
    'page callback' => 'mymodule_thank_you_page',
    'access arguments' => array( 'access mymodule thank you page' ),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_theme() {
  return array(
    'mymodule_thank_you' => array(
      'variables' => array(
          'form_id' => NULL,
          'content' => NULL,
          'title' => NULL,
      ),
      'template' => 'thank-you',
      'file' => 'mymodule.theme.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
    ),
  );
}

function mymodule_thank_you_page() {
  drupal_set_title( t( 'Thank You.' ) );

  $variables = array();

  return theme( 'mymodule_thank_you', $variables );
}

In mymodule.theme.inc, I have:

function template_preprocess_mymodule_thank_you( &$variables ) {
  $variables['title'] = 'test';
}

The problem I'm facing is that while I can access the thank-you template correctly, it doesn't read any of the variables I define in the preprocess function in the theme.inc file. Can anyone advice what I'm doing wrong for this?

I tried your thing on my local server. And its working fine. Just try in your template:

<?php
  // Print your defined variable here like this.
  print $title;
?>


How to count entity references from same field in different entity types? I have three entity types:

Company
Team (has field_company which is an entity reference to    Company)
Employee (also has field_company, and field_team which is an
optional entity reference to Team)

The idea is that all Employees are at least part of a Company, and possibly part of a Team within that Company.
Using the Reference Field Option Limit module I have limited the options shown for field_team to only show Teams for the selected Company.

So far so good.

Now I want to create a table view with the following columns:

Company Name
Team Count
Employee Count

I have created two relationships to referencing entities for field_company, and created a type filter for their types (Employee and Team). The problem is that Companies with no Teams, or no Employees are filtered out.

Any help with solving this deceivingly simple problem would be greatly appreciated!

Firstly, create a users view of the format: table with aggregation options with the following fields:
- Company ref.
- Team ref.
- User name.
Then go into the table's settings and add a group and compress function to the first field, and count to the others. Optionally you can use the tally members function and you'll get team names with counts displayed between parenthesis.

Secondly,.. well this is simple but depends on how much you are comfortable with php.

Create a views_preprocess_view (either that or _views_pre_render) function in your theme or in a custom
module.
Install and enable devel and use dsm() in your function to print the resulting array of your view.
Use entity field query to get a list of your companies.
Compare your views results array with the entity field query results to figure out what is missing from the list.
Add it to the view with 0 or dashes for counts.


How can I safely move a module to another folder? I created a module through Drupal Console, unfortunately it wasn't placed in a folder of its own, rather straight into /modules/custom. Before I noticed where it had gone, I enabled the module.

In Drupal 6/7, this was easy to fix - I could literally just put the files into the correct path, clear the cache (maybe rebuild the registry, it wasn't an exact science), and all was well.

The same isn't true for Drupal 8; I moved the files into a subfolder, rebuilt cache, and all requests tell me that Drupal is failing to include a required file. The particular file is a block class, and the path Drupal is trying to find it is where it used to be, not where I've moved it to.

The bit of code objecting is in Symfony's ApcClassLoader, so I guess I need to clear something that's slightly above Drupal's head to get this path reference updated.

How can I do that?

Uninstalling and re-installing the module does work, but once there's important data stored that's not going to be an option.

I was wrong, uninstalling and re-installing is not a viable option. After uninstalling and reinstalling, Drupal can no longer pick up the custom blocks the module defines. I'm guessing that reference is cached somewhere that isn't cleared when the module is uninstalled. Just need to find out where that is and how to clear it...

Just restart apache. The APC cache will be rebuild then.

You can also try to hit rebuild.php or run drush cr. Those all attempt to explicitly clear the APC cache.


How do I programmatically delete a reference field value? I have a multi-valued taxonomy reference field named field_classrooms in a node type. I use below code to delete the value in the field.

$node = Drupal\node\Entity\Node::load('1512');
unset($node->field_classrooms[0]);
$node->save();

I can't figure out what I am doing wrong here.

Maybe something like this could help you out

// Get the list of the associated classrooms ...
$classrooms = $node->get('field_classrooms')->getValue();
// ... if there are any associated classrooms ...
if(!empty($classrooms)) {
  foreach($classrooms as $classroom) {
    // ... get the key of the classroom
    $key = array_search(current($classroom), array_column($classrooms, key($classroom)));
    // ... remove the relationship ...
    $node->get('field_classrooms')->removeItem($key);
  }
  // ... and save the node.
  $node->save();
}

If you want to remove a single classroom from the list and you already know the tid

private function removeClassroomFromNode($node, $tid) {
  if(null != $node) {
    // ... get the list of associated classrooms
    $classrooms = $node->get('field_classrooms')->getValue();
    // ... get the key of the classroom
    $key = array_search($tid, array_column($classrooms, 'target_id'));
    // ... remove the classroom
    $node->get('field_classrooms')->removeItem($key);
    // ... save the node.
    $node->save();
  }
}


How to automatically update field values for all translated nodes I have original node which is in english. Then I have another node which is a translation of the original node. Both of these nodes have the same image field. When I update the value - change the image for the original node and save it, the change doesn't apply to the second node (the translation of the original node). How do I make the field changes sync across the translated nodes?

Thanks.

There is a Synchronize Translations module which is part of the Internationalization Module and which allows you to synchronize one (or more) fields across translations.

Once you have the module installed and enabled you can navigate to the content type in question and in the Synchronize Translations-tab check all fields you want to synchronize.

Check the Documentation here: Synchronize translations.


Target single block with amended theme function? I have amended theme_user_list so that the user picture is printed out just before the username. I would like to use this function only on the Who's online block. Is there anyway I can make this block be the only target for my amended function? Thanks.

function MY-THEME_user_list($variables) {
  $users = $variables['users'];
  $title = $variables['title'];
  $items = array();

  if (!empty($users)) {
    foreach ($users as $user) {

      // $items[] = theme('username', array('account' => $user));

      $picture = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $user)) : '';
      $username = theme('username', array('account' => $user));
      $items[] = $picture . $username;
    }

  }
  return theme('item_list', array('items' => $items, 'title' => $title));
}

you can use preprocess_block function as follows:

 function mytheme_preprocess_block(&$variables) {
      if ($variables['block_id']->bid === 'target_block_id') {
       $users = $variables['users'];
      $title = $variables['title'];
      $items = array();

      if (!empty($users)) {
        foreach ($users as $user) {

          // $items[] = theme('username', array('account' => $user));

          $picture = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $user)) : '';
          $username = theme('username', array('account' => $user));
          $items[] = $picture . $username;
        }

      }
      return theme('item_list', array('items' => $items, 'title' => $title));
      }
    }


Schedule Delivery Time and Date Is there a module from Drupal Commerce to schedule Delivery date and time ?

Customer is required to specify the date and time. This then will be displayed in the admin side.

thanks appreciate your help

Check it out Commerce Field Group Panes module. Using this you can able to add field Delivery Date & Time field to check out process.

  This enables an easy way to collect information in the checkout
  process. For example customer comments, feedback about where the
  customer founds the shop or any other fieldable information.


Adding options to Drupal search I've been working on a site and I need to change the search.

I've changed the search form with hook_form_alter(), added some checkboxes, ... Now I need to get the new data to the hook_search_execute() function?

How would I achieve that?

Drupal's search platform is rudimentary one. You can't really extend it, best you can do is to replace it. Most popular free platform now seems to be Apache Solr, connected to Drupal with Apache Solr Search Integration.

If Solr's to much, Search API integrates with views pretty neat, you can have one field for search and other as Views filters.


Publish Node Confirmation When a user is creating content I need them to confirm (once clicking publish) that they are sure that they want to publish their post. I've been searching but cannot find an answer anywhere. I'm hoping for a modal window of some description that pops up with a message and confirm/cancel/save as draft buttons.

Any ideas?

Under /admin/structure/types/manage you can select the content type, and adjust the submission form settings to require preview before submitting.


Create an Availability calendar/table in Views I am trying to create a calendar table in Views to display availability states for multiple product rows, e.g. for a car rental site.
I have spent the evening researching modules that might be suitable, namely availability calendars (which I am familiar with) and a bunch of views plugins, even considered modifying rooms or uc_hotel modules to suit.. I haven't found anything that fits the bill exactly, but that's what I expected, so I'm looking for some recommendations or a solution. I have attached an illustration of what I am trying to achieve. Any help or pointers much appreciated.

An update.. in the end I decided against using views, and used a library called dhtmlx scheduler timeline. It's turned out to meet the requirements spot on, and wasn't too difficult to wrangle into Drupal..


How to get a dynamic Google map with filtered views and show a marker related to the selected item? I plan to create a real estate agency website. In the front page, users can select the type of contract and specific other things to get a list of all the nodes that fit those criteria. So the result is a view (filtered).

I want to get a Google map with marker related to this result. This is possible, but the thing that I can't do is this: when I select an item from this filtered view (with a checkbox for example) I want to recalculate the Google map with only this or those items selected.

About the modules I'm using: in fact until now I use nothing, this is why I post the question, to know if a module (such gmap or simple Google Maps) is better for doing such kind of stuff.

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


How can I display a confirmation message after someone subscribes via simplenews? I want to show a message after users submit their email in Simplenews block.

Currently when the user clicks on the subscribe button, the page is refreshed and no message shows ups.

Instead, I prefer to show a message with javascript in modal or something.

Any help/suggestions?

Consider using the Rules module to implement this. And enable the Simplenews rules module (a sub-module of Simplenews).

Then create a rule like so:

Event: "A user has been subscribed".
Action: "Show a message on the site" (located within "System").


How to appened a new 'class' attribute to a custom field ? - twig drupal 8 Just started to work around with Drupal 8.

I want to add class "center-block" to the field_product_image.

How do i do this guys?
below is the twig code

   {% if content.field_product_image| render %}

    {{ content.field_product_image }}

    {% endif %}

        {{ content.body }}
        {{ content.field_features }}

Normally I would say to call addClass() on the image.attributes variable in your image Twig file, but I believe images don't have a lot of template suggestions (everything goes through image.html.twig) which means that your class will be added to all images. Likely not what you're looking for...

Option one, inspect the variables in image.html.twig and see if they give you the information you need to determine when to add the new class. If so, do it in the Twig template (attributes.addClass('new-class')).

Option two, implement hook_preprocess_image in your theme's .theme file. Something like this:

function MYTHEME_preprocess_image(&$variables) {
  if (some_way_to_figure_out_if_this_is_the_right_image) {
    $variables['attributes']['class'][] = 'new-class';
  }
}

Hope that helps. (Edited for better code formatting).


Search API Solr integration with fivestar (or similar) rating system (fascet and sort) I'm attempting to sort nodes by ratings using the Search API faceted search with Solr integration. I've already set up fivestar ratings (about 9 per node, its a large multi-axis rating system.) but i'm unable to index these ratings!

Can someone help me understand how to change this so I can use a facet search for ratings?

Otherwise, are there any recommendations on other modules (aside from fivestar) which would allow the votes to be indexed?

Thank you!

Justin

You can best create a new Entity property in a hook_entity_property_info_alter(), and add a custom field "rating" with a custom getter callback. Like so:

...
      $properties = &$info['flatrow']['properties'];
      $properties['my_indexable_rating_axis_1'] = array(
        'type' => 'integer',
        'label' => t('Rating axis 1'),
        'query callback' => 'entity_metadata_table_query',
        'getter callback' => 'rating_axis_one_get_properties',
      );
      return $properties;
...

Use it to extend the node entity. The getter callback is where you retrieve the value to be indexed,

function rating_axis_one_get_properties($entity, array $options, $name, $entity_type) {
  $value = $node->field_fivestar['average_rating']; // I made this up, check how to do it

  return $value;
}

Then index the field with Search API.


How to assign IDs to each radio button in drupal form radios? I am using drupal form radios, I can use Prefix and Suffix to assign IDs to group, how can I assign different IDs to each radio button inside the radios element? Thanks

You need to use theme_radios() hook in your template.php file, if what you get is insufficient.

Parameters
$variables: An associative array containing:

element: An associative array containing the properties of the element. Properties used: #title, #value, #options, #description, #required, #attributes, #children.

Return value
A themed HTML string representing the radio button set.

To interfere with single radio element, see theme_radio(), of course.


How to use websolr with Apache Solr module? (D7) I´ve got a Drupal 7 site and I would like to use apache solr.

Is there any way to connect websolr to that module? Haven´t found any module to do that (ie. as the Acquia module).

Thanks!

Apache Solr presents a generic API, and you should be able to use any search module which uses Solr with Websolr. We tend to recommend the Apache Solr Search Integration module.


Allow non-members of an OG to post group content I'm building a website with the use of Organic Groups module. I need to allow all registered users (not only group members) to have permission to post nodes of a certain content type to any group. However I failed to achieve this behaviour as well as finding helpful info online. Can anyone please advise me on how to make this? Are any additional modules needed?

You need the OG permissions overview menu (admin/config/group/permissions). You can find there permissions to let non-members post content.


How to properly set up Drupal Console on Windows 7 I have been trying to set up Drupal Console for quite some time now on Windows 7; however, there always seems to be some kind of error which I am unable to solve.

I have installed Drupal Console via the drupal.phar way which I placed in a directory that is included in the PATH variable and it gets called properly. However, every time I call the console from the command line it gives me the following notice:

Notice: Undefined index: commands in phar://C:/_Skripty/drupal/vendor/drupal/console-core/src/Utils/ConfigurationManager.php on line 273

The second weird thing is that I want to use it in multiple project and it does actually seem to be working, in a way, in one of the projects but not in the other. For example, I am able to get the list of available commands in one, but running that same command in the other produces the following fatal error in addition to the above mentioned notice.

Fatal error: Trait 'Drupal\Console\Command\Shared\ModuleTrait' not found in C:\xampp\htdocs\sam_stroje\modules\metatag\src\Command\GenerateGroupCommand.php on line 32

I suspect that this might be caused by some modules not correctly implementing the stuff that has to do something with the console but I'm not 100% sure.

What might be the cause of these problems?
Thanks in advance for all replies.

This will surely help you debug: https://evolvingweb.ca/drupal-console-windows-devdesktop-troubleshooting

And here is a guide explaining how to do it from scratch: https://evolvingweb.ca/blog/installing-drupal-console-windows


How to properly check in entity form validation if field is empty? I have a content type "A" (Node entity type).
In it's node form (new/edit) I need to check if some fields are empty or not (which are not required in general).
My first intention was to use FormState "getValue", "isValueEmpty", "hasValue" functions, but I can't figure out how to easily solve this problem:

Text fields has value: array("value"=> "") if they are empty, and it's not considered empty by the functions above (so I can't use them)
I could check by myself for isset($field['value']), but there are also file fields and entity reference fields which has a whole different "value" structure.

So what would be a clean way to achieve this?

I think I found what I was looking for, ContentEntityForm does it like this:

/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $this->buildEntity($form, $form_state);
$violations = $entity->validate();

All I have to do is building the entity, after that I have to just check the right field, which has already the ability to tell per fields if they are empty or not. (since each field is knowing it's type and also how to check if there is a value or not)


Drush CC all returning "No Drupal site found, only 'drush' cache was cleared" I've tried other solutions, but none of them are specific to my setup. I just started using the new Linux subsystem featured in the recent Windows 10 update. I'm using WAMP x64 v3.0.6, and have successfully cloned my website and got it up and running. At the root of the Linux subsystem, I installed Drush globally with Composer, using the directions given on the Drupal webapage.

Typing drush status returns the following when I run it in my default directory:

Drupal version         :  7.50
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  aerosphere
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/bob/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /mnt/c/wamp64/www/drupal-7.50
 Site path              :  sites/default

But, as mentioned in the title, drush cc all returns No Drupal site found, only 'drush' cache was cleared.[warning] I assume it has something to do with adding a path to the .bashrc, but I don't know what to add. Any tips would be greatly appreciated!

My question is different from "Drush - No Drupal Site Found when clearing cache", they're on a Mac and using MAMP, and I'm using WAMP on Windows. I've tried the solutions offered on that post, but the issue has not been resolved.

I'm obviously having issues connecting to MySQL as I get this when I run mysql command:

  The program 'mysql' can be found in the following packages: * mysql-client-core-5.5 * mariadb-client-core-5.5 * mysql-client-core-5.6 * percona-xtradb-cluster-client-5.5

  Try: sudo apt-get install .

So I've added these lines to my .bashrc file:

PATH="$HOME/.composer/vendor/bin:$PATH"
export PATH="/mnt/c/wamp64/mysql/mysql5.7.14/bin:$PATH"

The top line was added to get drush working. I've checked multiple times, and I have the path correctly set, but it's still not working.

There are a few things you can do to help debug your drush. Here is what you can try:

Debug output

Use drush cc all -vvv

This will provide you with some valuable information in terms of what Drush is doing in the background and maybe show you the actual error message.

Check your settings.php

Depending on your setup you may be passing in environment variables to your settings.php file for a database configuration for instance. Or perhaps to provide memcache. Drush unfortunately does not pick these up as it's bypassing apache. Therefore I would give it a test run without environment variables to see if that eliminates the issue or help narrow it down. For debug purposes it may be worth just using a clean copy from the example.settings.php and just modifying the database array to test this.

Check the mysql client is available

This is one that tripped me up a while ago and the drush -vvv will point you in the right direction. If it can read the settings.php, which it appears it seems to be able to as it gets the db settings, then perhaps it can't connect to your mysql database. One of the issues I had was that mysql client command was not available. E.g. try calling 'mysql' and see if that works. After fixing that it worked. In my Mamp setup it was just a matter of ensuring the correct path to the executable was in my shell $PATH.

I hope this helps.


if empty statements in views fields or field templates Normally, my situation is easily solved using views rewrite feature. However, in this case I am unable to use views rewrite because I have data attribute tags in the field wrappers that are stripped out by views. So I need to handle this at the template level. I have no problem with the field data itself, but with the field wrappers. I need to use php if statements in either views-view-field.tpl.php or views-view-field.tpl.php to enclose the wrapper html too along with the field. But i can't figure out the php syntax to use to accomplish this. I need to be able to show the field data plus wrappers if the field has content, but show some empty field without the wrappers if there is no data.

so far i have tried things like views-view-field.tpl.php

<?php if ($output): ?>

<?php print $output; ?>

  <?php elseif ($empty($output)): ?>

      <?php print $empty; ?>

  <?php endif; ?>

How can i revise my if statements to it works in either fields or field.tpl.php?

First of all, there is no such thing as $empty in views-view-field.tpl.php

Second, if you're not printing anything when the output is empty, then there is no need to add an else statement. Thus, this should do the trick:

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

<?php print $output; ?>

<?php endif; ?>

The first line means if NOT empty, in PHP ! = not.


Drush on Macbook Pro cannot read Dupal Correctly NOW RESOLVED! Tried to get Sass & Compass working on Windows, but ran into too many problems.  Now I have purchased a vintage Macbook Pro (2008).  I finally got Drush working on Windows, but I can't seem to get Drush to work on the Macbook.

ON THE MAC: I am using a MAMP-Stack.  I tried installing Drush-6.0, but it began to ask for 'Composer' and other such further complications.  I installed Pear, but could not figure out the instructions to use Pear to install Drush. So I tried a simple install of Drush-6.0 from a Tar file Download.  I installed it to the '/Applications/MAMP/htdocs' Folder.  It could download Modules and Themes, but Drush could not do a simple Status check or Cache-Clear.  Somehow it could not interact with Drupal.

Next I tried a Zip Download of Drush-5.9.  I removed the previous Drush-6.0 from the 'htdocs' Folder with 'rm -rf drush'.  I installed Drupal-5.9 by pulling the Zip into my  Folder.  Then I did a 'chmod u+x drush' in the working directory of drush.  Then in the same HOME Folder, I edited the .bash_profile and .bashrc Files in Vim.  There is nothing in either of those two files that refers to the previous Drush Path (htdocs) from the previous installation, but now they instead point to the new installation of Drush-5.9 (In the '/Users/MY-NAME/' Folder.

However, when I try to launch Drush, Drush can do a status-report. It reports Drupal, but incorrectly reports the Garland-Theme being used, which is NOT the Default Theme.  By the way this same output happens if I am in the Omega-Theme working directory or the Drupal-Root working directory.

Drush also fails to accomplish a simple 'drush cc' (only the Drush-Cache is available to clear).  Drush cannot do a 'drush pm-list', instead I get an error message about Drush not being able to bootstrap the Drupal Database.

I read the 'read-me' in the Drush-Installation-Folder and tried to follow the prescription for changing my PHP direcory in .bash_profile.  Then trying to follow the instructions for configuring php.ini, I got lost at the point where you try to find out what version of php your Webserver is using (I presume this means MAMP, maybe not).

Now I am at a loss as what to do next to get Drush functional.  Any help is greatly appreciated.

BASH_PROFILE:

# Set Architecture flags

export ARCHFLAGS="-arch x86_64"

#Ensure user-installed binaries take presidence

export PATH=/usr/local/bin:$PATH

export PATH=/Users/ChandraSwami/pear/bin:$PATH

export PATH=/Users/ChandraSwami/Dev:$PATH

export PATH="$PATH:/Users/ChandraSwami/drush:/usr/local/bin"

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.4.24/bin:$PATH"

#Load .bashrc if it exists

test -f ~/.bashrc && source ~/.bashrc

:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a
function*

source ~/.profile

END-BASH_PROFILE

RESOLVED. 9/22/2014

I began to discover that the previous method of attempting to change the 'alias' or otherwise redirecting Drush to use MAMP's PHP was the wrong way to go. Especially 'name-distorting' the original MacBook-OS-PHP so that Drush would opt for the MAMP-PHP was causing all kinds of problems with other software, as might be expected. I don't know how this method came to be recommended, but it appears that it is actually a pit-fall.

The way better approach (watch me eat my words in a few weeks), is to rather just upgrade the MacBook-OS-PHP to the same or nearly same version as the MAMP-PHP. Then it does not matter which version of PHP Drush or anything else uses because they are both the same. This overcomes all the issues and is not that difficult to accomplish. At least on my platform which is a MacBook-Pro (2008-Mavericks).

The way that I upgraded my MacBook-OS-PHP was by the CLI-command "curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5".

This is a download from a group of developers in Germany which upgrades your PHP. Check out "http://php-osx.liip.ch/".

Once my System-PHP and MAMP-PHP were almost the same, all my issues with Drush went away. I undid all my 'aliases', 'redirects' and 'name-distortions'. So far all is working well.

Note that on my machine MAMP is using PHP-5.5.14 and my CLI reports with a "php -v" command that MacBook-OS is using PHP-5.4.30 though I am not sure that the version is accurate. In the write up on the PHP-Upgrade it mentions that the version might not be accurate.

By the way this does not OVERWRITE your previous PHP installation but rather just adds a newer installation and directs your system to use it.

I will update if there later prove to be drawbacks in this approach.


How to remove the ADD USER in the “admin users area” in Drupal 7 I already did the admin only register but I would like to remove this tab if anyone can help me

Thanks

That link is available to users with the "Administer users" permission enabled. You can disable that permission for all roles other than a role you create, and then give your account that role (or users you want to delegate this to), which would result in only you (or a limited number of people) with access to that link.  Hope that helps!


"Simple FB Connect" module return page not found when user path replace with another module called "Rename Admin Paths" Hi I am using "Rename Admin Paths" module for replace "user" path to "account" & working good. But today when I am trying to integrate "Simple FB Connect" module with my drupal 7 site, it return Page Not Found - when try to navigate domain.com/account/simple-fb-connect. But when i try domain.com/user/simple-fb-connect after disable rename_admin_paths module, its working, i can connect with facebook.

I am trying to replace all 'user/simple-fb-connect....' path to 'account/simple-fb-connect....' into simple_fb_connect modules files, but no luck!

Can anyone help me please... how can i configure simple_fb_connect with rename_admin_paths module.

Thanks.

after 2 days, i solved my problem by change 'user/simple-fb-connect' to 'connection/simple-fb-connect' and its now working.


Rewrite output for view field only when certain condition is met? You have a list with Views
It contains titles of nodes.
When clicked those titles redirects to the nodes.

How to make a condition that if e.g. a checkbox is selected in the node saying something like e.g. 'Don't link this to the original content, redirect it somewhere else instead', then overwrite the default path of that node title to something custom?

I found a module https://www.drupal.org/project/views_conditional does it do what I'm trying to achieve?

So e.g. you have a list with 10 nodes titles, 9 of them links to its content, but 1 links somewhere else because it has a checkbox/term selected in the node's settings?

You can do this with the UI with some of my favorite Views trickery.

Go to your content type, click the Boolean field and change its Off value to 0.
Create a new view and add the Title field twice. Rewrite the link for one of them, and Exclude both from Display.
Add your Boolean field to the view and..

a. Rewrite the title of this field: [title]

b. No Results behavior: [title_1]

c. Count the number 0 as empty: ✓

d. Hide rewriting if empty: ✓

Because you changed the Off value of the field to 0, you can make Views trigger the No Results Behavior for the field. I've just tested this and it works fine so ask if you have any trouble.


blocks forgetting region placement So i've run into an issue with a block somehow losing its region placement somewhat randomly.
For background the block is very simple

        $blocks['tx_leftcol_block'] = array(
      'info' => t('Tx leftcol block'),
    );

The content isn't the issue, as even with some static content this block disappears.

On the blocks overview page this is placed on a custom region called tx sidebar (its a sidebar for certain pages). The weird part is other blocks show fine in this sidebar and dont lose placement, but for some reason this block gets disabled randomly, i.e. every couple of login/logouts it hides, or after a certain amount of time.

Any ideas what could be the cause?

It turned out to be a caching issue which i resolved by suing the block_flush_caches
method.


Can a domain redirect work for both http and https? Currently hosting a site on Pantheon and I would like to redirect traffic to a single domain. There is already a lot of links inside my site that are using:

http://example.com/somepage, http://www.example.com/somepage, https://example.com/somepage, https://www.example.com/somepage

Since Pantheon uses nginx I would have to use settings.php to redirect traffic. My Question is would it be possible to direct traffic to a single domain but it can be served in either http or https?

Some sample code:

// Require www.
if (isset($_SERVER['PANTHEON_ENVIRONMENT']) &&
  ($_SERVER['PANTHEON_ENVIRONMENT'] === 'live') &&
  (php_sapi_name() != "cli")) {
  if ($_SERVER['HTTP_HOST'] == 'example.com' ||
      $_SERVER['HTTP_HOST'] == 'https://example.com') {
    header('HTTP/1.0 301 Moved Permanently');
    //or https://www.example.com
    header('Location: http://www.example.com'. $_SERVER['REQUEST_URI']);
    exit();
  }
}

Nginx/settings.php

Try this: $base_url = 'https://'.$_SERVER['SERVER_NAME'];

Apache/.htaccess:

You can simply add the following to your .htaccess. It will redirect all traffic from http://example.com and http://www.example.com to https://example.com. Put that below RewriteEngine on.

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www.example\.com*
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]


Possible to join different entity type on using EntityFieldQuery? I am wondering whether I can use EntityFieldQuery to fetch all entities belonging to a specific content type. This entity type has a reference to another entity type. Is it possible to check against the refereed entities fields in the same query?

No.

An EntityFieldQuery allows you to run queries based on field and property conditions, but it has no way to query the fields or properties of a referenced entity.

Such a thing would involve some pretty full on logic, and it probably wouldn't even be possible to provide a programmatic interface to it that made sense.


Node type created by custom module doesn't get updated I'm working on a custom module that creates a new content type. Recently I added a new field to the content type, but it doesn't get updated. I don't have any nodes of this type and when I disable my module, the content type is deleted. After I enable it again, the content type is back, but with the old setup and without the newly added field.
I'm probably overlooking something very basic, but I couldn't figure out what. I cleared the cache and run cron before and after I disabled and enabled my module.

I even tried to give a different name to my content type and fields, but then the content type is not created. I bet it's just some small mistyping or something.

What could be the problem?

Here is the code. I put the field arrays into functions, but I don't think this causes any problem.

function simplegal_node_info() {
  return array(
    'simplegal' => array(
      'name' => t('Simple Gallery'),
      'base' => 'simplegal',
      'description' => t('A simple gallery that will display all images from a given directory'),
      'title_label' => t('Title of gallery'),
      'locked' => TRUE,
    ),
  );
}
function simplegal_node_type_insert($content_type) {
  if ($content_type->type == 'simplegal') {
    $body_instance = node_add_body_field($content_type, t('Description'));
    field_update_instance($body_instance);
    foreach (_simplegal_installed_fields() as $field) {
      field_create_field($field);
    }
    foreach (_simplegal_installed_instances() as $instance) {
      $instance['entity_type'] = 'node';
      $instance['bundle'] = 'simplegal';
      field_create_instance($instance);
    }
  }
}

function _simplegal_installed_fields() {
  return array(
    'simplegal_gallery_dir' => array(
      'field_name' => 'simplegal_gallery_dir',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 60,
      ),
    ),
    'simplegal_thumb_width' => array(
      'field_name' => 'simplegal_thumb_width',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 10,
      ),
    ),
    'simplegal_thumb_height' => array(
      'field_name' => 'simplegal_thumb_height',
      'cardinality' => 1,
      'type'        => 'text',
      'settings'    => array(
        'max_length' => 10,
      ),
    ),
  );
}
function _simplegal_installed_instances() {
  return array(
    'simplegal_gallery_dir' => array(
      'field_name' => 'simplegal_gallery_dir',
      'label'       => t('The directory of the gallery'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
    ),
    'simplegal_thumb_width' => array(
      'field_name' => 'simplegal_thumb_width',
      'label'       => t('Width of thumbnails'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
      'default_value' => variable_get('simplegal_thumb_width',120),
    ),
    'simplegal_thumb_height' => array(
      'field_name' => 'simplegal_thumb_height',
      'label'       => t('Height of thumbnails'),
      'widget'      => array(
        'type'    => 'text_textfield',
      ),
      'default_value' => variable_get('simplegal_thumb_height',120),
    ),
  );
}

My wild guess is:

From hook_node_type_insert documentation:

  Respond to node type creation.
  This hook is invoked from node_type_save() after the node type is added to the database.

Because you're not "Uninstalling" the module after you disable it, the content type will be kept, but it will simply be flagged as "Disabled" in the "disabled" column in the {node_type} table.

Therefore that hook is not invoked when you re-enable the module, hence the new fields not added.

So what you need to do is after disabling the module, go to the Uninstall tab and uninstall it, or if you're using drush:

drush dis -y simplegal && drush pm-uninstall -y simplegal


How do I generate a form knowig its ID? Using Drupal 8, I want to use registration form outside user/register.

I can generate the user login form but I couldn't find how to get the user.register form.

So my question is, how can I render the user registration form?

The user register form is located in Drupal\user\RegisterForm. Check the annotation on the User class.

/**
 * Defines the user entity class.
 *
 * The base table name here is plural, despite Drupal table naming standards,
 * because "user" is a reserved word in many databases.
 *
 * @ContentEntityType(
 *   id = "user",
 *   label = @Translation("User"),
 *   handlers = {
 *     "storage" = "Drupal\user\UserStorage",
 *     "storage_schema" = "Drupal\user\UserStorageSchema",
 *     "access" = "Drupal\user\UserAccessControlHandler",
 *     "list_builder" = "Drupal\user\UserListBuilder",
 *     "views_data" = "Drupal\user\UserViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\user\Entity\UserRouteProvider",
 *     },
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },
 *     "translation" = "Drupal\user\ProfileTranslationHandler"
 *   },
 *   admin_permission = "administer users",
 *   base_table = "users",
 *   data_table = "users_field_data",
 *   label_callback = "user_format_name",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "uid",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/user/{user}",
 *     "edit-form" = "/user/{user}/edit",
 *     "cancel-form" = "/user/{user}/cancel",
 *     "collection" = "/admin/people",
 *   },
 *   field_ui_base_route = "entity.user.admin_form",
 *   common_reference_target = TRUE
 * )
 */

_entity_form: user.register pulls from here.


Drupal 8, "view ui query" to drupal code query api ? When we build a view from the view ui, we can show what is the "hard query" is executed, example :

SELECT node__field_house_count_added.field_house_count_added_value AS node__field_house_count_added_field_house_count_added_value, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {node__field_house_tags} node__field_house_tags_value_0 ON node_field_data.nid = node__field_house_tags_value_0.entity_id AND node__field_house_tags_value_0.field_house_tags_target_id = '4'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_1 ON node_field_data.nid = node__field_house_tags_value_1.entity_id AND node__field_house_tags_value_1.field_house_tags_target_id = '5'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_2 ON node_field_data.nid = node__field_house_tags_value_2.entity_id AND node__field_house_tags_value_2.field_house_tags_target_id = '16'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_3 ON node_field_data.nid = node__field_house_tags_value_3.entity_id AND node__field_house_tags_value_3.field_house_tags_target_id = '6'
LEFT JOIN {node__field_house_count_added} node__field_house_count_added ON node_field_data.nid = node__field_house_count_added.entity_id AND (node__field_house_count_added.deleted = '0' AND node__field_house_count_added.langcode = node_field_data.langcode)
WHERE ((( (node__field_house_tags_value_0.field_house_tags_target_id = '4') AND (node__field_house_tags_value_1.field_house_tags_target_id = '5') AND (node__field_house_tags_value_2.field_house_tags_target_id = '16') AND (node__field_house_tags_value_3.field_house_tags_target_id = '6') )))
ORDER BY node__field_house_count_added_field_house_count_added_value DESC
LIMIT 2 OFFSET 0

Is there a way for get quickly the query, but in the query api format ? Like :

$query = db_select('users', 'u')
  ->condition('u.uid', 0, '<>')
  ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
  ->range(0, 50);

Thanks :)

No, there is not.

You're also not supposed to write a query directly against entity or field tables yourself. Use the entity query API instead:

https://www.sitepoint.com/drupal-8-version-entityfieldquery/

$uids = \Drupal::entityQuery('user')
  ->condition('uid', 0, '<>',
  ->range(0, 50)
  ->execute();


How to add an autocomplete field with pure javascript I'm implementing the javascript library Annotorious which allow to add annotations on an image. My goal is to be able to link content with part of the image select with Annotorious. When we select a zone, Annotorious open a form we can personalize to add information we want link with the zone. In my case, I added a fieldtext but I want it uses the autocomplete but I don't know how to activate this behavior.
Regarding the code in core/lib/Drupal/Core/Render/Element/FormElement.php, the form element add the class 'form-autocomplete' and the attributes 'data-autocomplete-path' equals to the url of an autocomplete function on his input and inject the library core/drupal.autocomplete. Regarding this, I tried to reproduce the same behavior. But I guess something is missing because my field doesn't query my endpoint when I typed in it but I don't know why. I was also thinking this maybe doesn't work because it's add by javascript after the loading of the page but in this case, I don't know how to solve this problem.
Here my code:
My widget field:
class ImagePinWidget extends ImageWidget {

  public static function process($element, FormStateInterface $form_state, $form) {
    $element = parent::process($element, $form_state, $form);

    $element['preview']['#attributes'] = array('id' => array('my-image'));

    $element['#attached']['library'][] = 'my_module/image-pin';
    $element['#theme'] = 'image_pin_widget';

    return $element;
  }

}

My my_module.libraries.yml
recogito-annotorious:
  version: 1.x
  css:
    component:
      /libraries/annotorious/annotorious.min.css: { minified: true }
  js:
    /libraries/annotorious/annotorious.min.js: { minified: true }

annotorious-toolbar:
  version: 1.x
  js:
    https://cdn.jsdelivr.net/npm/@recogito/annotorious-toolbar@latest/dist/annotorious-toolbar.min.js: { type: external, minified: true }

image-pin:
  version: 1.0.0
  css:
    component:
      css/image-pin.css: {}
  js:
    js/image_pin.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - my_module/recogito-annotorious
    - core/drupal.autocomplete
    - my_module/annotorious-toolbar

image_pin.js:
(function ($, Drupal, drupalSettings, Annotorious) {

  'use strict';

  Drupal.behaviors.redacto_form_image_pin = {
    attach: function (context) {
      var config = {
        image:'my-image',
        widgets: [
          Drupal.behaviors.my_module_image_pin.nodeSelectorWidget,
        ],
      };

      var anno = Annotorious.init(config);

      Annotorious.Toolbar(anno, document.getElementById('toolbar'));
    },

    /**
     * Dynamic behavior when the status changes.
     *
     * @param $status
     */
    nodeSelectorWidget: function (args) {

      // Adding the autocomplete field
      var createField = function() {
        var input = document.createElement('input');

        input.classList.add('form-autocomplete');
        input.setAttribute('data-autocomplete-path', '/fr/autocomplete/custom');

        return input;
      }

      var container = document.createElement('div');
      container.className = 'nodeselector-widget';

      container.appendChild(createField());

      return container;

    }

  };

})(jQuery, Drupal, drupalSettings, Annotorious);

I precise the path /fr/autocomplete/insects return correctly a json list of content and autocomplete create in a usual form works correctly with it. Example of autocomplete I do in an usual drupal form with this custom autocomplete:
$element['test_autocomplete'] = [
     '#type' => 'textfield',
     '#title' => t('Autocomplete Articles'),
     '#autocomplete_route_name' => 'my_module.custom_autocomplete',
   ];

Thanks to Clive for his help ! To active the autocomplete, I should re-attach the autocomplete behavior after added my new element.
nodeSelectorWidget: function (args) {

      // Adding the autocomplete field
      var createField = function() {
        var input = document.createElement('input');

        input.classList.add('form-autocomplete');
        input.setAttribute('data-autocomplete-path', '/fr/autocomplete/custom');

        return input;
      }

      var container = document.createElement('div');
      container.className = 'nodeselector-widget';

      container.appendChild(createField());

      // Re-attach autocomplete behavior to active the autocomplete on the added input
      Drupal.behaviors.autocomplete.attach(container);

      return container;

    }