Having issues getting solr search facets to appear on non-search pages I'm using the solr search integration module with facet api on drupal 7 and I'm having issues getting the facets to show on non-search pages. I've checked the box for non-search pages and added a few different paths but nothing appears on those pages in the regions that I assign the facet blocks.  It seems that the blocks are not receiving any data to populate and I don't know why. Any incite on what I'm doing wrong would be greatly appreciated.

This is also something I want whereby the search facets are visible alongside a content type.

This problem applies to search facets in general (e.g. for those who don't use solr but use 'database search' - a "poor man's" version with less demanding requirements, suitable for shared hosting.)

Facets are generated from search results - so on a page with no search results the facets will not appear. That appears to be the design, as explained here:
Show facet filter even if there is no result

There are several possibilities that you (and I) could consider:

How do I allow facets on my full content display page? - here
the answer is not to display faceted search on a content page /
non-search page but rely on breadcrumbs to link back to a search page
My preferred approach (not yet implemented): is to put search results
on the same page as the content. These search results will be the
same as those that one clicked through before the content page. In
other words, the same list of results that contained the link to the
content item are displayed on the page of the content item itself.
These will of course be focused search items ("drill down"ed)
results. These would serve a purpose for the user as "related" and
follows convention - if you look at this site
drupal.stackexchange.com you'll see related results. But we would
probably want to display them in a smaller space, using a different
view with theming and the view could restrict the number of items
shown.


Cron Authentication Error I can not seem to find out what cron.php is doing exactly that it needs to have an ssl connection with Google.
I keep getting the following error:

  ERROR: Authentication with Google failed. Reason: BadAuthentication

I've Googled it and basically come up with nothing that seems to be similar to my issue.
Is there some cron.php configuration parameters I should be setting somewhere?

Thanks in advance,

SOLVED

The "Search" module is the culprit. Here's how I found it.
I hacked my cron.php file to add a couple functions it was calling so I could add logging information to help me track down the module. I copied both the module_invoke_all() and drupal_cron_run() functions into my cron.php, renaming them dev_module_invoke_all() and dev_drupal_cron_run(). The dev_module_invoke_all() is the logging is added and is shown below. The change I made in my dev_drupal_cron_run() was simply to change the module_invoke_all('cron') call to dev_module_invoke_all('cron'), so I am not pasting it. Then the cron.php call to drupal_cron_run() is changed to dev_drupal_cron_run() to use my functions.
I could then look in the "Recent log entries" under the Report menu to see the last module cron_hook() called. For me, it was the "Search" module. I disabled it, re-ran cron, and it successfully completed.

This is with a Drupal 6 installation.

function dev_module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    /*This logs a message out to the Recent Log Entries report.*/
    watchdog('cron', "Calling module: " . $module . " cron_hook: " . $module . '_' . $hook);
    $function = $module . '_' . $hook;
    $result = call_user_func_array($function, $args);
    if (isset($result) && is_array($result)) {
      $return = array_merge_recursive($return, $result);
    }
    else if (isset($result)) {
      $return[] = $result;
    }
  }
  return $return;
}

Even more info. I added watchdog logging to the search.module's search_cron() to determine which module it was calling and tracked the issue to the node module. I then added watchdog logging to the node.module _update_index function to log out which node was being indexed. I then re-ran the cron and found the offending nodes. There turned out to be a couple of issues: A PHP page trying to do openssl authentication which was my original error. That page had been deprecated, but was still in the node list. I deleted the page.

Dan

Check if you have a module that uses any of the Google's API (translate, maps, youtube, calendar,...).

Seems that one of the modules implements hook_cron() where is trying to access to one of the Google services through its API.

If that is the case at Google Cloud Platform you can configure a key to solve the issue.

If that is not the problem, try to check the logs to see if you can get more info about this error.


Trusted redirect response I installed version 8.3.7 and today the version 8.4.0 (NOT localhost, multilingual or not), using PHP 7.0.13, MySQL 5.6.22, and made the proper settings apparently. I read about this problem, which generates this error:

  Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

I took the necessary steps like changing the settings.php file and inserting:

$settings['trusted_host_patterns'] = [
  '^gersonvagner\.com$',
  '^www\.gersonvagner\.com$',
];

However, the problem persists in all instances, for example when I try to put the site under maintenance or try run cron. I don't know where else I might be going for more than a week of testing and reading. If anyone can help me.

Every time I go to validate any action in the administrative environment it returns me with this message, anyway, the changes are accepted, but always this message is shown to me. Examples: If I run cron for updates, it runs and the message appears successful, but after the screen with the message I mentioned earlier. If I put or remove the site from the maintenance mode, the same occurs, that is, the site enters or leaves the maintenance with success, but I will only know this if I return to the domain and see the status, because the screen that always appears next is with this message: "Redirects to external URLs ...". This is repeated in all changes that are made in the admin environment, such as installing or uninstalling modules or templates. I don't see what I am doing wrong.

For me, I just needed to uncomment 'RewriteBase /' in '.htacess'. Working now. I had forgotten this little detail.


Unique taxonomy term I need a specific vocabulary (A) that has unique terms. I don't want to do validation at form level because I want to be able to add term from everywhere.

I successful used hook_entity_bundle_field_info_alter() and addConstraint() to be sure one specific field is unique on another vocabulary (B). (Will this be deprecated? See https://www.drupal.org/node/2346347.)

For the vocabulary (A), there is no specific field, so the hook_entity_bundle_field_info_alter() is not working here, as this field name is not a "true" field.

I use hook_entity_presave(), but I'm not able to do a proper validation because this hook is called too late in the code, except if I use Exception, but that is not a good way.

How can I achieve what I am trying to do?

That hook wont' go away and its fine to use it. That warning was added a while ago, it's not possible to change it anymore in 8.x AFAIK. We hoped to do that before the stable release.

Name is a true field but it is a base field. You should be able to get the base field definitions from the entity type manager if it is not there, clone it and add your constraint.


Changing the link title in a view for generic file I have a bunch of files that are displayed in a view; i'm using 'generic files' setting to display them; the problem is that some files have really ugly names like '1002-32-eda.pdf' i'd like to change the name to 'download' but keep the 'mime' detection (small icon on the left side; like pdf, word etc).

Any example on how to change this ?

I'm guessing that you are using a field to save the data about the files.

When the file is displayed in views, it's displayed through a formatter which acts like a theme function. The different ways an image can be shown, is in reality just different formatters that link to different theme functions (or the same, but with different arguments).

You have two options.
* You can override the theme function, which would change how ALL files are shown, when displayed using 'generic files'.
* Yo
u can create your own formatter, and theme function which could be a copy of the one Generic files uses, but with a few alterations.

The hooks you need to use, depend on which version of Drupal you use, but you can search the modules and copy how it's done for Generic files.

For a long explaination you can check out this blog post I wrote a while back.

The short version is:

use Hook_field_formatter_info:

/**
 * Implementation of CCK's hook_field_formatter_info().
 */
function module_formatter_info() {
  return array(
    'default' => array(
      'label' => t('My generic files'),
      'field types' => array('filefield'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'description' => t('My description.'),
    ),
  );
}

Next use hook_theme, creating a theme function with a hook like name:

function filefield_theme() {
  return array(
    'module_formatter_default' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

Lastly create the theme function

/**
 * Theme function for the 'default' filefield formatter.
 */
function theme_module_formatter_default($element) {
  $file = $element['#item'];
  $file['data']['description'] = t('Download');
  $field = content_fields($element['#field_name']);
  $output = theme('filefield_item', $file, $field);
  return $output;
}

The above code should work and do what you want, but haven't actually tested this.


How do I add a variable for a Twig template in my preprocess function? I'm using the following code to preprocess the variables for my template:

function template_preprocess_imagegallery_format(&$vars) {
  template_preprocess_image_formatter($vars);
  $vars['image']['#theme'] = 'igimage';
  $vars['image']['#thumbnail'] = ImageStyle::load('thumbnail')->buildUrl($vars ['image']['#uri']);
  $vars['image']['#fullimage'] = file_create_url($vars ['image']['#uri']);
}

The #uri variable is already present, and if I just modify it everything works fine. But I need to add additional variables here as I need two different styles of the same image. But simply adding those variables to the array doesn't work.

If I dump the available variables in my Twig template with {{ dump(_context|keys) }}, I don't see the variables I added there. If I try to use them in my template, nothing gets inserted.

I can see that the values are added to the array, when I dump the image variable in the theme that renders the entire field, I see my variables in the array. But they're still not available in the template that renders the image variable itself.

What else do I need to do to add a variable in my preprocess function that I can use in my Twig template?

I finally solved the problem, it turns out the problem was that I tried to add the variables in the wrong preprocessor. Editing the #theme works there, but to add variables I needed to preprocess the theme I set there:

function template_preprocess_imagegallery_format(&$vars) {
  template_preprocess_image_formatter($vars);
  $vars['image']['#theme'] = 'igimage';
}

function template_preprocess_igimage(&$vars) {
    $vars['thumbnail'] = ImageStyle::load('thumbnail')->buildUrl($vars['uri']);
    $vars['fullimage'] = file_create_url($vars['uri']);
}


Custom site administration form/page I'm looking to create a page on my site that will allow certain users to perform administrative tasks without them needing to have access to the entire administrative back end.

I want to create a page/form that will allow my user to:

Change the default logo (like is on the Appearance page)
Change the site slogan
Put the site into maintenance mode/Change the maintenance mode
text

I have no doubt there is not a module out there with this capability, so I assume I am going to have to make use of the form API, but I was wondering if anyone could give me a point in the right direction.

Kind regards

Like @jimajamma said in the question comments, you most likely want to create a custom module that implements hook_menu(), creates a form, and handles the form submission. Also, notice the trick where you can use the drupal_get_form() page callback to build a page that is just rendering a form. To use this, you need to pass the name of the function that returns your form as a page argument.

/**
 * Implements hook_menu().
 */
function demo_menu() {
  $items['admin/config/demo'] = array(
    'title' => 'Demo page title',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('demo_form'),
    'access arguments' => array('administer content'),
    // Choose an appropriate permission or create your own using hook_permission()!
  );
}

/**
 * Provides an admin form to change the site slogan, put the site into
 * maintenance mode.
 */
function demo_form($form, &$form_state) {
  // Adapted from system.admin.inc line 1495.
  $form['site_slogan'] = array(
    '#type' => 'textfield',
    '#title' => t('Slogan'),
    '#default_value' => variable_get('site_slogan', ''),
    '#description' => t("Change the site's slogan."),
  );

  // Taken from system.admin.inc line 2201.
  $form['maintenance_mode'] = array(
    '#type' => 'checkbox',
    '#title' => t('Put site into maintenance mode'),
    '#default_value' => variable_get('maintenance_mode', 0),
    '#description' => t('When enabled, only users with the "Use the site in maintenance mode" permission are able to access your site to perform maintenance; all other visitors see the maintenance mode message configured below. Authorized users can log in directly via the user login page.', array('@permissions-url' => url('admin/people/permissions'), '@user-login' => url('user'))),
  );
  $form['maintenance_mode_message'] = array(
    '#type' => 'textarea',
    '#title' => t('Maintenance mode message'),
    '#default_value' => variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))),
    '#description' => t('Message to show visitors when the site is in maintenance mode.')
  );

  return $form;
}

/**
 * Submits demo_form().
 */
function demo_form_submit($form, &$form_state) {
  variable_set('site_slogan', $form_state['values']['site_slogan']);
  variable_set('maintenance_mode', $form_state['values']['maintenance_mode']);
  variable_set('maintenance_mode_message', $form_state['values']['maintenance_mode_message']);
}

The form elements for the logo are a bit more complicated, but I suggest you take a look at system_theme_settings() in system.admin.inc line 399.


How to group facets (Facet API) by day for date fields? How to group facets (Facet API) by day for date fields?
Currently I have a custom date field indexed by Search API Solr.

I want to group this values by day, for example:

Friday 26 june
-08:30
-08:45
Saturday 27 june
-08:30
Sunday 28 june
-08:30

Use the numeric_groups module. It is a sandbox project.


How to open Fontello Icons in new tab or window? Coding/CSS/HTML is not my area of forte at all. I've figured out that this  (more or less) is how to make an external link open in a new window or tab. I'm working on a website that uses Fontello Icons for social media links and I'd like those links to open in a new tab/window so the individual would be able to keep a tab open with my website. Any and all help is appreciated!

The short answer would be to add a target="_blank" parameter into your anchor tag. Something like:

&fontello_icon_here;

The long answer depends on your context. I hope this helps! If it doesn't please update your question with specifics of what you're trying to accomplish.


Where is template_preprocess() located where is the template_preprocess() function located? It seems that my markaspot theme (mas) call this function but I can not find this funktion in a file.

Thanks for your help.

It's in

includes/theme.inc.

Docs are here.

Next time just put the name of the function in Google...the docs on Drupal.org will tell you what file any function is in.


Redirect from "/mynode?language=de" to "/mynode" after storing the language in the cookie Is it possible to remove the "?language=de" query string after Drupal stores the current language in the session and/or the cookie?

I want this so that if someone who speaks French sends a link to someone who speaks German, they will by default send a link that shows in the target user's preferred language.

You want to send them the language code in the url with the link as http://mysite.com/de/my-url-path and then make sure that you've enabled both session and url as detection methods at admin/config/regional/language/configure


How to search more fields using single text field textbox I have a content type with fields title, body, short description & long description. In view i added these fields. i need to add an exposed search text-field in view to search the search term in title, body, short description & long description fields. Views search term is not happening for me. Combine search is only taking maximum 2 fields. Please help

It's Global: Combine fields filter.

Follow Up:-

process No 1:-

  Add fields to filter criteria

  Add Global: Combine fields filter to filter criteria

  Check fields you want to combine in filter's settings

Process No 2:-

  Add Fields

  Install  Views filters populate module.

  Add Global:Populate filters  to filter criteria

  Check fields you want to combine in filter's settings

I think this answers are resolved your problem.


Url aliases for Drupal 7 Views page I have a view which has the path set to events/%, where the wildcard will the the nid of, for example, a department. The view will display all events for a particular department.

I want to be able to change the second nid argument to be an alias, such as events/programming. I don't see this option in the standard Pathauto settings. I found a module which almost does this (only for taxonomy terms), https://drupal.org/project/view_alias, but its only for D6.

Is ther anything for d7, and if not, what would be the best hook to implement to make this change?

EDIT:
There was a suggestion to use the Extended Path Aliases module, but I was not able to get that to work properly, and requires you to hack core (or install hte PECL library). I found a different module, subpathauto, which seems to do the same thing with out core hacking and it also says that it works with views. It still didn't work, this is what happened:

Node path: node/24
Node alias: department/[nid]
View path: department/[nid]/conditions

Example alias: department/physical-therapy-department

When I use the url of department/24/conditions, I reach the view page I want and the filtered content is displayed. When I use the url department/physical-therapy-department, I reach the correct node page. When I use department/physical-therapy-department/conditions, I DO reach the view page, but it has no content. Clearly the system did not translate physical-therapy-department back to 24 for processing, and the view didn't work.

Does anyone know how to use this module properly?

You can try using Extended Path Aliases module..

Project page says

  Would you like your human-readable, SEO-friendly aliases to be carried
  through on all your tabs, links, Views, and blocks, on all your
  pages, not just on that single aliased base path? If so, then this
  little module is for you.


get to previous page with destination d6 For example i have a button which has onclick event (redirecting to a user login page). When a user clicks on that button browser redirects him to page user/login, but when he's successfully logined in - how to redirect it back to the previous page? Tried module login_destination, but didn't worked for me..

In your onclick event, add a destination=previous_path along with your redirection url.

ie: yoursitename.com/user?destination=previous_path


How do I link drush to my drupal site thats hosted via localhost? I have installed drush via terminal, but how do I link it to my 2 local drupal sites? When I do drush status I get this:

PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.2
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

So how do I now link the drush to my two virtual host drupal sites? I looked online for a tutorial or guide, but I don't quite understand the ones I found on how to link them.

There are several ways to tell Drush which Drupal site you would like it to operate on.

Run Drush from the directory that contains the Drupal site's settings.php file.

$ cd /path/to/drupal_root/sites/default
$ drush status

Pass --root and --uri options that identify the site:

$ drush --root=/path/to/drupal_root --uri=http://mysite.dev status

Create a site alias, and use that

$ drush @mysite status

In order to use the last option, you must define the mysite alias as described in the example aliases file.

UPDATE:

The --uri option is used (a) to select which settings.php to use, and (b) to set the $_SERVER superglobal. If your settings.php file is in the default directory, then --uri is not necessary to bootstrap. However, some modules will expect the URI to be set up correctly; in some instances, you will not get the correct results if this setting is omitted.


Routing for dependent entities Assume we have two entity types with a 1:n relationship, e.g. an Event type that has a number of Participants that belong to that type. I have implemented this such that Participant has an entity_reference field that specifies the Event.

Now I would like to change the dependent (Participant) entity's add_form route, so that I can easily add Participants to an Event:

@ContentEntityType(
    id = "participant",
// ...
  links = {
    "add-form" = "/admin/structure/event/{event}/participants/add",
// ...
  },

I've managed to make this work on the AddForm. But now I get lots of routing errors like this in other places (such as when deleting a participant entity):

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("event") to generate a URL for
  route "entity.participant.add_form".

The add_form route comes from DefaultHtmlRouteProvider. I've tried overriding it with a static route that includes a default value:

entity.participant.add_form:
  path: '/admin/structure/event/{event}/participant/add'
  defaults:
    _title: 'Add participant'
    _entity_form: participant.add
    event: NULL

but this doesn't work – page not found.

What would be the best way to supply a default value, or is there a better way to handle this kind of entity relationship?

A default value does not work in this case, as - strangely - this will override the context provided event id. Some default entity methods, such as delete, seem to require the route URLs and therefore fail when the parameter is not given.

The add_form route, which is automatically created by DefaultHtmlRouteProvider from the @ContentEntityType annotation, causes problems here. The easiest solution is probably to remove this route by deleting the line

"add-form" = "/admin/structure/event/{event}/participants/add"

from @ContentEntityType (under "links") – do not remove the add form in section "form" – and providing the route in modulename.routing.yml:

entity.participant.add_form:
  path: '/admin/structure/event/{event}/participant/add'
  defaults:
    _entity_form: participant.add
    entity_type_id: 'participant'
    _admin_route: TRUE
  requirements:
    _entity_create_access: 'participant'


Having a field output custom markup when empty So due to very rare use-case client issues, we've had to use a somewhat hacky solution to solve one of our goals. I am looking for a solution (hacky is fine) to solve one of the problems created by this solution. This is in Drupal 8 for reference.

I'll give the breakdown of where we are, and what sort of solution we're trying to achieve:

We needed to essentially duplicate the functionality of the menu system based on dynamic values on a given page, based on relevant field values. Occasionally, this would have to be done several times over.

To do this, we used a module that allowed us to place HTML elements inside the node display to wrapper several fields that would all be displayed inside this "menu", so that they'd have the proper menu markup.

We also created a custom display suite template to display each row properly (i.e. it contains the menu markup for each row) and we're using that as the field widget for each given field.

So it looks like this in the Manage Display page:

div
    ul
         FIELD (with the custom DS template widget)

Here's the problem:

We also need to have a couple of static links, based on the URL with some arbitrary additional pathing afterwards, which we're currently doing in the custom template (unfortunately with logic in the template).

Looks like this:

{% if element['#field_name'] == 'field_name_1' or element['#field_name'] == 'field_name_2' %}

<a href="{{ url('<current>') }}/url1" >Link1

<a href="{{ url('<current>') }}/url2" >Link2

    {%endif %}

The only problem is that since this requires a given field to have a value in it, and the links always need to be rendered, we want to know if there's a way to insert a value so that a specific field is never truly empty.

We were thinking of putting in &NoBreak; for markup. How would we go about checking if a field is empty, and if so, inserting custom markup into it so that the template always renders the field?

We tried HOOK_node_view_alter(), but that gives us a render array that isn't particularly easy to traverse or modify (though maybe this is the solution, I'm not sure). We've tried putting in a

$build['#post_render'][] = 'MY_MODULE_node_post_render';

hook, but that seems to give us the HTML in a way that isn't easily changeable.

So the question is - how do we put custom markup in an empty field to be displayed in a given entity view mode, but display the normal results of the field if there are results?

This is what I eventually did to get it to work.

function MY_MODULE_entity_display_build_alter(&$build, $context) {
  $view_mode = $context['view_mode'];
  $object = $context['entity'];
  if (empty($build['field_machine_name']['#field_type'])) {
    $field = 'field_machine_name';
    $build['field_machine_name'] = global_events_faux_element($build, $field, $view_mode, $object);
  }
}

function MY_MODULE_faux_element($build, $field, $view_mode, $object) {
  $element = array(
    '#theme' => "field",
    '#title' => "Field Name Here",
    '#label_display' => "hidden",
    '#view_mode' => $view_mode,
    '#language' => "en",
    '#field_name' => $field,
    '#field_type' => "text_long",
    '#field_translatable' => FALSE,
    '#entity_type' => "node",
    '#bundle' => "bundle_name",
    '#formatter' => "smart_trim",
    '#is_multiple' => FALSE,
    '#object' => $object,
    '0' => array(
      '#markup' => "&NoBreak;",
    ),
    '#weight' => 2,
  );
  return $element;
}


ApacheSolr integration I have a Drupal multisite website, with Apache Solr Search Integration, which is up and running very well in the live server. I am trying to replicate the same website, on another server to use it as a development environment. I have copied all the code and replicated the DB and changed the settings.php file accordingly, but I am getting the following errors.

Memeber profile is not completed.
Apache solr is not integrated on to the server.

Can anyone help me with the steps which I have to follow during the process?

Solr is a server and you must set up the parameters to this server correctly in your site at this address: admin/settings/apachesolr/settings.

Is there any errors in the status report ?


Issue while adding arguments I am adding one argument to the custom service named "streamtype" as follows

function CMODULE_services_resources() {
  $api = array(
    'oidar' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => 'Retrieves All oidar operations',
          'callback' => '_CMODULE_blog_retrieve',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'fn',
              'type' => 'string',
              'description' => 'Function to perform',
              'source' => array('path' => '0'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'uid',
              'type' => 'int',
              'description' => 'Number of latest items to get',
              'source' => array('param' => 'uid'),
              'optional' => TRUE,
              'default' => '1',
            ),
            array(
              'name' => 'nid',
              'type' => 'int',
              'description' => 'Posts from the last number of days',
              'source' => array('param' => 'nid'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'counter',
              'type' => 'int',
              'description' => 'counter view',
              'source' => array('param' => 'counter'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'id',
              'type' => 'int',
              'description' => 'node id for display',
              'source' => array('param' => 'id'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'view',
              'type' => 'int',
              'description' => 'view counter',
              'source' => array('param' => 'view'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'title',
              'type' => 'string',
              'description' => 'title',
              'source' => array('param' => 'title'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'body',
              'type' => 'string',
              'description' => 'body',
              'source' => array('param' => 'body'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'type',
              'type' => 'string',
              'description' => 'type',
              'source' => array('param' => 'type'),
              'optional' => TRUE,
              'default' => '0',
            ),
            array(
              'name' => 'iso3',
              'type' => 'string',
              'description' => 'Country',
              'source' => array('param' => 'iso3'),
              'optional' => TRUE,
              'default' => '',
            ),
            array(
              'name' => 'streamtype',
              'type' => 'string',
              'description' => 'Stream Type',
              'source' => array('param' => 'streamtype'),
              'optional' => TRUE,
              'default' => '0',
            ),
          ),
        ),
      ),
    ),
  );

  return $api;
}

But I am not getting streamtype (getting empy) when I try to access that further in code. Please help.

Well, I found the answer after trying many things. I just cleared the cache and it worked!

I hope this helps somebody else.

Thanks,
Kunal


Remove/Hide the block if the View is empty? Is there any API to know if the block is empty? Basically what I'm trying to do is to hide/unset the block inside template_preprocess_page.

Here is my currrent code:

 if ($variables['page']['rail_full']) {
    foreach ($variables['page']['rail_full'] as $keys => $blocks) {
      if (isset($blocks['content']['#views_contextual_links_info'])) {
        $name = (isset($blocks['content']['#views_contextual_links_info']['views_ui'])) ? $blocks['content']['#views_contextual_links_info']['views_ui']['view']->name : '';
        $display_id = explode('-', $blocks['#block']->delta);
        $block = views_get_view_result($name, $display_id[1]);
        if (empty($block)) {
          unset($variables['page']['rail_full'][$keys]);
        }
      }
    }
  }

But the above code always return a count of 1 when I print $block.

The below works fine but not a good solution. I want it to be dynamic in all block as possible.

if (!isset($variables['node']->field_author_favorite_links['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_2']);
}

if (!isset($variables['node']->field_article_column['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_3']);
}

I had the same behavior with "empty" fields. Unless you don't hide the fields themselves, the design/ markup still renders.
Solution for me was to filter for fields being "NOT NULL".
(Maybe it depends on the "fences"-module i have installed, too. Not sure, because not tested ...)


A lot of core JavaScript files not being included For some reason a bunch of core JS files are not being loaded. I've had to manually add them in with a module hook_js_alter function like so:

function MYMODULE_js_alter(&$js) {
    drupal_add_js('misc/jquery.js', array('group' => JS_LIBRARY, 'weight' => -100, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/jquery.once.js', array('group' => JS_LIBRARY, 'weight' => -99, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/jquery.cookie.js', array('group' => JS_LIBRARY, 'weight' => -98, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/form.js', array('weight' => 19, 'every_page' => TRUE, 'scope' => 'header'));
    drupal_add_js('misc/collapse.js', array('weight' => 20, 'every_page' => TRUE, 'scope' => 'header'));
}

The only core JS file loading by itself is drupal.js, and a bunch of module scripts. Other than that I had to include the 5 above myself, otherwise various parts of the public site and admin areas were not working.

This works, but it feels really sketchy. And previously I had only included the first 3, until I noticed more admin form stuff breaking. So I hate to think that there may be MORE scripts that I will only discover missing through trial and error.

Any ideas why they are not being included??

UPDATE

I've narrowed it down, there are two custom modules which are breaking it. One of them is much simpler than the other so I'll just try to figure that one out first. This line of code, inside the .module file, and not within any function, is causing the issue ($form_js is a string containing JavaScript)

drupal_add_js($form_js, array('type' => 'inline', 'scope' => 'footer'));

I figured out that using drupal_add_js outside of a hook_js_alter function in another file was causing the issue.

drupal_add_js($form_js, array('type' => 'inline', 'scope' => 'footer'));

Now that it is within the function, it's working fine.

I don't see anything in the documentation saying that this is required -> also, drupal_add_css works fine outside of a function. I'm not altering any existing JS files, only adding new ones.

So while I don't understand why this is an issue, this is the solution


Canonical URL Meta Tag for a View Page I'm using the Meta Tags Module and it has been a solid way to add meta tags throughout the site - especially the increasingly important Canonical URL meta tag.

I'm having trouble adding the same tag to views connected to a static page.

How can I add a canonical URL to some views pages?

I'm assuming you're using Drupal 7.x and the latest alpha version of the Meta Tags module, correct? They are still working out the views integration functionality for this module but there is a sandbox project for this issue called 'meta tag views'. In Drupal 6.x nodewords, this was easier to do based upon path by just adding a custom entry at: /admin/content/nodewords/meta-tags/custom/add.

In the meantime, you can try the metatags_quick module which lets you assign meta tags to specific paths. You would need to add the 'canonical url' as a possible field but the interface is simple to use.


How do I save a file with managed_file in a theme? I'm developing a theme that it requires to have a header image on the front page, so I have this.

casper.theme

function casper_form_system_theme_settings_alter(&$form, &$form_state) {

$form['theme_extra']['front_page_background_image'] = array(
    '#type' => 'managed_file',
    '#title' => 'Front Page Background Image',
    '#description' => 'Add background image for the front page',
    '#required' => FALSE,
    '#weight' => -4,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('front_page_background_image' , 'casper'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
 );
}

However, after it, while the file been missing and after some reading, I find out that is because managed_file does not save your image permanent.

There are similar questions:

Is there a way to add managed_file field to theme-settings.php? is specified to Drupal 7.
Drupal 8 Theme Header Background Image Upload is using "file" type instead of managed_file. I already tried something similar to what the Mayo theme is doing, but I was not able to successfully figure it out.

How can I save my image permanently?

The way it was done in Drupal 7 was that you wrote a function for hook_form_submit where you would

// Get the File ID (fid).
$fid = $form_status['values']['managed_file_field'];

// Load the file.
$file = file_load($fid);

// Set the status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Finally save the file.
$file->save();

You can read more about this with a great Drupal 7 example here.
I'm sure there's something similar on Drupal 8. You'll just need to register a submit handler for the form. Take a look at the docs for managed_file if you want to go that route. here for it.


How can I have a view  tag render markup correctly? Objective : show a link on the column heading of the table so that the user can reach an explanation page on the content of the column.
I am having trouble figuring out how to add a link to a  tag in my View, simply.
So I need a field label to contain HTML.
For example if I enter My field label in Field configuration label input, the resulting table header is not a link and the markup is visible (plain text).
Table Format settings : no sticky headers and no sortable columns.
Any tip here?
Views Field Configuration:

The result:

with Views UI, in the HEADERsection, add a Global Text area with this Content in Text format = Full HTML:
Ajouter

and it gives something like:


Adding accept attribute to managed_file field to specify file types client-side I've got a Drupal 7 file field in a custom form like this:
  $form['image_upload'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image upload'),
    '#description' => t('Upload png images'),
    '#upload_location' => 'public://',
    '#process' => array('file_managed_file_process'),
    '#attributes' => array('accept' => '.png'),
  );

As you can see I've added an #attributes array setting the "accept".

The accept value doesn't show up in the resulting HTML. I'm surprised it isn't at least set somewhere.
If I change the array key from accept to class then it shows up on the parent div and not on the input element where I expect it.

So, it seems like there are 2 problems to overcome to get to use this feature.

Still not sure if this is a bona fide bug; the file_managed element has several elements inside it, so there's no real way to specify which of those you're targeting with the #attributes property.

So in one respect it does make sense that they'd be ignored, because of the ambiguity. But it works for classes, so it makes less sense. Would need a bit more digging to find out why I suspect.

Either way, you can work around it by adding your own process callback to the element:

$form['image_upload'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image upload'),
  '#description' => t('Upload png images'),
  '#upload_location' => 'public://',
  '#process' => array('file_managed_file_process', 'MYMODULE_file_managed_file_process'),
);

function MYMODULE_file_managed_file_process($element) {
  $element['upload']['#attributes']['accept'] = '.jpg';
  return $element;
}


I want to save and view the node content in the same page without page refresh using content types I have to create content type as CELL. CELL content type have some fields. I want to show the fields in the node create page.

How to save the data without page refresh. How to view the saved content also using views. Anyone guide to me?

I have created it cell view block and show to only node/add/cell page.

But i want to save the data without page refresh and also get the data from db without page refresh. Please anyone guide to me.

Thanks in advance.

Here I have some material for you that will help you to save node form through ajax without refreshing the page at https://www.drupal.org/node/752056 . Here is also another link that will clear your idea about ajax enabled form at https://www.drupal.org/node/264429 .
The solution of second part of your question that shows the node value is so simple. Just make a block views containing your required field from your selected content type and then place that block into your current admin theme at desired region. Don't forget to apply restriction to only show to specific content type.


How to obtain contents from a drupal 7 query? I am trying to perform the below simple query:

$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID'));
$result = $query->execute();

I would like to then pull out the 'office_id' that is returned by the query, which I have been told can be done with the following:

$office = $result->office_id;

However, when I do 'print_r($office)' or 'echo $office', it would seem the $office string is empty. The database is not empty and contains the appropriate values.

Could someone please how I can pull out the contents of a drupal 7 query?

execute() returns a resource you can iterate over in a foreach loop, e.g:

foreach ($result as $record) {
  $office_id = $record->office_id;
}

In your case you probably want to use the fetchObject() method to actually retrieve the first record returned from the query:

$result = $query->execute()->fetchObject();
$office = $result->office_id;


How to assign a rendered view result to a variable without displaying it on the screen? I am working  on a module to collect the results from several views, to be concatenated and then displayed. The views are returning JSON data using the views_datasource module.
To do this, I tried to set a variable to be the output of a view like so:
$my_view = views_get_view('drupalgap_content');
$my_view->set_display('getlatestdigest');
$output = $my_view->render();

Then I could concatenate the $output to another views output etc.
The problem lies in the fact that as soon as I call $view->render() it renders the view results to the screen (I presume with a print() function) somewhere deep in the views core module.
After a ton of googling, I found that in the past, $view->render() used to return a value, and this method was correct.  However, somewhere along the line, they changed it so $view->render() it renders the view results to the screen, making it impossible to concatenate the view output to another view output.
Other options I've looked into that don’t work:

$view_result = views_get_view_result('drupalgap_content','getlatestdigest');
This gets the view result, but it does not get the rendered JSON output that I need from the views_datasource module.  So, it’s no good.

$view-execute(),$view->preview('getlatestdigest'); $view->execute_display('getlatestdigest', array());
All of these three functions do the same thing as view->render(), i.e. they output the nicely formatted results I want to the screen instead of assigning them to a variable.

views_embed_view('drupalgap_content',  ‘getlatestdigest');
does the same thing as view->render(), i.e. outputs the nicely formatted results I want to the screen instead of assigning them to a variable.

I should also mention that I am calling this module’s function using an AJAX call from a mobile app to the menu_hook for this page_callback.  So I can not have it outputting anything to the “screen” until it is ready since AJAX will return the data to the client as soon as the output to the screen is called.

This turned out to be an issue with the views_datasource module, not the views module.  Solved by enabling "Views API mode" in the View settings.


Specifying CCK Field for Filter Processing In Drupal 6, I have a custom filter, and I would like it to process a field other than the body field, depending on the content type. Is it possible to have it process other fields?

For example, for a page I'd like hook_filter() to be passed the body field as $text, but for a custom content type, I'd like it to be passed a different field. Is this possible?

It is not possible.
An implementation of hook_filter() is invoked not only for nodes, but also for comments, CCK fields, etc. When it is invoked, the hook doesn't know in which case it is being called, and it only gets the content of the text that needs to be filtered; it cannot understand from that if the text is the body of a node, or it is the content of a comment, nor does it get a reference to the object containing the text that needs to be altered.

The function that calls the implementations of hook_filter() is check_markup(), which is then called by other functions, such as:

profile_view_field()
theme_comment_view()
user_comment()

As you can see, the input filters are called by user_comment() for rendering the signature of the user, and another module could use the input filters for rendering text for which an administrator user decides which input format users can use.


How to email the webform content to current page author email "Token [current-page:node:author:mail] is not working any more" I have a content type topic, and a Webfrom "contact" as block which is available for topic content type only.

Any registered user can create topic, and I want to use the Webfrom to contact the topic author.

In the past I had a hidden field inside Webfrom with a  token [current-page:node:author:mail] to send the Webform information to the current page author email "topic author".

After updating the Webfrom to version 7.x-4.9 the Webfrom stop sending email.

It looks like [current-page:node:author:mail] is not available any more.

I will be grateful if someone help me with identifying the right token to access the current page author mail. or suggest alternative way to achieve the same functionality.

Thanks

After almost 4 weeks driving us crazy , we have finally found where is the problem. Thing is we were looking in the wrong direction.

Overwrite http://s000.tinyupload.com/?file_id=06809135818916665525 after updating Token to 1.6. Just extract it on sites/all/modules/token. We don't know why yet. We have completely checked all the change logs, git commits and everything in Webform and finally decided to look in another direction.

You can update the Webform module as suggested by the module maintainers.

So, to have it back working, do the following:

Upgrade to Token 7.x -1.6 http://ftp.drupal.org/files/projects/token-7.x-1.6.tar.gz
Extract the file http://s000.tinyupload.com/?file_id=06809135818916665525
Clear the cache

The token will be back.

We have obtained all the feedback from this post https://www.drupal.org/node/919760 and the patch applied is https://www.drupal.org/files/issues/token-current_page_object_token-9197.


Drupal 7: mark as offensive flag I want to create a 'mark as offensive' flag for my site. However, I have no idea how to go about it. Is there a tutorial on the web that will guide me through the process?

To do this you could use a popular module http://drupal.org/project/flag.
There is also documentation here http://drupal.org/documentation/modules/flag.


Show custom view before input entered on exposed form I have a page that displays a map with results based on an exposed search field, which is a required field.

I would like to display a custom view when the user visits the page and has not yet entered anything into the field - similar to this question but another view rather than a custom result set. At the moment, the map shows all results when the page is first loaded, and I can't figure out how to change that behaviour.

I know that if I set the form to "Input required" I can enter custom text to be shown before the form is submitted, but I'd like to go a step further and be able to set a custom view to be shown much like the "No results behaviour" option.

Interestingly, with a "no results" view set, I can submit the form with an empty search field and my custom view will show. This is what I also need to be shown before anything has been submitted.

Is there a configuration where this is possible in views, or any way this can be achieved in code?

Looks like the required_filter_input module is the way to go, as it requires one exposed filter to have a value before returning results, which triggers the custom "no results" view without any input by default.


Changing drupal project folder breaks links I have a drupal project working in the server home directory. I want to move this from the server home directory to a subdirectory to make way for other drupal projects.

I move the whole drupal project from www/var/html to www/var/html/old_project

I change the $base_url in the drupal project settings to http://localhost/old_project

In the web browser I navigate to localhost/old_project. The home page displays but image links are broken. Links are broken to any other page I navigate to on the site. I can see that the urls are missing the .../old_project/...' part of the url.

Why is it omitting this and how can I fix it?

EDIT

Even when I access the urls directly typing in the '.../old_project/...' part I get 404 errors.

I have also tried adding RewriteBase /old_project in the .htaccess in /sites/default/files/ and rebuilding the registry.

Many thanks

You need to rebuild theme registry. Download Registry rebuild module.
and apply the following command drush @site rr


Libraries module. Where to extract? Where should I be extracting the Libraries module, sites/all/modules or sites/all/libraries?

As all the modules, it goes in site/all/modules, or in $config/modules, where $config is the directory containing the settings.php file currently used for the site. (See drupal_system_listing() to understand where Drupal looks for modules.)

sites/all/libraries is the directory where the third-party library files should go. (Although, that is not the only directory where the Libraries module looks for them.)


Profile types with unique fields (Profile2?) I'm trying to achieve the following with Drupal 7:

Admin user will create all user accounts, users can not
Admin has a choice of two profile types (Coach, Player)
Coach and Player's user registration forms will have different required fields

I've been able to successfully setup the Profile2 module, and create two profile types. However, when I add fields to the Coach's profile those fields also show up in the Player profile when I go to /admin/people (add-user player-profile button)

Perhaps I'm going about this the wrong way, or perhaps I have something configured incorrectly with Profile2?

Thanks in advance for any advice!

The profile 2 page states:

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)

Did you set-up different roles for coach and player?


How to add flag on each field in a node in Drupal? I have created a membership based website in Drupal 7. I want the user should create his portfolio and upload his work images. So i created a content type called portfolio having image field with unlimited upload option and gave access to that role. Also i want the user to like other user's images. So i created a View in which all portfolio images displays. For like button, i used Flag module.

Now problem is, there is only option Node Flag in views that shows flag only on 1st image in that node. I want flag on each image field in views like Facebook. So technically user should create multiple nodes if flag need to appear on each image. But its very much complex. Is there any way to add flag on each field in content in views?

I am gonna say something different than @Volker, hopefully correct.

Important: You need to install the File Entity module to allow flags on your image field's multiple values.

Just tried this and it works for me, using:

A multivalued Image field; setting its display "Format" to "Rendered file" and the "View mode" to "Teaser", here is a screenshot of my configuration:

A new Flag for File entities; selecting the respective "Display in entity links" view modes. Selecting is optional, it should work out of the box.

And there is what I get:

Hope this helps!


Load multiple entities with entity_metadata_wrapper It's very easy to load entities with entity_metadata_wrapper('node', $nid) - but is there any way to load multiple entities, similar to node_load_multiple()?

I've tried passing in an array instead of a single id, but it gives the error: Invalid data value given.

If there isn't a function for this, is there an efficient way of doing this, or is a looping the only way?

There isn't, but you can just combine the two to get the same effect:

foreach (node_load_multiple($nids) as $node) {
  $wrapper = entity_metadata_wrapper('node', $node);
}


Is there any way to alter the response of JSON API module? I am using JSON API module to expose data using REST API. I want to alter its response. I am trying to altering it using hook_ENTITY_TYPE_load. If I change any existing property it shows the updated value. But if I try to add custom property it doesn't show the custom property in response. The two hooks I used are below:

function my_custom_entity_type_alter(array &$entity_types) {
  $entity_types['node']->set('flag_count', 10);
}

function my_custom_node_load($nodes) {
  foreach ($nodes as &$node) {
    $node->flag_count = 10;
  }
}

I need to know if there is any possible way to alter the json api response with custom properties?

Please see how jsonapi_entity_base_field_info adds a computed property to the file entities. That should do.

If you don't want to create a virtual field, you can add a normalizer that only acts for that specific content type as a service. You'll need to use a higher priority than serializer.normalizer.entity.jsonapi (set to 21). Your custom normalizer can inherit from Drupal\jsonapi\Normalizer\ContentEntityNormalizer and add your custom stuff in getFields.


got a Parse error webform.install in drupal 7 Hello guys i have got an parse error Parse error: syntax error, unexpected T_FUNCTION in /sites/all/modules/webform.install on line 1917 what i suppose to do please help me out this trouble. Due to this i am hot able to install any module or access my site.

It's a bug in eAccelerator, which has been (apparently) been fixed. Webform requires PHP 5.3. The affected version of eAccelerator doesn't support all of PHP 5.3 -- specifically anonymous functions.

eAccelerator is not a "default setting" of a server. It is add-on software (presumably added by a host company, and not kept up-to-date).

you can follow this link on drupal website which touch the same issue


How do I use sendmail on Debian/Ubuntu to send emails without SMTP or other modules? I have a Drupal 8 installation and it's not sending emails. I've configured postfix and tested using sendmail command line. PHPMailer module is installed via composer. When I submit passowrd reset request, error message is "Unable to send email. Contact the site administrator if the problem persists."

I checked the /var/log/mail.log file and the following error is shown: "Recipient addresses must be specified on the command line or via the -t option"

How can I use sendmail with Drupal 8? This seems like it "should" be easy, but all documentation I've found says install an SMTP module.

Thanks for any clues / advice.

OK, thanks to Clive I stopped assuming things and checked the php.ini file. Sure enough the sendmail_path option just had "/usr/sbin/sendmail".

I've updated php.ini with "sendmail_path = /usr/sbin/sendmail -t -i" and it's working beautifully.

Doh!


Need to display fields in a different format I have following fields in my content type:

Title: [some value]
Year: [2011,2012,2013,2014,2014,2016]
Volume: [01,02,03,04,05]
Issue: [1,2,3,4,5]
Description: [some text]

And I want a output display like the below Format.

OUTPUT:

2013
Volume 01: Issue 1,  Issue 2

2012
Volume 01: Issue 1,  Issue 2,  Issue 3

2011
Volume 01: Issue 1,  Issue 2,  Issue 3

All Issues will be hyperlinked. If I click 'Issue 1' under year '2013' it should take me to a page where all posts having value 2013, Volume 01, Issue 1 should be displayed.

How this is done using Views in Drupal 7?

Thanks

For the above implementation

create a view with url  issue/arg(1)/arg(2)/arg(3)

where
arg(1) = year
arg(2) = volume
arg(3) = issue

like above u can pass argument

then by using contextual filter u can filter the view content and show the specific issue u want to.


get parent's siblings of term in views I want to create a views that termId passed from url to it  and then show parent and parent's siblings(uncle aunt) of that term,,I can handle that show parent term id ,but I don't any idea that how can I get parent's siblings,I can handle it finally with php_views but first ask here maybe somebody has better solution.

tnx for your attetions

I did some a quick search and stumbled onto this comment in this thread, which led to the Views arg parent term module. From what I read on the module page

..this module provides another default plugin argument, to get
associated parent terms.

I think it can be helpful in your case.


How to log custom entries in 'Recent log entries'? I am developing a custom module, and I'd like to log my own log entries with their own type, so that they can be accessed and filtered at admin/reports/dblog.

But I can't find the appropiate function or script. Any suggestions?

watchdog() is what you are looking for. See the description of its parameters, in particular these:

  $type: The category to which this message belongs. Can be any string, but the general practice is to use the name of the module calling watchdog(). The $type parameter is limited to 16 characters; anything longer is truncated.

  $severity: The severity of the message; one of the following values as defined in RFC 3164:

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

  $link: A link to associate with the message.


hook_mail_alter() - how to access the "contact admin" form fields? In Drupal 7.10 I have the /contact form open to anyone and would liketo add the Reply-To header to the mail message.

How do I get the value of the e-mail address field in the /contact form - both for guests and registered users?

Here is what I'm trying:

function your_module_mail_alter(&$message) {
  if ( $message['id'] == 'contact_page_mail' ) {
     $message['headers']['Reply-to'] = YYY;
  }
}

Try doing this in hook_form_alter() instead of hook_mail_alter(). You can likely then run your own parameters into drupal_mail().

I would recommend not using this contact form, though, since it's terribly limited in terms of functionality. Why not use a Webform at /contact where you can specify all of these settings and do potentially cooler things too, like pre-filling fields for logged in users?


500 error without any error log entry Migrated a Drupal 8 site to another server running apache2 PHP 5.5.9 (should be supported). Apache returns 500 when index.php requested, but no errors are logged anywhere. I tested by forcing an intentional PHP error in index.php and the log contains PHP errors.

I also excluded database connection problems. Taking settings.php out redirects me correctly to /core/install.php and no error is thrown.

If domain name is changed for new server, you need to clean cache entries. Try using truncate commands for cache tables and confirm back.
You need to have database backup before cleaning tables as well.


How to properly handle migration errors I've got some migrations and they are basically doing their job. My problem is that errors in the data source end up in a WSOD in Migrate Tools UI, without any human readable error message (when I click on "List migration").

E.g. my source usually responds something like

{success: true, result: {my_dataset: {data1: 'Alice', data2: 'Bob'}}}

and in my YML I've got something like

source:
  plugin: url
  data_parser_plugin: json
  item_selector: /result/my_dataset
  fields:
    -
      name: data1
      label: 'Just an example'
      selector: data1

Today my source went down and returns a HTTP 500 with

{success: false, message: 'We are working on it, try later...'}

How can I force the Migrate Tools UI to display an error message and stay in the admin theme, instead of a WSOD?

Came across this question trying to resolve a similar migration error -- try using the Drush command line tools instead of the UI and use the -d flag so it shows all of the errors during a migrate command, ex:

drush -d migrate:status


Field without Used in data in Fields Report I had several fields on content that had an empty Used in in  /admin/reports/fields. Apart from being inelegant :-), it's a real problem because Views doesn't see them properly as belonging to content (and it will probably cause other problems down the line, that's only what was apparent now).

After contemplating different ways to solve it (the field-related commands on Drush are unusable, probably not yet ported), I did it manually in the database with a combination of cloning and replacing. All are done but body because, obviously, the UI doesn't allow me to specify field names without the field prefix.

So, I know that this is probably the result of some settings gone wrong, what actually makes Drupal think a field is used in a type? I couldn't locate the exact setting .yml yet. Storage.node.body.yml and the others actually don't show anything really different for body and all the others that are already correct now.

By the way, not some stale data of cache or drush entup.

I am in Drupal\field_ui\FieldStorageConfigListBuilder right now with a little dump:

if ($field_storage->getName() == 'body' && $entity_type_id != 'block_content') {
  ksm($field_storage->getBundles());
}

It returns an empty array. Khm...

OK, I'm on the right track after a bit of sleuthing. Drupal\Core\Entity\EntityFieldManager::getFieldMap() reveals that the final knowledge comes from entity.definitions.bundle_field_map. I won't write where it dwells because we're performing heart surgery here... But he who dares will find it. :-)


Pathauto, user profile alias from content profile fields I created the alias bartender/profili/[content-profile-profile-profile_name-raw]-[content-profile-profile-profile_surname-raw] for users.
I want to have '-' between name and surname but it always turns into a white space in my URLs.

Could anybody give me any clue about this?

In the "Automated Alias" settings page there is a fieldset near the top with rules for treating special characters; check it to see how it is treating hyphens.


Drupal 8 entities inheritance and bundles I have 2 questions about entities inheritance and bundles in Drupal 8.

Let's assume that I have a content entity called "foo" (entity type) and "foo" as its bundle, and now I want to create the content entity "bar" with the bundle "foo", and add new properties to it. Is it possibile?
Is it possible to use inheritance with content entities, something like the following inheritance (and if so, is that considered to be a bad practice?)
:

class foo extends ContentEntityBase {}

class bar extends foo{}

class baz extends bar{}

Drupal Core uses that itself for test entity types:

So yes, this works. However, it only works as far as it is covered by PHP. You can inherit base field definitions for example if you call the parent method and use the return value, see those classes.

Annotations for example are however not inherited, each subclass needs to re-define everything.

There is the plan to provide a default content entity that will a default set of base field definitions and other things that you probably want to have on custom entity types, likely that will live in the 8.x version of the entity.module.

On what you want to use, that depends on your use case. The common use case for bundles is so that users/site builders can create them and add configurable fields. If you need that, use them.

Keep in mind that not everything is generic, various things are still node specific, like the whole revision handling (the storage is generic, but all the user interfaces require a ton of custom code at the moment), the node preview functionality is also custom and other things. We plan to improve that situation in the mentioned entity.module until we can improve it in core.


Update hook - is it possible to generate success or failure message on operation success? I would like to be clear on how to indicate success (or failure) messages in update hooks, when a step completes successfully (not using &sandbox).

I vaguely remember seing a post on this (probably here) but all the examples I searched for do not show any messages in the update hook.

In Drupal 7, hook_update_N() doesn't need to return anything to make Drupal understand the update was successful; it needs to throw an exception in case of failure, which is what the methods of DatabaseSchema, such as DatabaseSchema::addField(), already do. (Those methods are the ones behind functions like db_add_field().)

See any of the update hooks used by Drupal core as example. (I removed the code comments just to make the code shorter.)

function user_update_7010() {
  db_change_field('users', 'signature_format', 'signature_format', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'description' => 'The {filter_format}.format of the signature.',
  ));

  db_update('users')
    ->fields(array('signature_format' => NULL))
    ->condition('signature', '')
    ->condition('signature_format', 0)
    ->execute();

  $existing_formats = db_query("SELECT format FROM {filter_format}")->fetchCol();
  $default_format = variable_get('filter_default_format', 1);
  db_update('users')
    ->fields(array('signature_format' => $default_format))
    ->isNotNull('signature_format')
    ->condition('signature_format', $existing_formats, 'NOT IN')
    ->execute();
}

function node_update_7012() {
  if (variable_get('update_d6', FALSE)) {
    db_update('field_config')
      ->fields(array('translatable' => 0))
      ->condition('field_name', 'body')
      ->execute();

    foreach (array('field_data_body', 'field_revision_body') as $table) {
      db_update($table)
        ->fields(array('language' => LANGUAGE_NONE))
        ->execute();
    }

    node_type_cache_reset();
  }
}

The only reason for hook_update_N() to return a string is changing the message seen in the update page.

// user_update_7002
if ($sandbox['user_from'] == $sandbox['user_count']) {
  if ($sandbox['user_not_migrated'] > 0) {
    variable_set('empty_timezone_message', 1);
    drupal_set_message(format_string('Some user time zones have been emptied and need to be set to the correct values. Use the new time zone options to choose whether to remind users at login to set the correct time zone.', array('@config-url' => url('admin/config/regional/settings'))), 'warning');
  }
  return t('Migrated user time zones');
}

Reference

update_do_one()


Reset node form after AJAX submit I have a node form in a block, that is submitted using AJAX.

I've created my own callback, because I'm adding the created node to the page if the submission was successful.

Now, I want to reset the node form to the default values. Any ideas on how to accomplish that?

Update:
I've managed to replace the form, by looking at the way node_add() works.

$new_node = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'node_type',
  'language' => LANGUAGE_NONE,
);

And then, I'm replacing the entire form with the return value from drupal_render(drupal_get_form('node_form', $new_node));

The form gets replaced as it should be, apart from some ids being different. However, when I submit the new form, I'll get a javascript alert window, with the entire contents of a new page. I can see from the HTML, that it's the page for the node that has been created. I suppose the AJAX callback gets redirected to the new node, but I don't know why.

Any clues?

Got it!

The main problem was that the new form was loaded from a cached version of the previous submitted form.

This is what I've got in my AJAX callback:

$new_form_state = array();
$new_form_state['build_info']['args'][] = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'node_type',
  'language' => LANGUAGE_NONE,
);
$new_form_state['no_redirect'] = TRUE;
$new_form_state['input'] = array();
$new_form = drupal_build_form('node_type_node_form', $new_form_state);
$commands[] = ajax_command_replace('#node-type-node-form', drupal_render($new_form));

The $new_form_state['no_redirect'] = TRUE; prevents the redirect, and the empty array in $new_form_state['input'] prevents the form from being loaded from a cached version.

@googletorp, thanks for the help!


Specific Site Building Setup Currently, I have a site set up like so:

Content Types:

Program
Course

Paragraph Type:

Semester

I have a lot of courses which are being taught in specific programs so I want to reference them and list them by semester on the program pages. One of my fields in Program is Courses of which I made it reference a paragraph type of Semester and this allows me to enter an unlimited amount of semesters.

The semester paragraph type is made up of a title field (of which I'd put in which semester it's in [ex. Semester 1]) and an unlimited content reference field that references the course content type.

I'm not sure if this is the best way to go about doing this but it seemed to work like I needed it to until I realized I needed the option to somehow add the ability to make it list two courses as optional. (Ex. It would need to say something like: 'Choose one of:  Course 1 or Course 2'. And I would need the option of possibly doing this more than once per semester.)

What would be the best site building method to allow me to do this?

This is basically what I'd like the final output to look like:

Assuming that you really want to groups with "Title" and those with "Choose one of:" to look the same, you can achieve that quite easily with nested paragraphs.

Something like a "Semester" paragraph type with a paragraph field called "Course groups", and a "Course group" paragraph type that has "Title" + Course lists. Then the title for the optional groups would simply be "Choose one of".

If you need different markup/output, you could handle that either with an "Optional/Select one" checkbox that you can check in a template or by defining two separate paragraph types and allowing both on the nested paragraph field, e.g. "Required course group", "Choose-one-of course group" paragraph types.

Or any other similar combination of nested paragraph types, whatever you need exactly.


Auto Import facebook comments into Drupal website Using Drupal 7. When i share a node on Facebook, i wish to automatically import Facebook comments made on Facebook for that node into the node's page on Drupal. I've tried a couple of modules including Facebook comments Block

1: https://www.drupal.org/project/facebook_comments_block and Facebook comments social plugin

but they only help users to comment on your site using their facebook accounts, no way to import comments made by users on the content page when it is shared to facebook.

You can fetch comments on a post using graph API. But you must know the Facebook post id of the corresponding node.

https://graph.facebook.com/<postedid>/comments

Try this - https://stackoverflow.com/questions/11043527/how-to-get-all-comments-and-likes-for-a-facebook-post


Facets display values instead of labels I am using the facets module to add filter blocks in my view.
I have a list field wich contains

FR|France
IT|Italy

My dropdown list of facet display values (fr, it)
I want to display (France, Italy)
How can I do that?
Thank you

try in search API > your index > search your field and then in the column type, select STRING.

Also maybe you can hook your field:

function HOOK_facet_items_alter(&$build, &$settings) {
   if ($settings->facet == "YOUR_FACET_NAME") {
       foreach($build as $key => $item) {
          $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
        }
    }
}


Why doesn't variable_set() work in an installation profile? I'm writing an installation profile, and I want to display some forms on some pages. The form below intended to set a variable at submission time. It does not work in the profile, but it works on an installed site. Why? Where is mistake?

function myprofile_install_mode_form() {
  $form = array();
  $form['myprofile_install_mode'] = array(
    '#type' => 'radios',
    '#title' => st('Please select'),
    '#default_value' => 0,
    '#description' => '',
    '#options' => array(st('Option 1'), st('Option 2')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => st('Continue'),
  );
  return $form;
}
// Submit handler
function myprofile_install_mode_form_submit(&$form, &$form_state) {
  $value = $form_state['values']['myprofile_install_mode'];
  variable_set('myprofile_install_mode', $value);
}

variable_set() works fine in installation profiles (standard_install() uses it), it's more likely that the submit handler for your form isn't being run. I seem to remember having to explicitly set the submit handler for one of these extra installation forms:

$form['#submit'][] = 'myprofile_install_mode_form_submit';

Try adding a call to drupal_set_message() in the form submit handler to make sure your code is definitely being run.


Apachesolr sort based on nodeviewcount I need to provide the option for sorting on the basis of nodeviewcount.
The criteria is that if any text is provided for search, the search results will be displayed according to maximum number of nodes viewed.

Take a look at Apache Solr View Count module which does exactly the same.

  This module allows you to index the node view count to Apache solr
  index as a custom field and let you sort SOLR results. The module
  requires Apache solr search module.

Disclosure: I'm one of the module maintainer.


How do I programatically get access to the file uploaded to a webform after a submission? I am using business rules custom action to access the submission data on entity insert.
I am able to get the file id and ultimately the realpath.
the real path is sites/default/files/private/webform/[webform_name]/_sid_/[file_name].
When I try to attach this file it is as if it were not there and ultimately gets moved into sites/default/files/private/webform/[webform_name]/[webform_submission_id]/[file_name].
I have tried to use the above path but it as if the file had not been written yet.
After the action has been completed I can attach the file with no problem.

The issue I am having is how can I get this illusive file and attach it to an email pragmatically.

here is the snipet of code that will generate the "/_sid_/" path

$file_id = $event['entity']->getData()[$file_field];
$file = \Drupal\file\Entity\File::load($file_id);
$realpath = \Drupal::service('file_system')->realpath($file->getFileUri());

Thank you for your responses and help on this.

Well, as first posts go, it ended up as a "stupid" mistake on my end. The webfrom module is well documented and the solution was very straight forward. (In short I was pushing an array into the ->AddAtachment method in PHPMailer.) For reference to anyone else here is my working code:

[module_name]\src\Plugin\BusinessRulesAction\SMTPAuthEmail.php

namespace Drupal\[module_name]\Plugin\BusinessRulesAction;
use Drupal\[module_name]\Controller\[module_name]Controller;
use Drupal\business_rules\ActionInterface;
use Drupal\business_rules\Events\BusinessRulesEvent;
use Drupal\business_rules\ItemInterface;
use Drupal\business_rules\Plugin\BusinessRulesActionPlugin;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render;
use Drupal\Core\File\FileSystem;
use Drupal\file\Entity\File;

class SMTPAuthEmail extends BusinessRulesActionPlugin {
    public function getSettingsForm(array &$form, FormStateInterface $form_state, ItemInterface $item) {
        //var_dump($item);
        $settings['email_settings'] = [
            '#type'          => 'fieldset',
            '#title'         => t('Email Settings'),
        ];
//this is just to show that I have a form for business rules that is being referenced later below.

    public function execute(ActionInterface $action, BusinessRulesEvent $event) {
    $send_email = new [module_name]Controller;
    $message = $action->getSettings();
    $css = file_get_contents(drupal_get_path('module', '[module_name]') . '/css/email.css');
    $entity_type = $event['entity']->getEntityTypeID();
    $node_storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $node = $node_storage->load($event['entity']->id());
    $build = $view_builder->view($node, 'table');
    $file_fields = $event['entity']->getWebform()->getElementsManagedFiles();
     if($file_fields){
        foreach ($file_fields as $file_field) {
            if (!empty($event['entity']->getData()[$file_field])) {
                $file_id = $event['entity']->getData()[$file_field];
                $file = \Drupal\file\Entity\File::load($file_id);
                $realpath = \Drupal::service('file_system')->realpath($file->getFileUri());
                $message['attachment'][] = $realpath;
            }
        }
    }
    $message['body'] = '<style>' . $css . '</style>' . render($build);
    $send_email->smtp_email($message);

}

[module_name]\src\Controller[ModuleName]Controller.php

class [ModuleName]Controller extends ControllerBase {

    public function smtp_email($data) {

        $mail = new PHPMailer();
        $mail->IsHTML(true);
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        if($data['tls']){
            $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
        }
        $mail->Host = $data['host'];
        $mail->Port = $data['port']; // or 587

        $mail->Username = $data['username'];
        $mail->Password = $data['password'];
        $mail->SetFrom($data['from']);
        $mail->Subject = $data['subject'];
        $mail->Body = $data['body'];
        if(isset($data['attachment'])) {
            foreach ($data['attachment'] as $attachment) {
                $mail->AddAttachment($attachment);
            }
        }
        foreach(explode(";",$data['to']) as $recipient) {
            $mail->AddAddress($recipient);
        }
        if(!$mail->Send()) {
            $message = "Mailer Error: " . $mail->ErrorInfo;
            $message_type = 'error';
        } else {
            $message =  "Message has been sent";
            $message_type = 'notice';
        }
        \Drupal::messenger()->addMessage(t($message), $message_type);
    }

}

I hope this helps someone!


How to set multi-value hidden field from javascript? I have a multi-value text field, the values should be set from javascript on the browser.
For a single value text field, I can just set the value of the hidden field. But for multi-value text field, drupal will only take the first value and omit following values even the browser post more than one value.
I insert some input tag with same name (nearly, see below) under the form using jquery:
<input type="hidden" name="field_subscription_id[und][0][value]" value="52e1c1d99c29ec6fd84698b6" />
<input type="hidden" name="field_subscription_id[und][1][value]" value="52e1c1d99c29ec6fd84698b6" />
...

data is POST like this (inspect using dev tool of chrome):
field_subscription_id[und][0][value]=52e1c1d99c29ec6fd84698b6
field_subscription_id[und][1][value]=52e3de349c29ec6fd84698d4
...

After node created, the field field_subscription_id will only have the first value.
So, any idea to make this work? ~thx
EDIT
I define the form from UI, just a normal content type and a text field. I make a ajax request to external site from page, let user select something (from the ajax response), then fill a field of add-node form with the selected ids.
Using the AJAX response, I build a list of <li>, each <li> has a checkbox, the form attribute (HTML5) of the checkbox has been set to the value of form-id of drupal add-node form on this page.

Fields will only appear in the $field_state array if they were there when the form was built. (If you inspect the $_POST array directly you should see your values there.)

The solution: When creating the form add enough fields so you don't need to add any more with js.

If you didn't create the form yourself then use hook_form_alter to add more fields.

If you need to be able to add more fields on the fly then you will have to look into the #ajax property. The examples module has some good examples on that.

Also make sure to use the #default_value, not #value property if you need to set a default value for any of the hidden fields as using #value will lock the value to that and stop the client from being able to make any changes.


How to render a field from loadtree Here is my code:

   $terms = array(

  \Drupal::service('entity_type.manager')
      ->getStorage("taxonomy_term")
      ->loadTree('faq', $parent = 0, $max_depth = 1, $load_entities = TRUE)

);

and when i'm using kint, i can see the first level of my vocabulary.

How can i render the field_question_tag in twig?

I Changed how to build my form,

public function buildForm(array $form, FormStateInterface $form_state) {
  $terms = \Drupal::service('entity_type.manager')
      ->getStorage("taxonomy_term")
      ->loadTree('faq', $parent = 0, $max_depth = 1, $load_entities = TRUE);
  $terms_select = array();
  foreach ($terms as $term){

      $question = $term->get('field_question_faq')->getValue();

      $terms_select[] =  $question[0]['value']);

  }

and then everything was fine!!

Thx to Vikram8888


Views Add Link to product field missing I have a search results View which list the (Commerce) products. I show the title and the image fields. I those fields to wrap in a custom <a> link tag. When I am adding fields, I miss the 'Link to product' field, so I am able to rewrite the fields and use the path {{ path }} token and theme it to my needs.

Do I miss or do I have to activate something?

The Path field has been deprecated, use Link to content instead. More info in this answer: How to get Node Url in RSS view?

When you have to construct a different output out of field values it's good to use the Custom text Field.

Exclude from display your Title, Image, and Link to content fields, reorder the fields so the Custom text field comes last.

Enter your anchor HTML into the Custom text area and use the  Replacement patterns you see in the list below the area to construct the full HTML code. One of them will be the URL token. Something like:

{{ title }} {{ field_image }}

Make sure your Title field settings aren't using links, and you may have to adjust the image field code further.


How to get the field template for view modes to work Content type - article , view modes - teaser, vma, vmb. There are 3 views , 2 on the left sidebar called vma view mode and vmb view mode, the one on the right is called teaser view mode. All the views show unformatted list of content using view modes vma, vmb and teaser respectively.
How to check for view mode in twig template?

Don't put too much logic into your templates. Simply add the field template suggestion by implementing hook_theme_suggestions_HOOK_alter to respect view modes from within your theme or custom module:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'] . '__' . $element['#view_mode'];
}

Now you can add templates following this pattern: field--node--field-myfield--article--teaser.html.twig.

When using Layout Builder or Display Suite you might need to check what else you find inside $variables['element'] by printing its values with Kint (sub-module of Devel) via ksm($variables['element']) and then build the template suggestion from what you find there.


How do I hide the page title based on node type using template_preprocess_page()? In Drupal 7, this was possible. (See How to hide page title based on node type using template_preprocess_page().)

function MYTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'concert') {
    $variables['show_title'] = FALSE;
  }
}

What is the equivalent in Drupal 8?

OUTDATED - please use this solution instead ...

In D8 i used

function MYTHEME_preprocess_page(&$variables) {
    if (!empty($variables['node']) && $variables['node']->getType() == 'page') {
        $variables['title'] = '';
    }
}

You still find the "node" object but you can't simply call the "type". The variable is protected, so you have to get the value via the function getType(). To get an overview install Devel and print with Kint the methods. This should only be a simple help, but maybe someone can deeper explain the concepts. Is it better to unset $variables['title'] in some way then to use $variables['title'] = ''?


SimpleTest clicking one of multiple "Add Another Item" buttons I'm attempting to test a node's form that has multiple fields that allow arbitrary numbers of entries. As such, there are several "Add Another Item" entries. In the SimpleTest docs (I think, I may have found it somewhere else ... code samples or something) it has examples for how to trigger the click of the Add Another Item button. Something like this:

$this->drupalPost(null, array(), t('Add another item'));

The trouble with this is that is targets the value of the field and the value is not unique across the page. In the docs it also suggests that you can pass in an array as the third parameter to drupalPost:

$this->drupalPost(null, array(), array('path' => '', 'triggering_element' => 'something_add_more');

Unfortunately I don't know what to set the path to. The default doesn't work (/system/ajax I believe) and I don't know what path drupal is using to trigger the ajax request to begin with when you manually click the button (if it's ajax at all).

I have also tried just passing the id or name of the button as the third parameters with no luck.

So here's my question: How can I uniquely select any one of the "Add Another Item" buttons found on the page from within the SimpleTest environment?

I think FileWidgetTestCase::testMultiValueWidget() should be useful as an example.

As you can see there, only drupalPostAJAX() supports to target the actual button based on the name, for drupalPost(), they actually mess with the HTML source ($buttons is a xpath result that can be altered).


How to speed up Drupal 7 calls to _theme_process_registry? Using xhprof php profiler I can see there is much more then 100000 calls to function_exists
each time user accesses a Drupal 7.8 page, mostly from _theme_process_registry.

What to do to limit the number of or cache these calls ?

I found there is already an issue related to this on drupal.org: Performance: optimize building theme registry by using get_defined_functions() instead of function_exists()


How can I delete nodes when an arbitrary date has past? I have a situation where future events will be posted to the website in question. These future events are a content type with a date field using the date module.

I wish to automatically delete these events once their date has past. I'm assuming that rules should do this but I have searched and I am struggling to find a way to do this.

You can use the hook_cron to solve your problem

function mymodule_cron(){
  _mymodule_delete_nodes();
}

function _mymodule_delete_nodes(){
  //select all nodes from type X where date expired
  //node_delete($nid);
}

See hook_cron for further information


remove unwanted path I have tried a lot to remove path that you can see in below picture:

I am new to drupal and learning it.So right now I am converting HTML template in to Drupal theme.

So for that I have copied bartik folder and I am changing in that.

For the content, I have used an article and from configuration I have set that article on front and removed title using function in template.php.

But I am not able to find, from where that path is coming from.

Inspect element of that specific part :

My page--front.tpl.php and template.php.

Ask me if more code is needed.

I have also tried by clearing cache but it did not help me out.

since it's not in either of those two file you linked, try node.tpl.php

failing that, see if you have a block defined to show in the content area, or content-top, etc.


Highlight Field Errors with an Ajax Form I'm using a number of Ajax form, and while the I can get the error validation to work, and present the error message using the following:

  if (null !== form_get_errors()):
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_remove('.alert-dismissable'),
        ajax_command_prepend('#myErrorDiv', theme('status_messages')),
      ),
    );
  endif;

However, I am unsure how to highlight the specific fields (usually done by adding a 'error' class to the form item.)

What the best way to achieve this, or is there a better way to handle the form errors that does not take over the normal error highlighting and message display?

Not as hard as I thought, but for anyone else trying to solve the same issue, you need to get all the relevant fields from form_get_errors() and add the error class to the same - note I also clear the previous errors:

if (null !== form_get_errors()):
  $commands[] = ajax_command_invoke('#myFormDiv .form-item.error', 'removeClass', array('error'));
  $commands[] = ajax_command_remove('.alert-dismissable');
  $commands[] = ajax_command_prepend('#myErrorDiv', theme('status_messages'));
  foreach (form_get_errors() as $field => $message) :
    $commands[] = ajax_command_invoke('.form-item-'.$field, 'addClass', array('error'));
  endforeach;
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
endif;

Note that your $field will be dependent in what you've set in your validation function, so you might need to do some funky things to make sure '.form-item-'.$field is finding the right div.


How do I add a class to HTML bookmarks generated by core? I'd like to add a CSS class to HTML bookmarks generated by core. Examples of these bookmarks include:

I'd like to turn them into:

I'm unable to alter these in comment.tpl.php and it looks like theme_comment_view is unavailable in D7, so I'm kind of lost.

Background: I have a sticky header menu that's 60px tall and as such, HTML bookmarks are landing about 60px lower on the page than they should. An example of this is when you link to comment by ID, like http://site.com/article#comment-766013.

Thanks!

Those anchors are added in comment_view(). To override them you'll need to implement hook_comment_view_alter() and reproduce a bit of the logic from the original view function:

function MYMODULE_comment_view_alter(&$build) {
  $comment = $build['#comment'];
  $node = $build['#node'];

  if (empty($comment->in_preview)) {
    $prefix = '';
    $is_threaded = isset($comment->divs) && variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED) == COMMENT_MODE_THREADED;

    // Add 'new' anchor if needed.
    if (!empty($comment->first_new)) {
      $prefix .= "\n";
    }

    // Add indentation div or close open divs as needed.
    if ($is_threaded) {
      $prefix .= $comment->divs <= 0 ? str_repeat('
', abs($comment->divs)) : "\n" . '
';
    }

    // Add anchor for each comment.
    $prefix .= "cid\" class=\"bookmark\">\n";
    $build['#prefix'] = $prefix;
  }
}


Passing nid into a context view I have a context that is fired when it is on a node page. I wish to pass the nid of the node being viewed, into a view to display on the page. Is this possible? How would you go about doing this?

Node id can be accessed by arg(2) function call on node page view. It would even work if you have defined a url alias using path/auto_path modules.

On the view, where you manage argument options, Try with Provide default argument option as Node ID from URL


Best way to get current user purchased products I need to get purchased products by the current user (Drupal Commerce).

I use this function to reach there :

function mymodule_user_purchased_products() {
    global $user;
    $query = db_select('commerce_order', 'corder');
    $query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
    $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
    $query->condition('corder.uid', $user->uid, '=')
          ->condition('corder.status', 'completed', '=')
          ->fields('prod', array('commerce_product_product_id'));
    $result = $query->execute();
}

But I think I forget certain things, and this solution isn't optimal.

Is it the recommended way?

One one thing that I can think of to change. Make sure you only get a single result.

$query = db_select('commerce_order', 'corder');
$query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
$query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
$query->condition('corder.uid', $user->uid, '=')
      ->condition('corder.status', 'completed', '=')
      ->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

Using this line:

->addExpression('DISTINCT prod.commerce_product_product_id', 'product_id');

instead of:

->fields('prod', array('commerce_product_product_id'));

will insure that you only get one product_id per row in your result. By using the DISTINCT SQL Keyword, it will only allow distinct values to be returned.


Rules: how to create variable with PHP and $_SERVER['HTTP_REFERRER'] I want to parse the query string off the HTTP_REFERRER and make that available as a variable for actions to use.

I feel like one of these options should let me do that, but I can't be sure...

The concept is simple

<?php
  $parts = parse_url( $_SERVER['HTTP_REFERRER'] );
  parse_str( $parts['query'], $q );
  // now set $q (or its elements) as the variable
?>

Turns out I just had to look harder and change my expectations a little.

Click Add a Variable
Select text (for my scenario)
In the Value field, you can then use php to echo out a value for a single variable

I was hoping to be able to create a variable with a type of 'object' (or similar) so that I could use the url values like [url:param1] or [url:param2].

I have not found a way to do that - I just created a different variable for each of the two parameters I needed off the query string.


Copying prod multi-site installation to dev multi-site installation I am attempting to upgrade my Drupal 8.9.2 multi-site installation to D9. I was hoping to work this all out on a development installation, that is located in a subdirectory of my home directory on my NameCheap Shared Hosting plan.
When I first installed this installation, I did so using the tarball method from years ago. I then followed the instructions given here (https://www.drupal.org/docs/installing-drupal/add-composer-to-an-existing-site). I was able to get the current running prod version converted to use composer with out an issue.
Before I go and start messing with the files, and attempting to upgrade to D9 through composer on a prod installation, I wanted to copy these files over to another installation where I can use it as a sandbox. To do this I:

copied the files on my server to a new directory
made clone databases for the new installation
truncated all the cache tables in the cloned DB
changed all the database settings in the settings files to point to the cloned databases

I've done this before without any issues, and now I seem to be getting a WSOD error on all the sites running from the new installation. The error I'm getting is

PHP Fatal error:  Uncaught Error: Class 'Drupal\Core\Cache\DatabaseBackend' not found in ~/{new installation dir}/public_html/index.php:16.

If anyone has any thoughts what's going on I am all ears.
Thank you in advance

I was able to get the current running prod version converted to use composer with out an issue.

If you have converted your site to use composer , you dont need to copy the whole code base into the new server. Just copy the config,custom modules, composer.json, composer lock files and other reqired files except the core, vendor and contributed modules into new server along with sites directory folder and run composer install in the root directory of the server.This can be done by initiating a git repo in the current code and using the default .gitignore file which is available in code.And cloning the same repo in new server.
As you have already copied all the files into new server.
Just run rm -Rf vendor , rm -Rf web/core and rm -Rf web/modules/contrib and run composer install from the root directory in the new server.
After doing this you will probably get your site running in Dev environment as well.