Duplicated results using fields from relation File Usage: file

You need to add a File relationship for a specific field, not a File Usage relationship.

In the options for 'Add relationships' select the 'File' filter and you should see an option for each field e.g. 'File: Content using My Field'. Use this and it will give you the same data (file size etc.) but just for files attached to that field.


you can try with hidden field. You can make #guid field a hidden field. in your hook_form_alter() #guid initially will hold the default value to empty on submission, you can make #guid fields value to whatever you want to make.

funciton mymodule_form_alter(&$form, &$form_state, $form_id){
  if(isset($form_state['values']['url']){
    $guid = 'extra string' . $form_state['values']['url'];
  }
  $form['#guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '';
    );
}


Have you tried removing the quotes?

field_reference:
-
  plugin: sub_process
  source: field_reference
  process:
    value: value
    format:
      plugin: default_value
      default_value: basic_html


Using the modules Rules and Facebook Autopost, the previous post body summary is used instead of the current post

Your publish_to_facebook is NOT your very last Rules action. In fact, as per the save_entity which follows it, it appears that you are publishing to Facebook something that hasn't been saved yet. So that at least seems to explain what you see happening.

Any attempt to get it to work should ensure that you only publish something that has been saved. So you may want to try by just swapping the last 2 rules actions.

The above is just a quick and dirty attempt, and I doubt you'll actually get it to work like that. But your question reminds me about issue # 430274, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to move your  publish_to_facebook action into a second Rules or component in order to ensure that the node is definitely saved correctly.

Method 1: Your original Rule "schedules the execution" (using the
Rules Scheduler sub-module) of that Rules component. For example
after only a few seconds or minutes if your cron job runs frequent
enough (otherwise it'll be next time cron runs). This compromise will
ensure that, at the time the Rules component is executed, the entity
is for sure saved (so that can't be the reason anymore then why
things don't work as expected).
Method 2: Add a Boolean field to the node type and when using Rules
to create the node, set it to "off". Then add a redirect to the
created node as the last action.
After that, create a second rule for "Content is viewed" which will make the Facebook post.
Condition: "Boolean field == Off".
Action 1: Post to Facebook using viewed node's data.
Action 2: Set a Data Value: Boolean field == "On".

If none of the above helps, maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?".

Note: In 1 of your (moved to chat) comments, you also added this:

  Facebook returns a unique identifier that must be saved as part of the entity so I can further code updates or deletes if necessary.

If I was to make this work, I would first make the original question work, which is about "add a new article" (updates or deletes is an additional challenge). Because as long as you've not succeeded in that, there is nothing to update or delete ...


Can a custom module be used to assign permissions associated with a different module?

There are hooks* to revoke or change permissions so there is no need to set TRUE or FALSE in your snippet.

Try this:

function mycustommodule_modules_enabled($modules) {
  if (in_array('contribmodule', $modules)) {
    $roleid = array_search('custom role', user_roles());
    if (is_int($roleid)) {
      user_role_grant_permissions($roleid, array(
        'permission from contrib module',
      ));
    }
  }
}

In this call, you are setting the array's value to the permission name -- Not the key.

*: user_role_change_permissions() and user_role_revoke_permissions()


Is it even possible to export webform form snippets?

The answer is no. This is not the way Drupal theming and form building works. One of the main reasons would be that default Drupal hooks and theme functions will not work consistently if you can get a snapshot of a template, export it and change to your liking.

Let's take an example:

You create a webform with several fields.
Through this fictive module, you get the output which you can use in template files.
You use the code where you want.

The following will not work:

hook_form_alter() implementations. Fields added through dynamic conditions will not be there as well as custom CSS/JS.
Theming overrides will not work as well; say that your theme changes the way textarea elements are rendered. By exporting the form, you get the snapshot; if there is any dynamic condition, it won't work because the system cannot alter the markup anymore.

Solving the above problems would end up in a real mess, and I think this is just a tip of the iceberg.


How do you get Product Variation Type fields and display modes to show up when displaying Products in a View?

It turns out that I had to add a relationship to Product Variation Type in order for those fields to show up. Hope this helps others!


You can remove a module's implementation of a hook like so:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_validate' && isset($implementations['anonymous_publishing_cl'])) {
    unset($implementations['anonymous_publishing_cl']);
  }
}


Your question is somewhat vague, what specifically is the "output" you want to override?! Is it drupal Field output, a theme variable such as $vars['geolocation-something-foo'] ... or something else?

There is likely a preprocess or process Hook you can implement to slide in your changes. Or using Devel Themer you can probably override their template file with one of your own easily.

Something I did yesterday was override the implementing function of another module with a (local copy) of my own version of that function in a custom module -- tweaked to add HTML attributes and tags that I needed and were'nt provided by the raw HTML (non render array) output of the other module.

I followed the good example from this Snugug: Overriding Drupal Theme Functions from your Module and used HOOK_theme_registry_alter() using the following logic:

/**
 * Implements hook_theme_registry_alter
 */
function mymodule__theme_registry_alter(&$theme_registry) {
  $theme_registry['ORIGINALMODULE_function_name']['function'] = 'MYMODULE_function_name';
}

I think took the body from the original function, copied, tweaked and pasted it into mymodule_function_name. I believe this hook is callable from a theme as well ...


Is possible to use multiple taxonomy terms name (not tids) as contextual filter in Views?

Maybe too late for this to matter, but you may be able to do this with hook_views_pre_view().

Possible example:

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if (!empty($args)) {
    // change the argument to term IDs
    $term_names = explode('+', $args[0]);
    foreach ($term_names as $term) {
      $terms[] = taxonomy_get_term_by_name($term)->tid;
    }
    $view->args[0] = implode('+', $terms);
  }
}


Try the Context Metadata module. It can add metadata to node and non-node pages. The following metadata tags can be set according to a context: Title, Description, Keywords and Canonical URL.


EntityFieldQuery with fieldCondition returns nothing

I hadn't checked it for trailing spaces. So using trim() on $unique_number did the trick. Thanks for leading me the right way Clive!


how to make a page with record displayed from database

Probably because before anything has a chance to print you are already returning #markup from formModule_page().
You might also want to use the Devel module's dpm() function for more cleaner and convenient debug messages and variable inspection.


call_user_func() and external functions problem

Your functions are in files that haven't yet been included, try changing your code to this:

foreach ($nodes as &$node_name) {
  module_load_include('inc', 'my_module', 'my_module.' . $node_name);

  $func = '_'.$node_name.'_create_node';
  if (function_exists($func)) {
    call_user_func($func, $node_name);
  }
}

I've never been able to get the files[] key in the .info file to work, I don't think it's used for arbitrary files but rather those that will form part of Drupal's code registry (using hook_hook_info() or something like that), but I haven't delved too deeply so it's worth checking yourself.

To answer your final question, yes I think you're over-engineering this a bit :)

It would make sense to do this if your module is going to become generic (so more content types can be catered for) but if it's really just 2 content types I'd put the code inside the .module file to be honest.

Obviously if you think these files will end up having a lot of code it makes sense to separate them, but if not I don't think you're really getting much benefit for doing so.


Can www.example.com/node/123 be used as a canonical url?

Permanently redirecting the canonical URL is allowed, but discouraged by RFC 6596:

  To better ensure that applications properly handle the canonical link relation, administrators ought to consider the following guidelines:

  […]

  Avoid designating the target (canonical) as:

  […]

  The source IRI of a permanent redirect (for HTTP, this refers to 300 and 301 response codes defined in Sections 10.3.1 and 10.3.2 of [RFC2616]


How to utilize custom form modes to edit a user entity?

You have to add the form mode in the handlers section of the user entity:

/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('my_profile', 'Drupal\user\ProfileForm');
}

Use the standard class ProfileForm as you only want a set new form mode, not a new form class.

Then you can use this new handler in place of user.default in the routing file:

'_entity_form' => 'user.my_profile',


How to get update status of multiple Drupal sites

A search on drupal.org found Drupal Remote Dashboard

If that module doesn't work for you, I would suggest a thorough search of drupal.org before jumping into creating your own module.


Create a footer menu from primary links and should be able to control what should appear

For this functionality, try Footer Sitemap

It allows you to choose which menus and/or menu items will be included in the footer sitemap.

You can then customize the template included to manipulate the markup if you need to.


Developing sites while using Aegir and Drush make

Yes. The short answer is you update your Drush make file to point to the new version of the module you want to be included in your new platform(build).

In your drush make file you would include the version of each module you are including in your platform build. So views for example would look like this.

projects[views][subdir] = "contrib"
projects[views][version] = "3.4"

Now if you want to update to the new version of Views module you would update your make file to something like this.

projects[views][subdir] = "contrib"
projects[views][version] = "3.5"

Then build a new platform in Aegir using this updated drush make file. Then you would migrate the site to the new platform and Aegir will do the update for you.

It's a pretty slick workflow. I keep all of my drush make files in a repo called builds so I can have a record of each build of a project. Hope that helps.


You are just processing the search results in your function but haven;t handled the output. Change the tpl.php to display the variables from your function rather than from the default search function.


My module development snapshot is never updated

Drupal.org shows a link to your drupal.org account for each commit you do only when Git has been set to use the same email associated to your drupal.org account.
If the email you are using with Git is different from the email you are using to get emails about your drupal.org account, you can add that email on https://www.drupal.org/user/1327432/edit/email-addresses. In this way, the commits you do for a module are associated to your drupal.org account which also means, for example, that the Maintainers for Slack to Drupal block that appears on https://www.drupal.org/project/slack_to_drupal show the exact number of commits you did and when.

The new email associated to the drupal.org account doesn't need to be made the default one, which means it would be used for every communication from Drupal.org. It just needs to be added to your account, so drupal.org associate the email to an account.
For the other commits to be associated to your account, you need to open an issue on the Drupal.org infrastructure queue asking to associate your commits to your account, similar to Request to associate commits with my account.


How to create a custom Aegir Drupal interface

Yup, create a theme with all things you want, some custom modules to do more heavy lifting and there you have it and install both on your Aegir server. (working on similar idea i have for Aegir, including fcgi support, so i can jail sites to a user, sell them in a store and let the users fix their own sites.)

And / or you could use something like http://drupal.org/project/hosting_services to write something yourself. (and loads more)


Generating Images from image styles in drupal 7

Are the folders where the images go writable? Also check the tmp folder


How to subtract two columns with db_select()?

You're looking for MySQL's HAVING, which permits SELECT level aliases.

So this:

SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
WHERE `difference` > 55

Becomes this:

SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
HAVING `difference` > 55

Which in Drupal-ese is:

$query = db_select('mytable')
  ->fields('mytable')
  ->having('difference > :floor', array(':floor' => 55));

$query->addExpression('column1value - column2value', 'difference');

For a simple calculation like this example performance would be better using the expression directly in a WHERE clause. In the example you've given in your answer, I suspect HAVING would be quicker (although MySQL's pretty smart, it may be able to cache that calculation)


Views - how to filter a result set based on a URL filter that affects an API call?

So, I am not 100% confident in this approach, but I got a working solution. The base table is Node, I have no join, this data is not stored locally and I use an API call to fetch the operating hours. So I looked at how the Global filter options worked and started from there with hook_views_data:

In mymodule.module:

/**
 * Implements hook_views_data().
 */
function harlib_restful_normalizer_views_data() {
  $data = [];
  $data['libcal']['table']['group'] = t('LibCal');
  $data['libcal']['table']['join'] = [
    '#global' => [],
  ];

  $data['libcal']['open_now'] = [
    'title' => t('Open Now'),
    'filter' => [
      'id' => 'open_now',
      'title' => t('Currently Open'),
      'help' => t('Filter results by "currently_open" value on results from LibCal Hours API.'),
    ],
  ];

  return $data;
}

In my custom OpenNow filter class:

namespace Drupal\harlib_restful_normalizer\Plugin\views\filter;

use Drupal\harlib_libcal_api\Client\HoursTodayClient;
use Drupal\views\Plugin\views\filter\BooleanOperator;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filters nodes based on libcal currently open value.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("open_now")
 */
class OpenNow extends BooleanOperator {

  /**
   * @var \Drupal\harlib_libcal_api\Client\HoursTodayClient
   */
  protected $hoursClient;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, HoursTodayClient $client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->hoursClient = $client;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('harlib_libcal_api.hours_today_client')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function postExecute(&$values) {
    if ($this->value) {
      foreach ($values as $key => $value) {
        $node = $value->_entity;
        $library_id = (int) $node->get('field_library_id')->value;

        if ($library_id === 0) {
          // No times associated with this library.
          unset($values[$key]);
          continue;
        }

        $hours = $this->hoursClient->request($library_id);

        if ($hours['currently_open'] == FALSE) {
          unset($values[$key]);
        }
      }

      $values = array_values($values);
    }

    parent::postExecute($values);
  }

}

If the filter is 'checked' or true, the postExecute method will loop the result set, check the hours returned and unset the result if the location is not currently open. I am not using pagination or anything, so, I did not test if it works in those conditions.

The better scenario is to filter the JSON list on the front end (since the data is already attached to the entity in the response), but I was asked to do it from the backend.


Modules needed to create the best WYSIWYG experience?

You will need the Drupal WYSIWYG module http://drupal.org/project/wysiwyg and the TinyMCE Library here http://www.tinymce.com/

TinyMCE supports plugins and you can make that "best WYSIWYG experience" that you are looking for. You can hook it up with your theme CSS and apply styles to the text aeras and see them in the WYSIWYG. Also check the WYSIWYG plugins page http://drupal.org/node/1197256


On a module Issue page, how do you tell what version the patch has been applied in?

As mentionned by Eyal a patch is always applied to the -dev version of the module. That's already a good stuff to know.
So yes, if a patch is committed you can download the -dev version specified in the issue (or apply the patch separately if needed).

Usually the patches included in a new release are listed in the changelog:
.

note:
normally once a patch is committed the issue status becomes "closed (fixed)" and you will ind this kind of details in the latest issue comments:

In the sidebar of the presentation page of the module the "View pending patches" can be helpful to check if the issue you are looking for is still opened or fixed. There is also the "Views commits" link for a quick overview. this page provides a detailed list of the patches implemented (issue date, version , description, id).

--

The official doc https://www.drupal.org/issue-queue/status could also help you to understand the process.


How to create regular (monthly) reports from users?

This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Have a look at the "Northwind database" demo videos, which is similar to what you're looking for. Such as these videos:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).
Various other Video demos and tutorials created in an earlier (7.x-3.x) release of Forena (which are mostly still accurate, but only using outdated Forena screens that have been enhanced in the 7.x-4.x version).

Below are some more suggestions to map the various features you're asking for to Forena equivalents ...

  There are several users with a customized role - Sales managers, who need to provide monthly reports on sales.

Forena comes with various types of permissions, such as:

Who is allowed to build the SQL statements (data blocks) that will be used in the reports that visualize these data?
Who can browse specific reports?

Especially for "sensitive data" (commissions, salaries, ...) this is important.

  A Content Type - Sales Report was configured in the system.

Forena doesn't really need a content type to show its reports/graphs. And using the BEAN integration of it you can also create blocks that display Forena reports. For the actual look-and-feel of the report, anything that can be expressed in XHTML is supported by Forena.

  The users will need to login and if the report is not yet provided for the last month, they need to have an option to create a new one and submit it.

That sounds like anonymous users are to be excluded from Forena reports (a matter of permissions). If the site somewhere shows a menu item or some link to "a" (monthly?) report, these users just have to use that link.  And specifying the actual month for which the report is to be shown, is typically implemented as a "report parameter", typically a pull down selection list near the top of the report.

Because of all the options that Forena offers to specify report parameters, there are various ways you could implement the selection of the actual month to be reported about.

  If the report was provided - they need to have the option to edit the report.

That's what you typically do using the WYSIWYG report editor. Though somebody who's familiar with XHTML might rather want to directly edit the (so called) .frx files.

  After the report is submited, a user with the role Department Manager will have to approve the report or send it back to Sales managers to be update.

That sounds like a workflow issue. Not sure if it is the only (or most elegant) way to implement this, but here is a possible approach:

Somebody authorized to do so, should create a report for the "new" month, by cloning the report from the "prior" month. Probably only changing the parameter list (by adding the new month to it).
Grant access to this new report to (only) role Department Manager, so that such users can look at the new report.
Continue improving the "new" report (as in step 1.) until it gets approved by the Department Manager.
After the "new" report is approved, grant access to anybody else who is now also allowed to browse it.
Build a special Forena report that can be used (by an authorized user ...) to send a notification eMail to all users that might be interested in being notified that the "new" report is available. To do so, you just build a report of such users, and enable "eMail" as on of the allowed "document formats" (= formats that a report can be exported to, such as CSV, XLS, PDF, eMail, etc).

  How do I organize/configure this with Drupal?

As detailed above: there's a module for it, i.e. Forena

PS: nowhere in your questions it says anything about "Charts" (sales people often "need" them also) ... But creating charts is a bonus that comes with Forena also ...

Disclosure: I'm a co-maintainer of Forena.


How to count the node a user has created in a View?

you have to use the Aggregation setting and active it in your view.

Activate Aggregation. (It's in the "advanced settings" of the view)
As your view is a view of users, add the relationship "User : content authored". If you set the option "Require this relationship", you'll skip users with no nodes created (can be useful)
Add your user name field, don't use aggregate
Add a node field, let's say Node : nid with the relationship set
Use Aggregate for this field, "Count DISTINCT".

Have fun !


After defining your menu item via views, you have to go back to the views list (/admin/structure/views). There is a "Translate" option under "Edit".

There, you can "Add" a translation, then choose your page display options and translate the menu item (applies for Drupal 8 only).

If the menu item is not showing up, clear the caches (e.g. cache rebuild using drush cr).


Drupal commerce user based percentage discount

Yes, Rajeesh, anything is possible with Rules. : P

In this case, I'd recommend something like a discount percentage field on user profiles that defaults to 10% and is only visible to administrators who can then override the field value on a user-by-user basis. Your product pricing rule can then look for this field to have a value on the order's user (i.e. use commerce-line-item:commerce-order:owner as the token, not the site:current-user) and then apply it as a discount using the appropriate line item action.


Changing Drupal's default email notification on password reset

Pop to http://www.mysite.com/admin/user/settings, you can edit the subject and body for the email under the "Password Recovery Email" fieldset.

To do this programatically you can call _user_mail_notify() with the password_reset op parameter:

_user_mail_notify('password_reset', $account);

You can generate a one-time login link using the user_pass_reset_url() function:

$url = user_pass_reset_url($account);


Is there an easy way to prepopulate webform field default values from profile2 field values?

hook_form_alter(){
//and set default values form profile2_load_by_user();
}


I would advise you to learn how to use the views module.

In order to achieve what you want. Make sure to install the views module first. To add a new view go to admin/structure/views/add and you should see the page below. Select the content type you want

On the same page change teasers to fields. And then click continue and edit. It should take you to a new page. To add more fields from the content type you want, click on the Add link under the fields category. To make it better formatted, you can change the format type under the format category. Once you have added all your fields, click on the save button at the top.


How to link a view´s field to attachment´s field?

So, my mistake, it is quiet simple. If you struggle with similar problem:
in the Attachment:
-add a field content: NID, hidden

-In global: custom text add, for example,
[title]

This way we have an NID anchor we can link to.

In the block view:
-add a field content: NID, hidden (so our link field gets NID as a value, not as a string "nid")

-we rewrite some field (for example title): output this field as a link. Link path: #[nid]

Voila, it works. My problem was I forgot to include content: nid in block view.


After altering form I cannot save changes in nodes

As @NikhilMohan says, you can't just remove fields like the title; they're required for validation. Event setting #access => FALSE has strange results in my experience.

What you could do instead, is set a value for the fields you're hiding, and change their #type to 'value'. That way the element will still exist on the server side, and validation/submission won't break.

e.g.

$form['title']['#type'] = 'value';
$form['title']['#value'] = 'Some default value for the title';


Change the confirm_form message of an entity made with eck

You can use hook form alter to change a piece of the form, see this answer by Clive:

https://stackoverflow.com/questions/8111034/altering-title-on-drupal-node-delete-confirmation-form


Add .active class to a menu link when other menu link is clicked

The cited solution appears a little buggy, as it replaces all potentially existing classes of the menu items. But what makes it not suitable for your use case is, that it is intended to add the active class only, if the current path matches the menu link's URL path.

What you are looking for instead, is the menu items' "active trail". It is a flag set by the menu module on every menu item found when traversing the menu tree upwards, starting from the current active item up to the menu root.

With this information at hand, have a check for the default menu template. It features the menu item specific property in_active_trail:

  in_active_trail: TRUE if the link is in the active trail.

So you can easily add the active class to your currently active menu item and all its parents by using the following in your theme's menu.html.twig:

{%
  set link_classes = [
    item.in_active_trail ? 'active',
  ]
%}
{{ link(item.title, item.url, {'class': link_classes}) }}

A more complete example for a Bootstrap 4 navigation with menu.html.twig:

{#
/**
 * @file
 * Theme override to display a Bootstrap 4 menu.
 */
#}
{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('nav') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'nav-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {%
          set link_classes = [
            'nav-link',
            item.in_active_trail ? 'active',
          ]
        %}
        {{ link(item.title, item.url, {'class': link_classes}) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}


Invalidate cache on ConfigFormBase submit

You have to add the cache tags to the rendered output of the config field:

$form['example'] = [
  '#markup' => $settings->get('name'),
  '#cache' => [
    'tags' => $settings->getCacheTags(),
  ],
];


I've finally succeded in correcting this bug, by modifying directly the Panels module. I'll publish a patch on panel's forum on drupal's site. Here's the solution :

In the file /sites/all/modules/panels/plugins/display_renderers/panels_renderer_editor.class.php, you have to change get_url() function (line 505), replace this:

 $url = 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

by this

 if (variable_get('clean_url', FALSE))
  $url = '?q=';

$url .= 'panels/ajax/' . $this->plugin['name'] . '/' . $command . '/' . $this->display->cache_key;

As you maybe know the problem is caused by cleans Url, so it works without the fix if u disable it. But if you want to keep cleans url, apply the fix, it forces all ajax requests to be without cleans urls

PS: Thank you to MPD♦ who deleted my previous answer where i put a link to azure forum which was a possible way to solve the problem.


Is it possible to use a user display form in a page?

Unlike view modes there is no UI in core to apply different form modes other than the user register form. You can try one of these modules:

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

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


Views exposed filter using Solr only returning results for exact phrase

This is a screenshot of the basic search view that we setup for our Search API + Apache SOLR configuration:

The settings for the filter can be shown here:


Can I create nodes through drush for particular content type

Just a note to point out a new module called Faker which can be used in conjunction with Devel Generate :

  Use the PHP Faker library to generate more meaningful sample content.

  Devel Generate is great for creating a lot of sample content in a
  hurry, but sometimes you want samples that are more meaningful, or
  closer to the content you expect users to generate. This is where
  Faker comes in.

  Faker is a PHP library that generates fake data for you

  Faker (the library) can generate real looking names, addresses,
  emails, domains and more. Faker (the module) combines the library with
  quick content creation abilities provided by Devel Generate, to give
  you the power to easily generate real looking sample content.


If you're looking to do this in code, I believe that this question has already been answered:

Given a File ID (fid) how can I get the HTML that represents that fid?

You can also access the file's page at yoursiteurl/file/fid, but this isn't a direct link to the file.


Permission issues with Custom Content Entity exposed to REST API

Actually, this was a false positive error.. I did some testing with my REST Client in Chrome (please see screenshot at the end of the paragraph) and permissions are correctly working.

The issue was related to my XHR request which was (for some reasons) keeping a valid CSRF token and because of this I appeared to be identified as admin. And of course as admin ID 1, I was granted full access on CRUD..

Sorry and thanks for your time guys!


"Find Content" (/admin/content) then Edit the node.


How to avoid timeouts on real long page loads

The Drupal Batch API is a great solution for something like this. You can specify or count the number of actions that need to be done, display a progress bar, and prevent timeouts on long processes. Also there are many examples like this one you can utilize to create a good solution for your use-case.


The {cache_form} table is a little funny, and behaves in a slightly different manner than other cache tables.

If you take a look at drupal_flush_all_caches() you will see that {cache_form} isn't cleared.  This is to protect in-progress forms from being nuked.

The system_cron() function does take care of pruning out old data from {cache_form} along with the other cache tables.

You really should run cron on all Drupal sites.  If you {cache_form} table is ginourmous, then I bet your {watchdog} and {session} tables are, too.  Many other modules run housekeeping activity as part of their own hook_cron() functions.

You may also want to poke around the issue queue.  There have been some bugs with {cache_form}, and you may be running into one.


You could simply call drupal_get_form() on the search form_id, which I think is - either search_block_form or search_form

And use drupal_render() on the returned array.

  print drupal_render(drupal_get_form('search_block_form'));

Though I might be wrong about the drupal_render() part, yet it seems to me since the drupal_get_form() returns an array drupal_render should be used on it.

Also this page might be helpful too - http://data.agaric.com/print-form-such-search-form-anywhere-drupal

Hope that helps.


What is the Context column for in String Overrides module?

Currently, not much!

It appears to mostly be for D8.

http://drupal.org/node/1477568


Read the UPGRADE.txt
Have a look at the CCK Module for D7. It comes with a migration submodule.
The them has to be adapted to D7 manually. Have a look at this for reference.


Creating a custom field view using theme_field template

I'm not really sure what you are trying to do, but if you only like to render a custom array with the field template this should work:

$field = array(
  '#theme' => 'field',
  '#field_type' => 'text',
  '#field_name' => 'temp_field',
  '#entity_type' => 'node',
  '#bundle' => null,
  '#items' => array(
     array(
       'value' => '',
     )
   ),
   0 => array(
     '#markup' => '
This is a test
'
   )
);
print theme_field(array(
  'label_hidden' => false,
  'label' => t('custom field label'),
  'items' => array($field),
  'classes' => 'test',
  'content_attributes' => '',
  'attributes' => '',
  'item_attributes' => ''
));

You can load one of your existing field using field_view_field() to check what data the renderable array contains. For example to load the body field from a node with an id equal to 1000 you could do like this:

$node = node_load(1000);
$field = field_view_field('node', $node, 'body');
print_r($field);


Views Autocomplete search multiple values

You can use Views autocomplete filter module to have auto-complete feature on views exposed filters.

  It works for node titles or cck text fields.

  The autocomplete results are actually the view results, so they are
  view related.

Check out this Demo video.


To use the "Set breadcrumb" rules action you should add it to the event "Content is viewed", for example

Event: Content is viewed
Condition: Content is of type article
Action: Set breadcrumb: Title: Articles\n[node:title] Paths: articles\n[node:url]

rules_action_breadcrumb_set basically goes through those title and path values and uses drupal_set_breadcrumb to set the breadcrumb.


SQL query for phpMyAdmin to delete authenticated users

As mentioned in the comments, directly modifying the tables could be disastrous.  If you need to get rid of large numbers of users I would suggestion Using Views with Views Bulk Operations:

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month.

This module augments Views by allowing bulk operations to be executed
 on the displayed rows. It does so by showing a checkbox in front of
 each node, and adding a select box containing operations that can be
 applied. Drupal Core or Rules actions can be used.


Reason for Revolution Slider failure found: the Rev Slider uses the hammer.js jQuery plugin. Elsewhere on my site I have installed the jQuery mMenu, which also has hammer.js among its scripts. I disabled hammer.js in mmenu, and the Rev Slider comes alive immediately. The clash centres around the event listeners functions in the hammer script.

Haven't solved all though, mmenu still works fine but I do get a 'where is hammer.js' error thrown at me now of course. Will report when and how I solve that..


Yes. Just require the services you need in your constructor, and wherever you create your object, pass them in.

That is the very definition of dependency injection.

The container/services are just a way to describe your dependencies to the environment/Drupal so it can do that automatically but that is in no way a requirement.

What you probably want to do is to use the factory pattern, so that you have a factory, which you can define a service, which offers a method to get your value object with the necessary services injected. Drupal 8 has various examples for the, for example KeyValueDatabaseFactory (keyvalue.database), which has a get($collection) method. Each call creates a new object, passes the dependencies that object needs to it and then returns it.


In the settings of the view field you can use this option (located in STYLE SETTINGS):

  [x] Use field template

Now the field is rendered by the same field template you use in the content type including preprocess hooks.

To see the added theme hook and field template enable Twig debug and look at the html source in the browser.


How to set a phone number via entity_metadata_wrapper?

I got around this problem by using the following snippet just before the user_save(..) call:

$fields['field_mobilephone'][LANGUAGE_NONE][0]['number'] = $_REQUEST['mobilephone'];
$fields['field_mobilephone'][LANGUAGE_NONE][0]['country_codes'] = 'au';

This approach bypasses the entity_metadata_wrapper altogether.
Pretty sure there's a cleaner way, but I'm not yet aware of it.


Implementation of the Google Identity Toolkit (openid like)

If you want to implement it in specific open source platform, please use Google Identity Toolkit Plugins. There is a plugin for opencart 1.4.x: http://www.opencart.com/index.php?route=extension/extension/info&extension_id=3302

It only asks you for 3 installation steps without any coding work to make your dream become true! =)

Drupal plugin for it will be alive soon.


Query method not triggered in custom filter handler?

As suggested by todinov, you can use Drupal contrib modules Date along with its sub module Date Views which will most probably handle any kind of filter in Views. If it doesn't help, you can achieve it through code by implementing hook_views_query_alter.


You need enable the basic page link in admin/structure/menu/manage/navigation. I think this might be the problem


How do I set my views to return a 404 using Global: Null under contextual filters?

In Contextual filters select Add; in the dialog box that appears, select Global: Null.

Click on Add and configure contextual filters.

In the dialog box that appear next, in the fieldset When the filter value is available or a default is provided, check Specify validation criteria, select - Basic validation - for Validator, and select Show "Page not found" for Action to take if the filter value does not validate. In the fieldset More, check Fail basic validation if any argument is given.

I tested it with an "Articles" view I created, and it works.

The "Global: Null" argument must be the last one. If you need a user ID, for example, first you add it as argument, and then add the "Global: Null" argument.

I altered the "Article" view to accept a user ID as argument, which is used to filter the list of article nodes. The view still works, as it doesn't accept an extra argument.


Listing Active Members of Current Group in View pane (OG 7.x-2.3)

In retrospect the answer was rather obvious. When you migrate from OG 1.x to OG 2.x, the views associated with OG do not get updated. So they have "missing/broken relationships." For most of the view panes it was easy to fix by going to the view page and under the "edit view name/description" drop down, there is an option to "Revert View". Choosing this fixes the views that come with OG because it "reverts" the view to the updated OG 2.x code. Custom views have to be rebuilt.


Or just edit comment.tpl.php in your template files. Copy comment.tpl.php to your template folder and if not present in the code, add $author name and desired text.


Replace the underscore characters with hyphens, and clear the cache.

The template filename should be views--view--taxonomy--term.html.twig.

   function mediumish_blog_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
      if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
       $term = Term::load($tid);
       $suggestions[] = 'views__view__taxonomy__term';
     }
   }


How to save the image of a node to the custom directory programmatically?

You have to use following module https://drupal.org/project/filefield_paths . then you can add tokens for it .


How do I prevent Drupal raising a segmentation fault when using a Node.js theming workflow?

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

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

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

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

unsafe-perm = true


Use taxonomy_get_tree instead, it takes vocabulary ID as the first param, and the term ID under which to generate the tree - this should give you all children of a term.

More info here.


What am I doing wrong when trying to set the default value for this radio button form element?

The #default_value is the key in the $options array. you want:

'#default_value' => 'no',


I installed the Civicrm module on drupal but it s not showing in the navigation bar

Installing the CiviCRM module on Drupal requires a few more steps than just enabling the module itself. Check out how to do this in the Drupal Installation Guide for CiviCRM for the version you're using.


How to make an existing content type a product in Ubercart 3 and Drupal 7?

Have you simply tried to put the machine name of your existing content type in Class ID, and its human name in NAME ?

I've had such problem 3 years ago, and I solved it so. More, for tests purpose I've just created a foo content type. Then I added the Class ID foo, and it has been mapped with foo content type.


What may cause "An illegal choice has been detected. Please contact the site administrator"?

I would say that this means that the user has selected term 423 for term_node_tid_depth_1 and 427 for term_node_tid_depth, but those values are not actually options in that field.

Usually the way this happens if you have custom code that sets the field value to an invalid value, or if it changes the field and removes some of the possible allowed values.

You say it doesn't happen when you are the admin, so I would guess that the admin has access to all the options in the field but other users are just seeing a subset of the field values, but somehow are still setting the field to one of the values they aren't allowed to see.

Do you have any custom code or are using any unusual field or forum related modules?


How is password hashing/encryption performed?

Why does Drupal 8 use PHPass / sha-512?

PHPass was originally implemented in Drupal 7, with custom code in order to use sha-512 instead of md5 which was used by other implementations at the time, and then ported to Drupal 8.
Drupal 8 originally supported older versions of PHP where the password functions were not available, and didn't yet use composer to adopt an existing polyfill.
It was (and still is) a low priority to update the hashing service after it was initially ported from Drupal 7.

Would it be difficult to use Blowfish instead?

There's a module for that - as mentioned in the issue you linked the PHP Password module replaces the core service with one that understands legacy hashes, but will upgrade them to bcrypt when possible.


Save multi value in multi value field programmatically

As per my understanding you are trying to create a new article content type with multiple images. Assuming that you have the path of the images. In Drupal 7 you can use the below code

  $node = new stdClass(); // We create a new node object
  $node->type = "article"; // Or any other content type you want
  $node->title = "Article title";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  //$node->path = array('alias' => 'your node path'); // Setting a node path
  node_object_prepare($node); // Set some default values.
  $node->uid = 1; // admin id
  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field
  // Add images
  $image_limit = 5;
  $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );
  for ($i = 0; $i < $image_limit; $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      $node->field_multiple_images[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign image
    }
  }
  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid
  drupal_set_message('article  saved !!!');
  watchdog('info', 'Article node created');


Unable to go to administration pages (access denied)

I recommend you to do the following:

backup your database
truncate drupal cache tables using phpmyadmin ui or from mysql command line
truncate role_permission table using phpmyadmin ui or from the mysql command line
try to login using super administrator, the user with id 1
if nothing change with you, try to install another drupal project and see if you get the same error messages; maybe you have an issue with your php version or configuration.


Sounds like a permission issue.

If you're using ubuntu, make sure the user owner for your modules folder is www-data and 755 permission.

Also, don't forget to run update.php by going to www.yourwebsite.com/update.php after you update drupal core OR any module.


How can I access the main menu in template_preprocess_page?

Remember your menu can be a block, and to render it, you just have to load and get its view in a preprocess function.

THEME.theme file

use Drupal\block\Entity\Block;
function THEME_preprocess_page(&$variables) {
  $menu = Block::load('id_main_menu');
  $variables['main_menu'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($menu);
}

page.html.twig

...
{{main_menu}}
...

Attention
You must create your block 'main_menu' in somewhere, (module install, block structure page...)


Views pagination based on taxonomy terms

I can't really understand why dates are stored as taxonomy terms, but yes, you can solve your task with powerful plugin system of Views. You should create custom views pager, which adds specific conditions to Views query.
The best example is an article by Views author Earl Miles: Creating a Date Pager Plugin for node "created" field (wow! dates, too).

  As an example, we’re going to create a pager plugin that is somewhat useful, and completely non-traditional for Drupal. You have, however, very likely interacted with a pager of this nature before. Instead of relying on the number of results, we’re going to rely on the post date of the content...

The code is avalible in Views plugin examples module.
Your task is more complex and, of course, requires professional skills.


You can change filter view settings. goto admin/structure/views and edit your views and follow the screenshots


Best way to add a wrapper  to selected fields in a content type

Maybe the Field Group module is what you are looking for? According to the documentation, it provides many kind of wrappers.

Hope that helps,


composer install will not install php; go ahead and follow the instructions in the Drush README for the composer install, and you should be fine.

Note also that Drush master (Drush 7) will soon require php 5.4, so you should use Drush 6 if you'd like to stick with php 5.3.

I don't have a FreeBSD system to try this on, but composer global require drush/drush:6.* works fine on my Linux box.  If you have problems with the composer install, you might want to try composer self-update, to insure that you have a recent version; I can't imagine why FreeBSD should be different than Linux when finding and installing Drush.


How to programmatically change the weight of children in a taxonomy vocabulary?

Change the weight property on the term object.

$term = taxonomy_term_load($tid); //$tid = your taxonomy term id
$term->weight = 10000; //Whatever weight value
taxonomy_save_term($term);


Using theme_username() with no link to user page?

theme_username() will only output the username as a link if the link_path variable has been set. This is done by default in template_preprocess_username(), and will happen as long as the user viewing the username has access to view the profile.

If you want to change that behaviour you just need to add your own preprocess function which removes the link_path variable:

function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path'])) {
    unset($vars['link_path']);
  }
}

Bear in mind that the above will remove the link system wide. If you want to remove just for this specific instance, I think the best way would be to pass a custom variable to the theme function and check for it in your preprocess function:

$vars = array('account' = user_load($record->uid), 'surpress_link' => TRUE);
$name = theme('username', $vars);

function MYTHEME_preprocess_username(&$vars) {
  if (isset($vars['link_path']) && isset($vars['surpress_link']) && $vars['surpress_link']) {
    unset($vars['link_path']);
  }
}


wget https://github.com/metaskills/less-rails-bootstrap/raw/master/app/assets/fonts/twitter/bootstrap/glyphicons-halflings-regular.woff2
and move it to the openatrium/themes/oa_radix/assets/font directory.
Here: https://www.drupal.org/node/2625784


Why node export:import link is not displayed?

Go to node/add/node_export (Content > add content > Node export: import) and paste the code or load from file.


Acquia cloud installing a module: private key file

The solution was to forget about Acquia and start using cPanel.

In here, was as straightforward as creating a subdomain, taking advantage of Softaculous scripts by installing in that location the 8.4.3 version of Drupal.

Once installation was complete (which was a matter of seconds) and I've logged in as admin, installing a module was never easier!

See for yourself:

Tiago


Why is redirect after login not working?

You can use this hook:

/**
* Implements hook_user_login().
*/
function my_module_user_login(&$edit, $account) {
 // $edit is empty with one time login
 if (!empty($edit)) {
   $_GET['destination'] = 'some-url';
 }
 // Or the form id is the password reset form
 if ($_POST['form_id'] != 'user_pass_reset') {
  $_GET['destination'] = 'some-url';
 }
}


Can you create a script to programatically run update.php on multiple drupal sites

I've written a similar script on a 50+ site multisite install. You want to use the command line powertool drush for this, and then run the command

drush updb

from a shell script, ex:

cd /var/www/site1-environment/
drush updb --uri=http://site1.com
cd /var/www/site2-environment/
drush updb --uri=http://site2.com
... etc

Of course if all of these sites are in the same multi-site structure than you won't need to repeat the cd command in your shell script.


How can I update content automatically every X hours?

This can be completely driven by Views & Views System Message module.

You can create a block view for node content of type XXX that has an added Filter Criteria Content: Updated date with the Operator set to Is less than or equal to and the Value type set to an An offset... of "-5 hours" Value. That will get you a block view of content XXX that was edited more than 5 hours ago.

The last part, the alert message, can be added in the Header area by selecting the Global: System message type and setting the parameters to your liking. Once the block view is saved, you can add the block to whatever region you feel most appropriate.


oderid sort not work correclty in number more than 1000 in commerce_orders views

As you can see in commerce_order_schema, order number is not a number, it's a string:

'order_number' => array(
    'description' => 'The order number displayed to the customer.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ),

This means that your view works as designed, sorting this text field that accidentally contains numbers alphabetically. Which, again accidentally, gave you illusion of numeric sort when numbers was in [100-999] range.

If you need something that's guaranteed to be numeric and ordered the way orders was placed, use either order_id ('type' => 'serial') or created ('type' => 'int').


Syntax for referenced variables in hook_commerce_physical_order_weight_alter?

If your hook_commerce_physical_order_weight_alter is not fired (remove if to double check that it's not), check if commerce_physical_order_weight() is fired as alter hook is right at the end (so add dpm() or die() at start of the function):

    function commerce_physical_order_weight($order, $unit = 'lb') {
      // ...
      // Allow other modules to alter the weight if necessary.
      drupal_alter('commerce_physical_order_weight', $weight, $order, $unit);

if it is not fired, that means the problem is somewhere else, so check if commerce_physical module is enabled and configured properly and you've the right dependency to it,
if it is fired, then check that:

your module is exactly called add_shipping_weight,
the module file included (add hook_init() or die() to check)
clear your caches (Drupal caches, memcached/redis if used, etc.), so list of hooks can be updated (it's a common mistake)


How To get transaction details in commerce checkout complete page

In general, for Drupal 7, you could do the following:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function  MODULE_form_commerce_checkout_form_complete_alter(&$form, &$form_state, $form_id) {
  $order_id = $form_state['order']->order_id;
  // Use the entity field query to get transaction entities.
  $query->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order_id);
  $result = $query->execute();
  if (!empty($result) && !empty($result['commerce_payment_transaction'])) {
    // Load the Payment Transactions
    $transactions = commerce_payment_transaction_load_multiple(array_keys($result['commerce_payment_transaction']));
    $form['payment_status']['#markup'] = '
' . t('Payment Pending') . '
';
    foreach ($transactions as $transaction) {
      if ($transaction['status'] == "success") {
        $form['payment_status']['#markup'] = '
' . t('Payment Received!') . '
';
        break;
      }
    }
  }
  else {
    $form['payment_status']['#markup'] = '
' . t('Error. No Payment Transactions.') . '
';
  }
}


form auto complete how to restrict results by previous drop down

Using the links suggested from Anil Sagar, I put together this solution using Ajax.

function HolidayAutosXML_carsearch_form($node, &$form_state) {
  $country_list = _get_country_list();
  $form['country'] = array(
    '#type' => 'select',
    '#title' => 'Select Country',
    '#description' => 'Select the country where you want to collect the car',
    '#options' => $country_list,
    '#ajax' => array(
      'callback' => 'update_officename_autocomplete',
      'wrapper' => 'haofficename',
    ),
  );

  $form['officename'] = array(
'#type' => 'textfield',
'#title' => t('Location'),
'#default_value' => $form_state['office name'],
'#size' => 20,
'#maxlength' => 50,
'#description' => t('Select the location where you want to pick up the car'),
'#attributes' => NULL,
'#required' => TRUE,
    '#autocomplete_path' => 'location-autocomplete',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (!empty($form_state['values']['country'])) {
    $form['officename']['#autocomplete_path'] = "location-autocomplete/{$form_state['values']['country']}";
  }

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

  return $form;
}

I added an Ajax element to the country drop down, telling it to look for a
 with an ID equal to "haofficename" and calling a function named update_officename_autocomplete().
I used a prefix and suffix element in the office name element to wrap it in a
 element with the ID haofficename, which Ajax is going to look for.
update_officename_autocomplete() simply returns the altered office name element of the form. if you look inside the if statement you will see that it is adding to the #autocomplete_path property. So I had to add a second parameter to my autocomplete function. This function now takes $country and $officename.

function location_autocomplete($country,$string){
   $matches = array();
   $result = db_query("select officename from {holidayautos_country_list}        where officename like :keyword and country = :country limit 0, 10",  array(':keyword'=>"%" . db_like($string) . "%",':country'=>$country));
  foreach($result as $row) {
  $matches[$row->officename] = check_plain($row->officename);
  }
  drupal_json_output($matches);
  }

It works like a charm.


The only email header field that can be replaced is the Reply-to field?

Not long after posting this question I found a working answer here
The problem can be solved programmatically using hook_mail_alter,


Custom validate exposed filter on a view

Another approach is to use hook_form_FORM_ID_alter() like other answers suggest, but to put custom validation before the default validation callback of views. By this way you can stop to step over to the second validation callback if validation fails, otherwise validation continues to process.. Example:

function MY_THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-MY_VIEWS_NAME_MY_VIEWS_DISPLAY') {
    array_unshift($form['#validate'], 'my_custom_validation_callback');
  }
}

function my_custom_validation_callback($form, &$form_state) {
  if(/* CONDITION */) {
    form_set_error('user_category', 'please enter a value');
  }
}


Views: How to display a grouped taxonomy list with node count?

It has been a while since I've done this, but I recall doing it with Views and setting the Taxonomy Term as the argument and using the Glossary option.

Alternatively, there are several snippets for doing this type of thing, as I recall. You can find a few of them here:

Show a list(x) of taxonomy terms with node counts
Drupal API - taxonomy_get_tree (or for D7)

In both cases, check the comments for various implementations or tweaks to functionality.


Which settings to use in hook_field_formatter_view?

This wasn't really a problem. This was because the page was a Panels page, and the field was added into the panel page with its own formatter settings.

Solved by setting the correct field formatter settings on the panel page.

It's one of d'ohs days.


Previewing a view does not show a phone number but when I look at the view by visiting the URL of the page it does?

They most likely modified a tpl.php file.  In the Views module when you are viewing to edit it, look for Theme: information and click information.

You will then see a list of possible tpl.php files.  If you see one that is not in the first position and bold, then you know they did some type of override on the tpl.php.  Look in the theme folder for that file name.

If its not in there, then you will want to look at your themes template.php for some type of override.  Finally, some people will put these overrides in a utility module.


How to open a new form in a block without reloading whole page?

You need to set the "Redirection Location" to "No redirect (reload current page)" in actual webform settings (/node/x/configure). This will show the confirmation message in block without reloading and provide a link "Go back to form" which will reload your form by ajax.


Change the front page based in the screen size of the visitor?

The responsiveness of Omega uses CSS3 Media Queries, which are totally client side.  The other thing to think about is that with true responsive design, the viewport of the client can change while viewing a single page, and the page should adapt.  For example, you can load a page in Chrome, and resize the browser window, and go through the narrow/normal/wide changes and see how responsive your site is.

My suggestion is to make your front page so you employ Progressive Enhancement and not Graceful Degredation.  Design the page so that it works well for users without Flash or Javascript, and make it responsive.  Then, when the page loads, have some JS that checks the browser width, and then use SWFObject to add in the Flash content using the dynamic method.  Depedning on your situation, you may want to add in some min-width and/or display: none on the Flash <div> in the narrow/normal/wide sheets to handle viewport changes.


Have you looked at the "Glossary" view?  It is a sample view included with the views module that lists all site content by letter in a manner similar to the link you listed.

The "Glossary" view is disabled by default, but you can enable it on the views admin page (admin/structure/views).

The settings for sorting the posts in the "Glossary" view can be found on the views edit screen under Advanced-> Contextual Filters-> Content: Title.  If you click Content: Title, under "More" you will find the option to use upper or lower case when sorting the view.


Setting entity reference field value in Drupal 8 programatically

If you are creating a node with reference field, see below code:

 use \Drupal\node\Entity\Node;
 $node = Node::create([
   'type' => 'post',
   'field_post' => [
     'value' => 'test',
     'format' => 'basic_html',
   ],
   'field_pattern' => [
      'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
   ],
   'field_visibility' => 1,
   'user_id' => $uid
 ]);
 $node->save();

If you are are not creating node then just replace your field_pattern like below:

'field_pattern' => [
   'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
],


How to Update Commerce Product Programatically

You may have better luck using entity metadata wrappers' ->set() and ->save() functions.


console.log() renders elements as "D.fn.D.init"

After a bit of digging around I managed to reproduce this on a couple of dev sites and I think I've narrowed down the problem.

The issue seems to be with the number of elements being passed to console.log.

This is what the output looks like with 100 <div> tags on the page:

And this is what it looks like with 101 <div> tags on the page:

So it seems either jQuery or console.log is imposing some sort of limit on rendering the output. I don't have time to look into it but my hunch would be that console.log is responsible for that.


User anonymity while using user_external_login_register()?

Would it be sufficient to hash the username and/or password through something like sha1()?

You then wouldn't be storing campus data locally, as the hash is one way.  You'd still be able to check against it later as Drupal would store the hashes.


You can do this using CSS

Firstly you will want to create your own theme using bartik as a base.

Copy /themes/bartik to /sites/all/themes/YOUR_THEME
Rename bartik.info to YOUR_THEME.info
Edit YOUR_THEME.info, Make Changes, name = YOUR_THEME, description = YOUR_DESCRIPTION
Edit template.php replace all instances of 'bartik' with 'YOUR_THEME'
Goto /admin/appearance
Find YOUR_THEME Enable and set default.

Why do we do this? Never hack the core or contributed modules and themes, If you do, updates will be a nightmare.

Now you will need to find the "id" of the menu element. In Chrome right click on the menu and 'Inspect Element' you may need to click up and down in the code window to find the relavant container. Example: id='block-system-user-menu' for the user menu block.

Modify /sites/all/themes/YOUR_THEME/css/style.css I will use 'block-system-user-menu' as an example.

Add this code (depending on your id).

#block-system-user-menu li,
#block-system-user-menu ul.menu li a {
  border:none;
}
#block-system-user-menu ul.menu li a {
  float:left;
  border-right:1px #fff solid;
}
#block-system-user-menu ul.menu li.last a {
  border-right:none;
}

That's it done!

You could also use the superfish module at http://drupal.org/project/superfish This will allow you to have a horizontal menu from any of your menus with some default styling or the ability to style it yourself in the same way as outlined above if you prefer. It is also an easy and clean way to get drop-down menus on your site.


The issue was connected to this: https://www.drupal.org/project/paragraphs/issues/2914259

I am not quite sure what exactly was the problem but when I went to the status report page I realized the error message

Entity/field definitions
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Paragraph

- The Published field needs to be updated.

I implemented the update function

_update_function() {
  try {
    $entityUpdateManager = \Drupal::service('entity.definition_update_manager');
    $entityUpdateManager->applyUpdates();
  }
  catch (EntityStorageException $e) {
    print_r($e);
  }
}

run update and the problems with the aggregated css disappeared.


There's three places where you can put your Javascript resources:

Your theme folder. If you have a theme in your site named Mechaflash, you could put it inside Mechaflash/js or just in Mechaflash. In order to make the theme folder "more organized", generally people create a dedicated js folder. I would place Javascript in the theme when your Javascript delivers functionality specific to the theme / presentation layer, or that it affects all of the site (global).
In one of your custom modules. The same principle of creating a dedicated js folder can also apply here. I generally put JS on the modules when the Javascript is delivering a very specialized functionality relevant to a specific module. It also allows you to "package" your Javascript with your modules and to pass this modules to other sites (i.e. a modular approach).
In the site's library folder. I've never done this personally. Not because it's bad, but because I think it's reserved for more complex functionality that other modules (and themes) can use. A good example, the JQuery UI library.

You can do all of this using the drupal_add_js() function. Here are some examples of how to add a JS file from a module:

// Add a "javascript library" from your module. JS_LIBRARY is an integer constant with a value of -100, which means that `mecha_library.js` will be added before `mecha_ninja.js`.
$module_path = drupal_get_path('module', 'my_module');
drupal_add_js($module_path. 'js/mecha_library.js', array('group' => JS_LIBRARY));

// Add a javascript file from your module. The default 'group' here is JS_DEFAULT, so mecha_ninja.js will be added after mecha_library.js.
$path = drupal_get_path('module', 'my_module');
drupal_add_js($path. 'js/mecha_ninja.js', 'file');


Image preview thumbnail does not display

Try removing any space, empty line before

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

Hope this helps.


The hooks/functions you shown for the .module file can be removed, since Drupal 8 doesn't use hook_menu(); therefore, Drupal will not use the littlurl_forward() function defined from the module.
The code in the Controller.php file needs to be rewritten for Drupal 8, since:

It should not access $_GET['q']
Instead of drupal_goto(), it should use the redirect() method of the controller

The first point means you should have three different methods you assign to the three different paths, which makes also more sense. It doesn't sense to assign the same method to three different paths, and the method then still need to understand for which path is being called.
As side notes, keep in mind that:

If you are editing a module that is already installed, or any of its files, you need to uninstall it first, since Drupal keep in a cache the list of hooks the module is implementing

The method of a class should not be named like lower_case(), but camelCase()

From the code you are showing, it seems you are redirecting from n to node; if that is the case, then you can simply use a path alias

If instead you are redirecting from /n/node-id to /node/node-id, then it is probably better to use the Pathauto module which creates path aliases for nodes, taxonomy terms, and users (and lets you decide which pattern to use for those path aliases)

If the routes you are defining get arguments, you should define them in the routes, such as /n/{node}

If all the routes are doing is allowing to use /n/node-id instead of /node/node-id, I don't see much of a reason to write the code just for that


Essentially, you want a hierarchical 'drill down' through taxonomy to narrow a search? If I'm interpreting this correctly, you're looking for something like Hierarchical Select, a module that does just that in the form of an input widget. I don't have personal experience with the exposed filter implementation, but it sounds like it exists.

http://drupal.org/project/hierarchical_select

http://drupal.org/node/720268


You simply can’t style a checkbox (+ radio + select) via CSS. You’ll have to include another jQuery plug-in to achieve your goal. Something like uniformjs. Hope this helps and answers your question.


Output all possible items in a list field as a View?

My own answer (but still feel free to chip in):

Create a View of the Content Type containing the list.
In the FIELDS section only have your Content Type Field that contains the list Content: (whatever the name of your list field is called)
Click on your Content Type Field under FIELDS for the 'Configure field: Content: Your field' Under Multiple Field Settings, make sure display multiple fields on one row is unchecked
add your Content Type Field to the FILTER CRITERIA. Filter should be set to 'is not empty' / not null
over to the right hand side of the Views settings, enabled Aggregation
back to FILTER CRITERIA and click Aggregation Settings for your content type field and select COUNT DISTINCT.

What this does is produce a unique list of items from all of the content that has this field with those items checked.

What it won't do is show items in from the list field if they have not yet been selected in any content.

It may also have a performance overhead to generate the list like this as it is based on the data from the entire set of content. The positive benefits flipside of this is that perhaps you only want to see items where there is content that has it checked and you may want to extend the list to include number of content using a list item.

Final thought - why did I not just use a taxonomy? this would have been far easier and Views supports this better. Reason: currently (at the time of writing), Views does not support context filtering on taxonomy where multiple arguments are provided in the URL. I want to use this list from this View as a menu block to filter data in a View in another block in Panels from multiple fields.

References / Credits:

How do I remove duplicates when using the random sort?


How to add template suggestions for entities?

I found a solution. The Entity API module defines template_preprocess_entity() such that you can add template suggestions during your own preprocessing in a custom module, like for example:

function mymodule_preprocess_entity(&$variables) {
    if($variables['elements']['#entity_type'] = "myentity") {
        $variables['theme_hook_suggestions'][] = "myentity";
    }
}

This runs preprocessing for custom entities built off the Entity API, but not for not nodes or entities built into Drupal core. In order to add template suggestions for Drupal core entities, you need to add it while using the various entity-specific preprocessing hooks provided in Drupal core. For example:

// Preprocessing for taxonomy terms
function mymodule_preprocess_taxonomy_term(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for user profiles
function mymodule_preprocess_user_profile(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for comments
function mymodule_preprocess_comment(&$variables) {
  // Add template suggestion code here.
}

// Preprocessing for nodes
function mymodule_preprocess_node(&$variables) {
  // Add template suggestion code here.
}


There is not any option in views module to add metatags. but you can add metatags to any url of your site by other drupal metatag modules.
See How to define Meta tags on Views?.


Some tags in the output from my controller are filtered away

That is behavior Drupal 8 has for the #markup property, as described in Render API overview. It is different from the behavior Drupal 7 had; if you are converting code from Drupal 7, you need to change that part of the code accordingly.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed_tags to alter which tags are filtered.

The highlighted part tells you how to solve the filtering of tags.

See also the next part of the documentation.

  #allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that Xss::filter() would accept. If #plain_text is set this value is ignored.


Is there a way to check user permissions in javascript?

It is not secure to only rely on Javacript. It is better to separate that .js function which needs permission to execute from other codes then put in a file and load that .js file from your hook_preprocess_page if the user has permission (or some role). I implement this idea with user roles, you may use another strategy for checking the permission.

function THEME_preprocess_page(&$var){
      global $user;
      if(in_array("SOME_ROLE_NAME_WITH_ACCESS_TO_JS_FUNCTION",$user->roles))
            drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/Your_js.js');

}

in your theme directory, I supposed you placed your .js files in /js directory. So you should create Your_js.js file in that directory and put that function inside it. If the user has appropriate role, that file with that function in it will be loaded and you can use it later, otherwise it won't.


How to implement question/answer functionality with following feature?

Well, while the Answers module does not support this entirely, it does provide some helpful functionality. (FWIW, this has been an open feature request for some time. I haven't gotten around to it ... but if you end up implementing it, I would love to integrate it.).

In particular, the Answers module allows you to programmatically "lock" questions, meaning additional answers are not allowed. You can also extend the module with the Best Answer module (which, naturally enough, enables question authors to select a Best Answer). The Best Answer module already provides an administrative setting which, if set, means that questions are automatically locked after the question author selects a Best Answer.


Show fields of content type B while keeping filter criteria as content type = A in view

You need Entity Reference, In your Article content type, create the author field as an entity reference field and refer it to the Author content type. After that you can create a view and add a relationship of Entity Reference and you will get the related fields. For further read, refer here


Email sent to customer from Drupal has RED LOCK icon in the email

I've read both your questions regarding this issue posted here. IMHO the red lock is not a thing you can overcome by encrypting the contents of your mail before sending it via an unencrypted channel.

This issue is not directly connected to Drupal, but to your Drupals mail gateway. Obviously your mail relay is not supporting TLS mail forwarding.

I do suppose you are sending the mails using Drupals built-in mail functions. These functions do use the PHP mailing functions, which by default are set-up to use your hosts mail services.

If you are working with a root server and installed your mail server yourself (e.g. postfix on Unix), you have to digg into its configuration and make sure it is set-up to use TLS when connecting to other mail servers.

When you don't have direct access to these settings (e.g. on a shared hosting package), you can overcome this issue by creating a mail account with a third-party email provider that is using TLS (e.g. gmail itself). With this mail account you will also get SMTP credentials to use for sending mails from your desktops mail client.

In your Drupal, you can install and configure the SMTP module to use these credentials for letting Drupal send mails via this external mail provider. Please note that some mail providers have flood mailing prevention in place that do allow a certain amount of mails each time/per minute only. So you might additionally consider using Queue Mail and a Cron job to send your mails in batches.

Edit:
Drawback of the second solution is, that the mails received by your sites visitors may have been flagged as "x-forwarded" or have the third-parties mail provider email address as sender. Some mail clients therefore may mark the mails as spam.

So another solution for shared hosting: Ask your hosting provider to change the default mail server settings.


exposed filter default values from user fields

Try like this.

function custommodule_form_views_exposed_form_alter(&$form, &$form_state){
  if($form['#theme'][0] == 'views_exposed_form__article__page_1'){
      $form['ct']['#options']['All'] = 'All Article';
  }
}


You're looking for the EntityFieldQuery class:

$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_my_field', 'value', 'a_value')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_my_field', 'value', 'DESC');

$results = $query->execute();
if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $nid => $node) {
    // Do something with the node object
  }
}

The above code loads all node entities with a content type of article. It filters on a custom field called field_my_field and the status property of the node. I only put that in for reference you wouldn't need it to load all nodes without any filters. Same goes for the order by statement.

Hope that helps.


Unable to retrieve value from settings file inside custom module

You need to put this file into

  myModule/config/install/my_module.settings.yml

Then uninstall and reinstall.

You ll get your value.


Delete user account after checkout completion

Deleting a user after checkout is a bad idea. I assume you know this, but the client is asking/forcing you to do this.

check this link - automatically delete all Ubercart-created users,  this has a solution.


The problem here is that in the given file, the line

$field['settings'] += field_info_field_settings($field['type']);

fails (i.e line 479), because field_info_field_settings() doesn't return an array. This shouldn't happen and it is probably caused by a custom or contrib module or by faulty data in your database.

You can try to trace the error down. Open field.info.class.inc in a text editor and put the following code directly above the line 479:

$field_settings = field_info_field_settings($field['type']);
if (!is_array($field_settings)) {
  print_r($field);
  die();
}

Then load a page where you would normally get that error and look at the printed details (I hope there are any). Then ask yourself the following questions:

For which field are the settings requested?
Does this field still exists?
Is it a field declared by a module that you have disabled?

This should help you to trace down the problem.

Remember to remove the debug code!


There are already existing modules to do it like mobile_tools. Where u can set what theme to use for mobiles. and redirection on mobile detection also.


Using webform rules to create node after webform submission

You should use Rules module in the following way:

Install and enable Rules module
Install and enable Webform Rules (https://drupal.org/project/webform_rules)
Create a new rule
Choose the "After a webform has been submitted" event
Optionally set your conditions
Add a new action "Create a new entity" of type "Content"
Add the neededs action to add properties to the created entity
Add the save action

I hope this helps.


You may want to add a filter for Content  Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the 'User's Current Language' is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Does this help?


How do I assign a specific role to each newly registered user?

I had to implement a similar feature in a site, where:

Users are not required to verify their email address
When users create an account, they get the unverified account role
Once the users verify their email address, the unverified account role
is removed, and they get a confirmed user role

It is pretty similar to what drupal.org does nowadays; I am just using different roles, and custom code that is different from what drupal.org uses.

I didn't use the Auto Assign Role module, since there isn't a working version for Drupal 8. I didn't use the Registration Role module, since it adds the roles to every account being edited, including the accounts with the administrator role.

I used a custom module (which I was already using for other purposes), where I implemented hook_ENTITY_TYPE_presave() with code similar to the following one.

function mymodule_user_presave(UserInterface $user) {
  if ($user->isNew() && !$user->hasRole('unverified account')) {
    $admin = FALSE;

    foreach ($user->getRoles(TRUE) as $id) {
      $role = Role::load($id);
      if ($role->isAdmin()) {
        $admin = TRUE;
        break;
      }
    }

    if (!$admin) {
      $user->addRole('unverified account');
    }
  }
}

hook_ENTITY_TYPE_insert() and hook_entity_insert() are the wrong hooks to use, since they are invoked when the entity is already saved in the database. Calling the save() method on the entity passed to those hooks will cause all the hooks invoked when an entity is saved to be invoked again, causing an infinite loop.


Add parameter to the URL based on a field value

Don't know if it fits for your use case, but I wanted all outgoing links from a specific node type to have the ID appended, e.g. on every product page all outgoing "Call to action" links should appent something like ?from_product_id=1234. My module name was 'wt_ctalinks`

wt_ctalinks.services.yml

services:
  cache_context.wt_ctalinks:
    class: Drupal\wt_ctalinks\CtaLinksCacheContext
    arguments: ['@request_stack']
    tags:
      - { name: cache.context }
  wt_ctalinks.ctalinks_pathmodifier_service:
    class: Drupal\wt_ctalinks\CtaLinksPathModifierService
    arguments: ['@request_stack']
    tags:
      - { name: path_processor_outbound, priority: 3000 }

src/CtaLinksCacheContext.php

<?php

namespace Drupal\wt_ctalinks;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;

class CtaLinksCacheContext implements CacheContextInterface {

  /**
   * @var Symfony\Component\HttpFoundation\RequestStack;
   */
  protected $requestStack;

  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
  * {@inheritdoc}
  */
  public static function getLabel() {
    drupal_set_message('Modify CTA links based on current node type');
  }

  /**
  * {@inheritdoc}
  */
  public function getContext() {
    $nid = 0;
    $request = $this->requestStack->getCurrentRequest();
    $node = $request->attributes->get('node');
    if (is_numeric($node)) {
      $node = Node::load($node);
    }
    if ($node instanceof NodeInterface && $node->bundle() === 'article') {
      $nid = $node->id();
    }
    return $nid;
  }

  /**
  * {@inheritdoc}
  */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

src/CtaLinksPathModifierService.php

<?php

namespace Drupal\wt_ctalinks;
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\config_pages\Entity\ConfigPages;
use Drupal\node\Entity\Node;

/**
 * Class DefaultService.
 */
class CtaLinksPathModifierService implements OutboundPathProcessorInterface {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  protected $bookingPath;
  protected $enquirePath;

  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if (empty($request)) {
      $request = $this->requestStack->getCurrentRequest();
    }

    $node = $request->attributes->get('node');

    if (is_numeric($node)) {
      // missing upcasting in revision view, have to load manually there
      $node = Node::load($node);
    }

    if ($node instanceof NodeInterface && $node->getType() === 'article') {
      // your logic here
    }

    if ($bubbleable_metadata) {
      $bubbleable_metadata
        ->addCacheContexts([
          'wt_ctalinks',
        ]);
    }
    return $path;
  }
}


Creating a custom url when navigating to a custom module form

There are multiple ways.

You could use hook_menu() to declare a new path with the same callback (while still leaving the old one intact).
You could use Redirect module.
You could create a .htaccess redirect. (A 301 redirect is the proper way to do it if you want the new one to permanently replace the old one.)
You could create a new Path Alias.


Pulling content from other nodes into a Panel Node

When you add an Object to your Panel Pane, you will find in the left column the option to add an "Existing node", choosing this, you can add a node id of the content you want to add.

If you want to dynamically provide different nodes provided by the user input on the node form using a node reference field, you need to add a context to the panel by using this reference field and then the referenced node will also be available.


Help with $base URL path in settings.php

All URL will be changed automatically, if u have not provide static URL in it. For further checking what is causing the issue, check your apache log (if your server is Apache2)

cd /var/log/apache2
tail -100 error.log

See the latest error which is showing, or paste it here.


In your .htaccess,

RewriteCond %{HTTP_HOST} www.example.com
RewriteRule ^ http://www.example.net/en [R,L]

Where www.example.com is your old domain and www.example.netis the new one.


After adding new content type, drupal (7) returns to same window without any notification

What do you mean by adding content type?
It Is normal that drupal return to the front page after creating a new content type...

Do you mean creating a node?Where does drupal returns?


Error: Private files directory not fully protected

Submit the admin form @/admin/config/media/file-system will also create this .htaccess file if your folders are setup correct.


How do I get a user field from an entity reference?

You need to use the action: Fetch entity by property.

Condition: Entity has field > node: field_office_sms
Fetch entity by property > User > Property: field_user_office > Value: node: field_office_sms:nid
Loop: List: [entity-fetched]
Action: Send SMS > list-item: field_mobile_phone


Add mini pager and infinite scroll to a view

You're description is a bit ambiguous because first you write

  Now after showing four items, 'load more' has to change to ' show less' and hide all four items

but then below you write

  Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

Sounds to me like once there are 4 items displayed, you want to have a show less AND a next button to be displayed?

What's safe to say though, is that you can't get that show less button using views infinite scroll.

I'd probably try to add pagination using views infinite scroll that shows/loads additional 4 items when you click the load more button. The show less button you'll probably have to implement as custom JS wrapped inside a Drupal behavior .

You may also consider to override the JS behaviors of the views_infinite_scroll module to achieve the show more/show less functionality if it's not possible in a custom behavior because you depend on views_infinite_scroll's JS code to run first or so


How to find the view/page/module that's generating a SQL statement

I suspect your logs are are the output from the MySQL Slow Query Log.  What ends up here varies based on server configuration, but they general culprits are

Queries that take a long time
Queries that don't use indexes

My suggestion is to try to match up the timestamps (start time) to the Apache access_log to get a page.  Then, use the Devel module and enable "Display query log" from admin/config/development/devel.  This will record queries and log them along with execution times.

It looks like that bad query is tied to a view.  For these, enable "Add Views signature to all SQL queries" on the Advanced settings page.  When you do this you can identify which view is slow.

To resolve the "slowness", copy the query and hand edit to add in the parameters.  Then open a MySQL tool, and use the EXPLAIN statement.  Look at what it tells you and go from there.


The issue was memcached, apparently variables were cached in the service. Once the memcached service was rebooted the issue disappeared.


Is it possible to add form elements to the existing fields with Field API?

File Entity module allows you to add extra fields to file fields.

  File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters.


By default the logs are saved at /admin/reports/dblog for which the dblog module in the core is responsible. More about dblog : https://www.drupal.org/docs/8/core/modules/dblog/overview

You can also have the logs stored on the file system by enabling the syslog module (also in core). More about syslog : https://www.drupal.org/docs/8/core/modules/syslog/overview

It is recommended that you should not use the dblog module if you need to log messages more frequently as it does a write operation to the database.


I can't see any issues with your code, and this might be a dumb answer, but a while back I was having trouble with chaining together entity query conditions. I got everything working by splitting it into individual statements. It didn't seem logical that that should make a difference, but it did. (Though, I'm sure it's possible I had some other logical problem that was the actual issue, and separating into statements was just incidental.) But maybe try...

$group = $query->orConditionGroup();
$group->condition('field_ref1_user.entity:user.uid', $user->id());
$group->condition('field_ref2_user.entity:user.uid', $user->id());

$query->condition('status', 1);
$query->condition('type', 'mynodetype');
$query->condition($group);
$ids = $query->execute();


How to change exposed filter select box style in views

You can use fancyselect module.

Fancy select is a jQuery plug-in developed by Octopus Creative.
This module loads fancySelect jQuery plug-in, which converts simple HTML select DOM elements with a specified CSS class into a stylish select box. You may configure DOM CSS from settings form.


The only permission a role needs in order to create new content for a content type is Create new content.  This permission must be set for each content type you want the role to be able to create content for.

If your user belongs to a number of roles, then it is - in a default Drupal 7 configuration - neccessary that at least one of the roles have this permission granted.  Unless you have some node access module installed that breaks with the Drupal paradigm of grants being accumulative (e.g. Deny Access), then it should not matter if some of the roles the user belong does not have this granted.


How do I redirect a Read More link to another URL in Showcase Image?

You can use the path-redirect module to forward the URL in the "read-more" link to any other internal or external URL.  If you forward internally, you need to use the "node/123" system URL and delete the alias for the node you are forwarding from, before you setup the redirect.

If you point at the read more link you'll see its node or alias in the lower left hand corner of your browser.


Here is a little example, how to make requests in Drupal 6. You may change table name and field name and it should work for you.

$query = db_query('SELECT n.nid, regid.regid_FIELD_VALUE
   FROM {node} AS n
   JOIN {regid_FEILD_TABLE_NAME} AS regid ON regid.vid = n.vid
   WHERE n.type = %s AND n.status = %d, $your_node_type, 1);

$result = array();
while($node_data = db_fetch_object($query)) {
  $result[] = array(
    'nid' => $node_data->nid,
    'regid' => $node_data->regid_FIELD_VALUE,
  );
}