The Search API supports views out of the box.  You just need to create a new view and select the "Index" you want to search.  E.g. Index Full Site or Index Resources.  These match the indices you have created in the Search API setup.

This will let you get any 'fields' in the index and use some Search API specific filters (e.g. Fulltext search which looks across all index fields.).

There are some options that refer to Datasource information.  This is the way you can take information from the index and related it to the full node.  Depending on your needs, you may need to use Relationships to get to other items, e.g files or images.

There are a fair number of tutorials on this, just search for them.


Is it possible to use Apache Solr to search across multiple sites?

Solr can be thought of as a document oriented database , it has a schema based, and a schema-less mode.

When used from the drupal module it uses a schema.xml file to specify what it expects to find in the documents (and hence index).

so if you go down that option one way you could search across the external domain and the drupal site is index the external domain to that schema, extending it where necessary

if you've got a title field in both sets of data , then it will index title that way. if your external site has different fields you could add them to the schema
you'll want to define a minimal shared set that documents from either site share, to make themeing, and UX easier.

The process I would probably go for is

create a schema that covers both sources of data
configure Drupal to use that schema and index the site
index the external site (Solr 5 has a crawler now, or might just be easier to build a CSV file with curl)

that would get you to a place where you can search across the 2 sites from the Drupal search.
It would be a case of getting the theme/markup right to represent offsite vs onsite results.


Captcha on the user_login_form and user_pass form?

You should add captcha to
1. user_login
and
2. user_login_block(instead of user_login_form)

as shown below:


Publish tweets in drupal 7 site in real time

Try Selective Tweets. As written in comparison to another Twitter module (Tweed Feed), Selective Tweets renders Tweets almost realtime:

Tweet Feed does periodic imports of Tweets and turns them into nodes,
while Selective Tweets renders Tweets almost realtime and saves none
of them in the database as content. This is also the main difference,
with the effect that Tweet Feed has a significant delay on the
realtime Tweets. On the other hand, the Tweet Feed created nodes can
be displayed in Views which gives big flexibility in the way of
displaying Tweets.
Use Selective Tweets when you want a light weight
manner of displaying Tweets without database storing and you want no
major delay in displaying realtime tweets.


The contextual links are being exposed via contextual module. just by looking into the module, you would find the function contextual_preprocess.

 $variables['title_suffix']['contextual_links'] = array(
      '#type' => 'contextual_links',
      '#contextual_links' => $element['#contextual_links'],
      '#element' => $element,
    );

So my first guess would be, that you are missing in the block.tpl.php or page.tpl.php, etc... templates to output the $title_suffix variable?

<?php print render($title_suffix); ?>


When you are using this syntax:

$form['submitted']['dia'] = array(

you create a whole new array, with only the values you provided. Old array that was there is simply discarded. If you only want to add or modify 'options', 'default_value', and 'ajax', you need to access them directly:

$form['submitted']['dia']['options'] = $options_first;
$form['submitted']['dia']['default_value'] = $selected;
$form['submitted']['dia']['ajax'] = array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
);


The fix is as follows:

In your php.ini file, increase the max_input_vars to 2000. That should fix the issue with taxonomy terms and blocks too.


Cron not working when called from SSH php curl - Elysia cron module activated

After much debugging (too much debugging, I am afraid), I discovered that the problem was in that the cron did not go through all the steps (bootstrap). The problem (which was not logged) was in the Domain Access module, in which I deleted the English language in one of the domain. IMHO, this is a bug, but not sure if of the module, the core or what. I cannot afford wasting 8 hours of my time looking for errors when I make a simple change that, in principle, should not affect the entire performance of Drupal. This is the kind of things that make Drupal not trustworthy.


what is '#access' => $admin in this code

#access property in Form API is to set whether the element should be visible to the user or not.
If its value is TRUE, the element will not be displayed (not hidden element - #required will not be enforced).
From Form API doc:

  Whether the element is accessible or not; when FALSE, the element is
  not rendered and the user submitted value is not taken into
  consideration.

$admin should be a variable you have forgotten to add/take from where you took the code.

Here is my suggestion to populate $admin variable. At top of the form function, populate $admin:

$admin = user_access('administer site configuration');

user_access function returns (bool) TRUE of the user has the given permission (or FALSE if the current user doesn't). administer site configuration is a general permission that will be usually given to administrators.
You can use whatever permission as appropriate for this.


Send argument to custom field constraint

The method addConstraint allows an optional array of options to be passed to the constraint plugin. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TypedData%21DataDefinition.php/function/DataDefinition%3A%3AaddConstraint/8.2.x


Drush site upgrade: Contributed extensions were not upgaraded

I think you should Migrate d2d module for content migration and also should upgrade contributed modules manually as might be some modules aren't supported in drupal 7. So, this should be a manual task. But using Migrate d2d module, you should be able to migrate content :).

I guess this is helpful to you.


The quick way

and maybe some will call it dirty way would be to add in your THEMENAME.theme file

function THEMENAME_preprocess_html(&$vars) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    // You can get nid and anything else you need from the node object.
    $vars["content_type"] = $node->bundle();
  }
}

and then in your html.html.twig

{% if content_type == "page" %}
  <script> ... </script>
{% endif %}

alternatively

you can just put it in a .js file and include like this

function my_module_preprocess_html(&$variables) {
  // To get around the issue of D8 core escaping inline js we cram our js
  // file into a twig variable for printing "raw" in "html.html.twig" like so:
  // {{ my_module_script|raw }}
  $variables['my_module_script'] = '<script type="text/javascript">' . file_get_contents(dirname(__FILE__) . '/js/script.js') . '</script>';
}

as described in this comment

proper way is probably to

Define a library and then to attach it following this guide


To address the 2nd bullet of your question, consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


The deleted column in a field table is:

  A boolean indicating whether this data item has been deleted

Therefore the only valid values are 0 and 1. Or, at least, 0 == false, and anything else is equivalent, and == true.

You'd need to ask the module developers for their motivation to be 100% sure why they're bucking the trend there and using '2' instead, but maybe it's some sort of hack to exclude certain records from being queried with WHERE deleted = 1, but still available for WHERE deleted > 0. Not sure though, that's just a guess.

As for what it does: it simply marks a record as deleted, so it won't be included in query results, and can be moved into a deleted data table, from which it's subsequently removed on cron runs.


Can I by pass the one time login page that forces a use to click "log in"?

If you look at this: http://drupal.org/node/350634

You could try setting your own function for user_pass_reset: http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user_pass_reset/7


Update customer billing address within custom pane

You can update the field value like this:
  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default');
  $billing_profile = $cart->getBillingProfile();
  $billing_profile->field_name->value = 'Hello World';
  $billing_profile->save();


Modules appear to install, but don't show up

We had this problem recently with a Centos server. If this is your scenario try

# chcon -Rv --type=httpd_sys_content_t ./sites/all/modules

From man chcon change security context, recurse, verbose, type is web content.

Note. Probably a good idea to check what type the files that are working are first.

$ sudo ls --lcontext google_analytics/
-r--r--r--. 1 unconfined_u:object_r:httpd_sys_content_t:s0 apache apache 31504 Jan 15 14:41 googleanalytics.admin.inc


You should be able to do that adding a field to user, say Blog address field_blog_address. Then you can use tokens in pathauto pattern configuration page to set the blog path as [user:field_blog_address].


Display author profile fields in nodes created by that user

1)Go to admin/config/accountsetting then manage field add fields (company name, address  and company name) into it.

2)Go to your content type job add fields (company name, address  and company name) as a existing field not as a new field.find your existing field from the list of available dropdown and select it and save.


How to select files from /sites/default/files with IMCE filebrowser?

Create a new IMCE profile from

  admin/config/media/imce/profile

Don't forget to add the Permitted file extensions and Directories while creating the IMCE profile.


Is the Admin role different than a role with all permissions enabled?

Yes, the user 1 is different in Drupal:

  The Drupal account created during installation (i.e. with user ID or
  UID=1) behaves differently from others. Primarily, it can bypass all
  access callbacks: it has permission to do everything by default.
  Failing to secure this account could result in potential security
  risks. Treat the UID=1 account as you would with root on Linux
  systems.

Source: https://www.drupal.org/node/947312


Display different account fields for my account vs public account

Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

You would want to use the view own value check and view any value unchecked.


When attempting to run drush ": No such file or directory"

I was getting this same error when running drush commands on a remote computer via a drush alias.  I could run the same drush commands  on the remote system directly with no problems but when I would try to run them via a drush alias (@remotesystem) I would get this error.

I found that the user on the remote systems default shell was sh and not bash. Because the bash configuration file ~/.bashrc contains the line that adds the location of drush to the path the sh shell was not able to find drush as ~/.bashrc will not be sourced by the sh shell only by bash.

The drush installation instructions on docs.drush.org state:

  Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).

You can check what your current shell is set to by running:

export |grep SHELL

This will print a line with your current shell in it like this:

declare -x SHELL="/bin/bash"

On Ubuntu the default shell is sh but the default user shell is bash. This happened on a Ubuntu Server install (no GUI).

To fix this change your default shell to bash.

For current users run the following to change the default shell:

sudo -u <USERNAME> chsh -s /bin/bash

For future users, if you use useradd, edit the /etc/default/useradd skeleton file (don't forget to make a backup though). Change the line:

SHELL=/bin/sh

to

SHELL=/bin/bash

This will set bash as the shell for new users that are created.


hook_node_insert() and drupal_goto conflicts with each other?

You can't use drupal_goto() in hook_node_insert() and other node_hooks too. The reason is that there is a queue of hooks that are executed on node insert and if you run drupal_goto() in some hook - all other hooks which goes after will not execute!

If you need redirect user after node insert to some url - implement hook_form_alter for node_form and add new submit callback $form['actions']['submit']['#submit'][] = 'my_module_submit_callback'. In this callback you will get $form_state with all $node fields and you can perform you redirect by specifying $form['#redirect'] = 'some/url'.


How to remove block from the page based on cookie value?

I'll assume this is not a block plugin, right (or at least you dont have access to modify it)? If it is or you can modify it, you should add the logic below to your build() method inside your block class.

Is the cookie you're looking for generated from Drupal? Assuming it is, you should be able to do something like this:

HOOK_preprocess_block__myblock__name(&variables) {
  if (!\Drupal::request()->cookies->get('mycookie') == 'allow') {
    $variables = [];
  }
  // Don't forget about cache context for cookie!
  $variables['#cache']['contexts'][] = 'cookies:mycookie'
}


How to get the number of pages in a view template?

Mini Pager doesn't give you that information. It's designed to not execute a count query. It just knows that there's at least one additional result (because it actually queries 21 if you show 21).


How to implement a select list that allows for multiple selections?

From the various attempts you tried, it seems that the reason for your issue is simply that you have not indicated that "multiple values are allow" for this field.

To ensure multiple values are allowed, navigate to /admin/structure/types/manage/mytype/fields/field_abc (assuming 'mytype' is the machine name of your content type, and 'abc' is the machine name of your field). As an alternative, use the "edit" link for your field, within the "manage fields" tab for your content type, after you selected the content type via Admin > Structure > Content Types.

Then within the option that says "Number of values", indicate the "Maximum number of values users can enter for this field.". Note: the default is 1, so if you did not change that yet (eg to 'unlimited'?), then that would explain your issue (and resolve it).


MySQL 5.1 to MySQL 5.6 update causes php-cgi error: PDO issue?

As noted above, the whole thing was resolved by pushing the default character set back to utf8 from the incompatible (for Drupal, but not for WordPress) utf8mb4...

Relevant my.ini settings as follows:

[client]

default-character-set = utf8 # not utf8mb4

[mysql]

default-character-set = utf8 # not utf8mb4

[mysqld]

# REF: http://stackoverflow.com/a/24487309/3174018
collation-server = utf8_unicode_ci
character-set-server = utf8 # not utf8mb4


How to save custom theme settings in a subtheme?

I ran into the same issue. After doing an analysis I found the following:

THEME_form_system_theme_settings_alter is called for the base theme and then for the sub theme. It's not really a hook as they say - "Implements hook_form_FORM_ID_alter().".
The base theme uses things like theme_get_setting('asdf_asdf', 'responsive') to get the default values for the settings form.
The settings you're saving are saved for the sub theme.
In templates settings are returned also using theme_get_setting('asdf_asdf', 'responsive').

Because of #2 and #3 the settings appear to not be saved.

Maybe they should have used theme_get_setting('asdf_asdf'). So it will default to the current theme. It can be used in both cases: #2 and #4. It would have worked fine.

For the sake of not altering the theme and because of #4, I would remove the extra settings in SUB_THEME_form_system_theme_settings_alter so you can modify the settings only in the base theme configuration page.


Visibility depending on several values of another field

The Conditional Fields module should be able to do that.


I solved the problem by first doing the field translation manually for one node, and then using Node Export to see the actual code describing the node.
Finally, I used the prepare function of the Migrate api to do the work manually.

function prepare($entity, stdClass $row){

    $entity->language = 'el';
    $entity->title_field['el'][0]['value'] = $row->name;
    $entity->title_field['en'][0]['value'] = $row->name_en;
    $entity->translations = (object) array(
                    'original' => 'el',
                    'data' => array(
                            'el' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'el',
                                    'source' => '',
                                    'uid' => '0',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                            'en' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'en',
                                    'source' => 'el',
                                    'uid' => '1',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                    )
            );
 }


You can try this. Set the node id in the form element

    '#nid' => $nid,

and use FormState::getTriggeringElement to get the triggering element and the property #nid:

  public function deleteNode(array &$form, FormStateInterface $form_state) {

    $trigger = $form_state->getTriggeringElement();
    $nid = $trigger['#nid'];

In some cases you have to get the triggering button from the parent property:

    $clicked_button = end($form_state->getTriggeringElement()['#parents']);


How to create a module that shows some fields of profile2 type?

Your hook_theme() implementation is returning an array with missing details; the key should be variables and its value array should contain keys that matches the variable names in your template.

function profile_header_theme($existing, $type, $theme, $path) {
  return array(
    'profile_header' => array(
      'template' => 'profile_header',
      'path' => $path . '/theme',
      'variables' => array(
        'field_store_name' => NULL,
      ),
    ),
  );
}


How do I display three months in the event calendar view?

It doesn't look like there isn't anything in the admin that will give you three months. I've implemented some similar solutions with custom calendars.

There are a few ways that you could do this. I'm not going to get to far into the code, but just describe what I've done (I don't have a multiple-month example).

Method 1) Duplicate the monthly view and  alter the defaults in the contextual filter. Display these multiple blocks or feeds on a page.

Method 2) Create a custom node for displaying 3 months. Pass the contextual filter to the same view. Twig Tweak can handle passing arguments, though you may end up needing to do more preprocessing what Twig Tweak allows.


"cannot use a scalar value as an array" warning for adding #prefix and #suffix in template.php via hook-form-alter – Drupal 7

Warning: Cannot use a scalar value as an array in MYTHEME_form_alter()

It is a common PHP error which means you are treating a scalar value (eg: int, string) as an array.

You can fix it by checking if it is an array before using it.

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &$field) {
      if (is_array($field)) {
        $field['#prefix'] = '
';
        $field['#suffix'] = '
';
      }
    }
  }

As mentioned by @Clive

Since you are adding #prefix and #suffix, you are obviously trying to change for the render element. So it would be better to limit the change occurred on render element only.

element_children is the API provided by Drupal for that purpose.

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($element_children($form['submitted']) as $key) {
      $field = &$form['submitted'][$key];
      $field['#prefix'] = '
';
      $field['#suffix'] = '
';
    }
  }


Module to create nodes that are lists of other nodes?

You could probably try the Flag module. It doesn't create nodes, but the idea is pretty much what you're lining out.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.


Saw your post on d.o.: https://www.drupal.org/project/domain/issues/1673650
The suggested fix looks good and should still run:
function MODULENAME_domain_cron($domain) {
  global $base_root;
  if (isset($domain['path'])) {
    $base_root = $domain['path'];
  }
  boost_cron();
}

The error you have there seems strange. The argument should be passed to the hook_domain_cron method ?!?
UPDATE: You still can try to make the argument optional:
function MODULENAME_domain_cron($domain=[])

But I would debug that to find out the real reason ..
How does your code look for mymodule_hook_domain_cron?


How do I write a custom migrate destination plugin in for a node type?

It's my understanding that your migration problem lies in the fact that you can't add a custom destination plugin for nodes. Your exact migration strategy is not entirely understood from your question, so I'm going to address only the part related to destination migration plugin, which might help you addressing the problem with adding custom logic to a migration process.

Destination plugins for entity migrations are indeed created by a deriver (see MigrateEntity::getDerivativeDefinitions()) and adding custom destination plugins is not as straightforward as creating, for example, a custom source plugin which extends an existing source plugin, because destination entity type is determined from the ID of destination plugin (entity:[name]).

You can still can create custom destination plugins for entity migrations in the following way:

Migration definition file:

id: fm_quiz
label: FM Quiz
migration_group: quizzes
source:
  plugin: fm_quiz
  key: source
destination:
  plugin: fm_quiz
process:
  type:
    plugin: default_value
    default_value: quiz
  title: title
  uid:
    plugin: default_value
    default_value: 1
  sticky:
    plugin: default_value
    default_value: 0

Custom migration destination plugin:

<?php

namespace Drupal\fm_quiz\Plugin\migrate\destination;

use Drupal\Core\Entity\Entity;
use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @MigrateDestination(
 *   id = "fm_quiz"
 * )
 */
class FmQuizNodeDestination extends EntityContentBase {

  /** @var string $entityType */
  public static $entityType = 'node';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return parent::create($container, $configuration, 'entity:' . static::$entityType, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function import(Row $row, array $old_destination_id_values = array()) {
    // Add custom code here, if needed.
    return parent::import($row, $old_destination_id_values);
  }

}

Technically, it's the same class that entity:node destination plugin would use, but create() method of the custom class tricks parent class to use storage of node entity type.


The thread you link to is for Drupal 6, if you are using Drupal 7 I think the template file should be:
page--mobile-special-events.tpl.php (note the double dash).


Should the Update Manager module be uninstalled when installing with Composer?

Personally, I have Update Manager installed on all my live sites.

While I use composer to manage all of my sites, I am do not blindly composer update and push out.  I like to read changelogs and make sure I regression test thoroughly.

So, I have email notifications for updates turned on for all of my sites.  Most are set for daily notification for all updates, but a handful of internal-only sites (as in behind the firewall) set for security updates only.

Then I can test and plan what updates go out when during my maintenance windows.  Or for security updates, triage how critical they are to go out outside the normal windows.


What hook to use changing image field description

The alternate text field is added by image_field_widget_process(), which is the process element function added by image_field_widget_form() (an implementation of hook_field_widget_form()). To alter it, you can add your element process function with hook_field_widget_form_alter().

function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'image' && $context['instance']['widget']['type'] == 'image_image' && !empty($context['instance']['settings']['alt_field'])) {
    foreach (element_children($element) as $delta) {
      $element[$delta]['#process'][] = 'mymodule_field_widget_process';
    }
  }
}

function mymodule_field_widget_process($element, &$form_state, $form) {
  // Verify the element is accessible to the currently logged-in user.
  // Differently, it will not be visible to the user, and it is useless to alter the description, or the title.
  if ($element['alt']['#access']) {
    // Use $element['alt']['#title'] for the title.
    // Use $element['alt']['#description'] for the description.
  }

  return $element;
}

The reason I would use hook_field_widget_form_alter() instead of hook_form_alter() is that the first has direct access to some information the latter doesn't get, such as the settings for the field instance, and the field settings. In this case, I can access $context['instance']['settings']['alt_field'] to check if the field requires the alternate text field.

If you are going to use hook_form_alter(), remember that:

A field could have more than one widget, if the user is allowed to enter multiple values.
When its #access property is set to FALSE, a form element is not accessible to the currently logged-in user; in that case, it is useless to change any other properties for the form element, as it will not be shown to the user.


Is it possible to change the value of the field based on the the browser's language?

This is the plugin what also core using for browser language negotiation. You can have a closer look what the plugin exactly does: \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser

The code

$language_negotiation_method_manager = $this->container->get('plugin.manager.language_negotiation_method');
$plugin_id = LanguageNegotiationBrowser::METHOD_ID;
/** @var \Drupal\language\LanguageNegotiationMethodInterface $language_negotiation_method */
$language_negotiation_method = $language_negotiation_method_manager->createInstance($plugin_id);
$request = $this->container->get('request_stack')->getCurrentRequest();
$browser_langcode = $language_negotiation_method->getLangcode($request);

This will either give you back a valid language code or FALSE if the negotiation was unsuccessful.

Regarding the dependencies

$container is only used as an example to show which services are being used.
Request is always present as an argument when you are in a controller.


How do I remove the arrows from the breadcrumbs?

You can override theme_breadcrumb() function in your theme. As mentioned in the below code.

function yourthemename_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
  }
}

Just write above code in your template.php and change >> to whatever you want.


I am trying to pull ldap server information from the ldap_servers table in drupal

Please read on Working with Result Sets documentation. You have not issued the query yet to your database, you've only built a SELECT statement.

I also recommend installing the Devel module as you can get much more readable debug information from dpq() for queries or dpm() for Objects you want to inspect.


What precautions should I take to prevent data leaking between users (especially anonymous)?

You shouldn't have to do anything special. not even disable render cache.

Form data is only cached after the first ajax request and then it is for the specific form build Id (which is unique) only. That means that while the form is generated and cached in the page cache, the first request for every request for every user will rebuild the form from scratch.

There used to be a bug in core at some point in 8.x (long before 8.0) where the new user entity including its UUID was cached on the register form and then only one user could register every 6h because the others had UUID conflicts. The form cache changes fixed this.


read webforms fields in a mobile app and write submissions to the site database

I believe services will fulfill your needs. You can try with  Services module.

You may require to customize the module for your custom made features in the site.


How To Get Views Argument as a Like / Contains Instead of Equals

Solution would be to filter results by argument value. Unfortunately, this doesn't seem to be doable in Views at the moment. Not via the Views interface, anyway.

However, by altering exposed filter form to set current argument value as filter default value, users have managed to get such functionality to work: http://drupal.org/node/360780

I don't know what state it is in, but you may want to have a look at this module, which is supposed to do just that -- enable using argument placeholders (%1, %2) as filter values: http://drupal.org/sandbox/itangalo/1086472 (git only)


How do I print the title in page.tpl.twig?

For title page-title.html.twig can be added in page.html.twig title of the page is not explicitly available by default.


How to correctly use cookies? (Twig and cache context)

I've updated the code in the question, the code is now working. It was almost complete, I had made some simple mistakes though:

Even when providing a proper cache context, you still need to disable the Internal page cache module. Only Internal dynamic page cache module is allowed.
user_cookie_save() prefixes the cookie name with Drupal.visitor. This is  the real name you'll also see in your browser's dev console. But when checking for cookie names in PHP, dots and spaces are converted to underscores. That means using user_cookie_save(['mycookie' => 'some_value']); creates a cookie with a "real" name of Drupal.visitor.mycookie, but in PHP

your template/module code needs to check
if ($_COOKIE['Drupal_visitor_mycookie'])
and you also have to use the underscore name in services.yml
required_cache_contexts: ['cookies:Drupal_visitor_device', '...other_stuff...']

Don't set the cookie value and check that updated cookie value in the same request:
user_cookie_save(['mycookie' => 'new_value'])
will immediatly update the cookie in the client browser, but PHP code in the same request like
if ($_COOKIE['Drupal_visitor_mycookie'])
will still return the original value from the previous request.


How can I list all the pages of a Drupal site in csv format?

I wrote a dirty script to query the node, menu_router, and menu_links tables: https://gist.github.com/dooug/b102a683d4e4854defba

This could be improved upon. The upside is that it includes "path,title" of all nodes, panel pages, view pages, etc. The downside is it includes all admin pages. Also, it includes lots of duplicates between the menu_links and menu_router tables. Please fork with your suggestions.


How to show a block only on the nodes which the user created

I don't understand your reluctance to use php in a block, particularly in the block visibility settings.

If you set the block to display only on the pages where the following php code returns true, then the following, or something similar, should do the job for you.

<?php
global $user;
$node = menu_get_object();
return ( $user->uid == $node->uid );
?>


Heartbeat module comments collapsed by default

In this case you can use Collapsible Comment module. This module will help you to collapse the threads of the comments.

Now if you want to collapse entire comment region in collapsible form then you can do this using javascript.

Create a js file and add below javascript in a js file and add it to your theme or module.

(function($) {$(function() {
      var $comments = $('#comments');
      if (!$comments.size()) return;
      var count = $comments.find('.comment').size();
      // if (!count) return; // Do nothing when there is no comment.
      var label = Drupal.formatPlural(count, '1 comment', '@count comments');
      var $legend = $(document.createElement('legend')).html('' + label + '');
      var fsetclass = 'comments collapsible' + (location.href.search(/#(comment|new)/) == -1 ? ' collapsed' : '');
      var $fset = $(document.createElement('fieldset')).addClass(fsetclass);
      var $fsetwrap = $(document.createElement('div')).addClass('fieldset-wrapper');
      $fset.insertBefore($comments).append($legend).append($fsetwrap);
      $fsetwrap.append($comments);
      var attach = function() {Drupal.behaviors.collapse.attach($fset.parent(), Drupal.settings);};
      Drupal.behaviors.collapse ? attach() : $.getScript(Drupal.settings.basePath + 'misc/collapse.js', attach);
    });})(jQuery);

The above code will help you to collapse comments. Enjoy!!! :-)


Site name cannot be changed for different languages and domains Drupal 7

It seems that the option in Domain Access "Override site name with name of domain." was causing all the problems. It was so simple, but was driving me crazy. It was checked and thus if I tried to change the value elsewhere (in the Variables section or in the Site info section), nothing happened, the value was not changed. Unchecking this option ("Override site name...") in the Domain Access configuration, this variable "site_name" can have multiple values depending on language and domain combinations.


Using field_create_instance(), db_set_active() and node_save() in conjunction

I've figured out a solution to this, although I'm not sure if it's the best performance wise. It would seem that even after switching database with db_set_active(), node_save() (and presumably any other field<>database operations) will continue to use the field info as defined beforehand, so even if you've specified a value for a field that only exists in the second database, it will assume the field doesn't exist. Using field_info_cache_clear() right after db_set_active() solves the problem.

Obviously clearing any cache in a hook like this sort of defeats the purpose of the cache; fortunately in my case it won't be necessary too often.

If anyone knows of a better way of handling it without clearing any caches or creating the field on both/all sites, I'd love to know. I won't mark this as the accepted answer for the time being.


This is an entity form and you need EntityFormBuilder::getForm() to build this form. After you have injected the entity form builder and the necessary user storage and current user services in the block plugin:

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Profile Block.
 *
 * @Block(
 *  id = "profile_block",
 *  admin_label = @Translation("Profile Block"),
 * )
 */
class ProfileBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFormBuilderInterface $entity_form_builder, AccountInterface $current_user, EntityStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entity_form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.form_builder'),
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

you can build the profile form for the current user with two lines of code:

  public function build() {
    $user = $this->userStorage->load($this->currentUser->id());
    return $this->entityFormBuilder->getForm($user);
  }

}


How to pass variables between theme functions

I am newish to Drupal, but will give this a shot (I'm sure someone will tell me if I am wrong).

You can set variables that exist in different contexts by using the template.php file of your theme by adding stuff to the $variables array with preprocessor functions. So you could maybe add your variables to the YOURTHEME_preprocess_html() function, which should make them available everywhere.

function YOURTHEME_preprocess_html(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}


How to stop cache_field table from growing?

You could switch that cache bin so it uses something like file cache https://drupal.org/project/filecache

Also look into using memcache as that will evict the older cache data so that memcache stays within the parameters you give it.

Also consider optimizing the database; it should help to reduce the overhead
http://dominiquedecooman.com/optimize-mysql-tables-gives-35-drop-disk-usage-drupal-7-performance-tip

Finally if you really want to disable that cache you can use the DrupalFakeCache backend for those cache bins
https://drupal.org/node/797346


How do I send email to a large number of Drupal users, based on rules?

The Mandrill module (combined with the Mandrill service) lets you send transactional emails (and, theoretically, bulk emails) very quickly. It has a built-in queue feature which adds outgoing emails to a cron queue.

Note that the Mandrill service requires you to build up a reasonable sender reputation before you can send many emails at the same time - there are hourly limits that increase automatically. And of course it can cost money.

The Queue Mail module is a general-purpose solution to queue outgoing emails, if you don't want to run Mandrill or other modules that have their own queueing.

Regarding cron: Drupal's built-in cron triggers all repeating tasks to run at once, which means it can be very slow for complex sites. Many cron tasks don't need to run that often, and many of them shouldn't run often (for example, the system cron clears caches, which can really slow down the site).

So you can use the Elysia Cron module to manage cron jobs more effectively: it allows you to separate tasks so that the ones that are fast and need to be frequent (such as Mandrill cron) run say every minute, while the ones that are slow (such as system cron) run every week.

The Ultimate Cron module is an alternative to Elysia Cron - I haven't used it recently so I'm not certain that it works well.


Using preprocess node variable in page.tpl.php

The node variable for page templates is set in template_preprocess_page
http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page/6
You should override that function in your theme


How can I send emails with drupal_mail() and hook_mail()?

Debugging such kind of eMail issues can sometimes be challenging.

Consider the 3 Modules to Help you Debug Emails in Drupal 7. Here is a quote from it:

  Problems can exist in multiple areas; like Drupal itself or your mail server. So when an email issue arises you first need to check and see if Drupal is generating emails and then make sure your mail server is sending the emails. Luckily in Drupal there are a few modules that can lessen the pain of debugging emails.

These are the 3 modules/steps mentioned on that link:

Intercept Emails Using Devel.
Log Emails Using Mail Logger.
Re-route All Emails Using Reroute Email.

PS: Debugging Drupal emails contains another checklist with 8 possible reasons about what may be the problem.


Migrate module. Users from D6 to D7 with preserved UIDs

For migrating to Drupal 7, it's much simpler:

// Pass the old uid through
$this->addFieldMapping('uid', 'uid');
// Tell user_save to create a new account with the given uid (otherwise it sees the
// uid and assumes you're updating an account).
$this->addFieldMapping('is_new')
     ->defaultvalue(1);


I assume you've added the Content: Has taxonomy term ID contextual filter. You can use taxonomy term names with this filter by adjusting Specify validation criteria settings. here's a screenshot:

Make sure Specify validation criteria is checked and you should be presented with more options. Under Validator choose Taxonomy term. You can optionally select with vocabularies to allow. Under Filter value type choose Term name converted to Term ID and check the Transform dashes in URL to spaces in term name filter values checkbox.


Views: Trying to filter content by two field values (either/or)?

You can solve this without any additional modules or coding, just with pure Views + Entity Reference. Here is how:

You need to add 1 more relationship to your current View (looking at your screenshot):

Entity Reference: Targeted User => This is the Entity Reference field that points to a User, what you call "targetuser"

You need to add a "User: Current" filter to your view. Once you click on that, you should see the following:

This filter will allow you to select only the nodes where the targeteduser is the same as the logged-in (current) user.
You need to place the universalswap in an OR relationship to the new filter inside a FILTER GROUP. Then place that group in an AND relationship to the rest of your filters, i.e. Type = Messages.

That should do it without any additional modules.
Here is a screenshot of my final View configuration:

I am logged in as admin (uid:1) and you can see in the results that I am getting all messages that are either "Universal" or targeted at me.

Good luck!


How to hook drupal commerce line item create

Yes, you can use

hook_entity_insert()

Act on entities when inserted.

hook_entity_presave()

Act on an entity before it is about to be created or updated.


Format of the JSON returned by the Services module

You should implement hook_services_request_postprocess_alter().


Even though you don't want to use a contrib module I will recommend the CDN module anyways. It does what you want, but if you don't want to use it you can still look at how they do it.

They define a lot of services, but the most interesting one is this one:

cdn.file_url_generator:
    class: Drupal\cdn\File\FileUrlGenerator
    arguments: ['@app.root', '@file_system', '@stream_wrapper_manager', '@request_stack', '@private_key', '@cdn.settings']

The class FileUrlGenerator then does checks for files to determine if they should be rewritten and rewrites them.


How do I call some function after an AHAH callback that adds a new item?

You could handle ajaxComplete jquery event, which is called right after completion of ajax/ahah requests.


Getting User Entered Form Data within a hook function

You can user this code in which you can add your form data in array and pass it to the Paypal api.

function do_custom_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method){
    if ($payment_method['base'] == 'commerce_paypal_wpp' ) { //check payment method

        //save form data
        $name = $form_state['values']['field_name'];
        $organization = $form_state['values']['field_organization'];

        $nvp += array(
        'name' => $name,
        'organization' => $organization,
    );
  }
}

Here is the similar solution for your problem in which user has passed order details. Click Here


Try the Get Form ID module:

  By hovering over any form you will see a contextual link
  available. By expanding the link you will see the form ID. Click
  on the link and you will see a modal window with copyable form id and
  hook_form_FORM_ID_alter() hook suggestion.

Step 1: hover over the form.

Step 2: expanding the contextual link.

Step 3: Click on the link and a new window will open with copyable form id and hook_form_FORM_ID_alter() hook suggestion


How to preserve discount set with query parameters into cart?

My current implementation:

Custom action triggered on "Calculating the sell price of a product":

looks for the query parameter "code" in the url
verifies code is valid and active (uses commerce_coupon)
applies it to the line item on product landing page
saves code as a session variable

Custom action triggered on "After adding a product to the cart"

looks for code as a session variable
verifies code is valid and active
uses 'commerce_coupon_redeem_coupon' to apply to cart order
clears the session variable

This seems to work, though it seems a bit rube goldberg. Still looking for a better way to preserve a discount that arrived as a query parameter, and apply it to a cart order, if there is one.


How do you get the weather module to recognise SVG files?

I don't like to, but I hacked the module: weather_theme.inc. I altered:

$image = $custom_path . $symbol . '.svg';

Here's the full function:

/**
 * Returns the <img> tag for the weather image to use for the current condition.
 *
 * @param $symbol
 *   The weather condition number from yr.no
 * @param $condition
 *   The translated condition text.
 *
 * @return $string
 *   Ready formatted HTML <img> tag
 */
function weather_format_image($symbol, $condition) {
  // Support a custom image directory. If the variable is not set or the specified
  // file is not available, fall back to the default images of the module.
  $custom_path = file_default_scheme() . '://' . variable_get('weather_image_directory', '') . '/';
  // Construct the filename
  $image = $custom_path . $symbol . '.png';
  if (!is_readable($image)) {
    $default_path = drupal_get_path('module', 'weather') . '/images/';
    $image = $default_path . $symbol . '.png';
  }
  $size = getimagesize($image);
  // Prepare the <img> tag
  return theme('image', array(
    'path' => $image,
    'width' => $size[0],
    'height' => $size[1],
    'alt' => $condition,
    'title' => $condition,
    'attributes' => array('class' => 'weather-image')
  ));
}


How to add parameter to URL when passing ids as arguments to a page?

As per suggestion from this post, you should write a custom action using hook_action_info similar as Pass ids as arguments VBO action, so consider duplicating it as a starting point.

See also the following feature request: Token support in "Pass ids as arguments to a page" URL field.


What is the equivalent of calling drupal_lookup_path()?

Drupal 7:

$path .= drupal_lookup_path('alias', $path);

Drupal 8:

$alias =
  \Drupal::service('path.alias_manager')
    ->getPathAlias($path);

if (strcmp($alias, $path) == 0) {
  $alias = '';  // No alias was found.
}

$path .= $alias;

Reference Link

8 calls to drupal_lookup_path()

drupal_get_normal_path
drupal_get_path_alias
purl_get_normal_path
rules_condition_path_alias_exists
rules_condition_path_has_alias


How to show main menu links based on user roles?

Meet Menu Per Role Module

  This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual.


Twitter sign in module session token values lost in twitter/oauth path in HTTPS - Invalid Twitter OAuth request

The error could be related to:

Using API on the wrong domain/subdomain (www prefix can be relevant).

See: Why do I get a Oauth error?
Temporary Twitter issue.

See: Twitter module Oauth 'TwitterException' with message 'Unauthorized'
Make sure your code is passing the valid oauth_verifier.

  For OAuth 1.0a compliance this parameter is required unless you are using xAuth. Currently Twitter supports both OAuth 1.0 and OAuth 1.0a which means we do not error if this value isn't included. It is strongly recommended that applications not using this parameter are immediately updated with support for oauth_verifier added. OAuth 1.0a will be enforced soon and applications not using the oauth_verifier will fail to complete the OAuth flow.

See: Oauth/access_token Stopped working today
Your Twitter module may be outdated, please consider upgrading it.

If it's still happening, check the logs for any detailed responses. Otherwise contact Twitter support.


The problem is that the path associated to your menu item is using a wildcard ("%nid"), but your code is not defining an auto-loader for that wildcard.

For a wildcard such as "%nid" Drupal is looking for a function called nid_load(), which doesn't exist; if you want to use video_load(), then the placeholder should be "%video" and not the one you are using. If that part of the path is a node ID, then you should use "%node" that would cause Drupal to use node_load(), which is a function defined from the Node object and that returns a node object for the node ID passed as argument.
The auto-loader function should return an object or an array. If the auto-loader function is not returning a value, then Drupal would act as if the returned value is FALSE, which is the value that causes Drupal to return to the user the "page not found" error, as it understands the value as meaning "I didn't found what the user is looking for." Return an object (which is what node_load() does), or an array, and the user will not see the "page not found" error anymore.

In your case, the URL for the menu item defined from the module is something similar to http://example.com/video/1, or http://example.com/video/2, where 1 and 2 are (I presume from your code, as you use "%nid" as wildcard, which should mean "node ID") the node IDs of existing nodes.
Take as example the URL for the menu item associated with the node view page, which is "node/%node"; you invoke that page with, e.g., http://example.com/node/1, and Drupal shows you the content of the node with node ID equal to 1.

If you don't want to use an auto-loader, then your menu item should use a path such as "video/%" and Drupal would not look for an auto-loader function. What I reported about the URL to use to invoke the page served from your module is still valid, except that the URL could be  http://example.com/video/asdfsdfwer, http://example.com/video/2, http://example.com/video/azder54gfg because the % in "video/%" matches any string.

Bart is correct in saying that using "%nid" as placeholder in the path, when the page callback, the access callback, or the title callback doesn't get any argument derived from that placeholder, doesn't make sense.

For more information, you can look at the documentation for hook_menu(); Wildcard Loader Arguments, Wildcard usage and core's wildcards, Dynamic argument replacement (wildcard), Wildcard, ancestors and fitness; and, as general information on how Drupal menu system work, Drupal menu system (Drupal 6.x).


EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX

EntityFieldQuery does not support Aggregations/Expressions.

You have three options, basically:

Load all nodes, make the summary in PHP. As you already said, not a good idea if you expected thousands or even just hundreds of payments.
Write an SQL query, which should be rather simple since your field is probably only attached to the relevant bundle so you only need to query a single table and get the SUM() of the field value of all values. To be sure, you could also join the node table and add a condition on the node type. Although not nice, doing this is IMHO fine for custom code, where you know that the field will always be in the database. If you want to support different field storage implementations like MongoDB, not so much...
Lastly, a bit more work, you could maintain a global summary that you update every time a payment is created/updated by implementing a corresponding node/field hook (like hook_field_insert(), as you can see this is what taxonomy.module does...). This would probably be a good idea if you expected that you need the summary frequently. Also, while it might be tempting to use variable_get()/set to maintain a single value, that's not a good idea as it results in cache clears every time a variable is written.


There is no built-in way to restore a deleted view. Check if you have an old database dump somewhere (a regular backup, or maybe you created one when you put your site live). Depending on your hosting setup, your webhost may also have created backups of your server.

If that all fails, I'm afraid you will need to rebuild your view manually. While you're at it, consider upgrading your site to Drupal 7. Newer versions of Views make it really easy to export your view to code, so you can store your view in a version control system and never lose it again.


Ajax fired when Filefield "Add Another Item" button is clicked conflicts with my jquery

These tips are correct for Drupal 7.
Your custom code should be coordinated with Drupal AJAX Framework.
When you click "Add Another Item" this happens:

AJAX handler sends all the form with all values, and with point to element which has triggered AJAX.
Server returns fully new field. For example, if there were 4 inputs in your field, server will return 5 inputs, not just last fifth.
After that new piece of HTML goes through all the behaviors. As you may know, behavior's attach method has two params: context and settings. context is just new HTML for your field.

So, if you add your JS to this schema correctly it must work.

Drupal.behaviors.YOURMODULE = {
  attach: function (context, settings) {
    $('.some-class', context).once('YOURMODULE', function() {
      // Do some work here
    });
  }
}


Can I specify the location of a .tpl.php while using preprocess hooks?

It has to be in either the module defining the theme function or the active theme, unless you want to make override in the theme registry.

Drupal provides a hook: hook_theme_registry_alter that allows you to alter the theme registry and thus also where Drupal would look for template files. Messing too much with this tends to make it blow up into your face, as you alter some default Drupal behaviors.


Drupal 7 - Teaser trim ends after first  tag. How can I make it continue?

This solution works if you are using Views to display your content (if you aren't, it's up to you which is preferable in your case between using Views and getting its many other advantages, or installing Smart Trim and keeping things simple. Views is complicated but learning it is time well invested).

Choose "Summary or trimmed" as the field's "Formatter"
Set the "Trim length" value much too high - big enough that it will always cover the whole of all the elements you'll want trimmed (e.g. 1500)
Under "Rewrite settings", select "Trim this field to a maximum length". Tick "Field can contain HTML", keep "Trim only on a word boundary" ticked, and enter the real character count in "Maximum length" (e.g. 200). It's a good idea to keep "Add an ellipsis" ticked to, so incomplete sentances don't look like a mistake.

So in our example, Drupal will choose the summary if there is one, or the body text if there isn't. It'll count 1500 characters, and trims cutting out any incomplete HTML elements. Unless your article contains an excessively long insane paragraph from hell, this will be at least 200 characters. Then Views' filter kicks in, trims it to 200 characters by the nearest word. This gives the real desired length, without losing the option of showing a trimmed version of the summary if there is one.

With "summary or trimmed" or "trimmed", the trimming is based on whole HTML elements so that long paragraphs can be cut out entirely. I've found that sometimes, if there's one long introductory paragraph, the trimmed field would show up completely empty - this solves that.


Google Analytics Reports: how to remove pageviews for Top Pages and add published date

You're looking a one difficult task & one simple one. Starting with the simple one (reverse order):

The Top Pages area is a block that's installed with the module. The Google Analytics Reports Summary (Google Analytics): Top Pages view can be configured in the Views UI (/admin/structure/views/view/google_analytics_reports_summary/edit/attachment_top_pages). To remove the views count you can click the Page Tracking: Pageviews field and use the Remove button or Excluded from display checkbox to get rid of it.
Adding the publish data is a bit harder because what the underlying View is querying. The view is querying data tables from your Google Analytics account. As such, there is no Drupal node data to display from the query. Normally, the Views way to solve this would be to add a relationship with the node table then reference the publish date. However, the module doesn't provide a relationship handler to node content so you're looking a couple things here:

Select a Google Analytics field that can be joined on the node table. Page Tracking: Page is a close candidate here as it contains a unique path used for the node link. Nid would be better, but that data isn't sent to Google Analytics by default (you'd have to configure a GA custom variable).
Once you have a selected joined field. You'd have to build your custom relationship handler on which you can join to the node table to retrieve the publish date.


Send HTML email to all users of a role in action not display .....help me please

That action comes from the Mime Mail module, it's not one of Rules's defaults.

Once you've downloaded and installed the new module, just re-visit the Rules setup page and you'll find it in the list.


The standard method for adding css classes to twig templates

Your variables classesand my_classes are arrays. You could merge them:

{{ attributes.addClass(classes, my_classes) }}

Or add them one by one:

{{ attributes.addClass(classes).addClass(my_classes) }}

Or merge an array constant directly:

{{ row.attributes.addClass(row_classes, ['class-name-1', 'class-name-2']) }}

Or single classes:

{{ row.attributes.addClass(row_classes, 'class-name-1', 'class-name-2') }}

According to the coding standards https://twig.symfony.com/doc/2.x/coding_standards.html you should use underscores in variable names.


Set data value in rules not written when using a condition

I have fixed. Seems like conditions is quite the puzzle. I fetched entity by ID with actions to fix it.

conditions:
Entity has field: parameter:node, Field:field_userref

actions:
Fetch entity by id(id01) :. type: user, id:node:field-userref:uid
Fetch entity by id(id02) :. type: profile, id:entity-id01:profile-main:pid
wich made all profile2 fields available.


It sounds like you want a compound document, the JSON:API mechanism that provides other referenced entities in a resource (e.g. a "page" content node that references other paragraphs). This is done via adding an include query parameter with a value that refers to a field's relational ID. An inclusion request will add an included array property with the related entity resource objects.

See the docs on Includes in the JSON:API docs for more concrete examples in action.

Since you mentioned it, ordering included resources isn't possible (IIRC); you might be able to infer order based on the Paragraph field. JSON:API is designed for minimal configuration and maximum adherence to the JSONAPI spec so you're limited to a couple of mechanisms to modify the output of the structured data.


How to get the inreverse selection of a Views query?

It is simple. Go back in your Views Settings and find Sort criteria. There you can either reversely sort bu date: Content: Post date (desc) or by alphabetic order. It depends what field you take as sorting criteria.


Displaying a product price on Ad Push content?

You would need to add a new Product Reference field to the Ad Push content type. This allows content editors to pick a product to reference. You can then display the price through the "manage display" tab of the Ad Push form. You'll want the "Product: Price" field.


Exception in worker callback prevents queue item from being removed

I have the same issue. For me putting everyhing inside the worker callback function in a try block solved the issue.


References by title (not nid) while creating nodes via PHP code

I don't think that you need to write your own function, just have a look at node_reference_autocomplete_value(), this functions does exactly what you need (match Node Title to nid)


How can I show only terms from a certain vocabulary in a view summary?

I was looking for the same thing. I found my answer here: http://drupal.org/node/1243488#comment-4843640

It's not very intuitive, but it works.


Change a div content after click on another div

You need to conform to the coding standards and make it anonymous so it doesnt conflict with jQuery.

(function ($) {
  Drupal.behaviors.mybehavior = {
    attach: function (context, settings) {
      var selector = '.title-noticia a';

      $(selector).click(function(e) {
        e.preventDefault();
      }

      $.ajax({
        url: $(this).attr('href') + '?ajaxrequest',
        success: function(data) {
          $('.region-content').replaceWith(data);
        }
      });
    });
  });
})(jQuery);

See more: https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

Your behavior will be called automatically, so there is no need for $(document).ready.


Using a Service to expose better getter methods for a Node instance

Having a service for frequently used things like this makes sense.

That said, your code can be simplified a lot.

$node->get('field_fully_booked')->value == 1;

Does exactly the same. If you want to check something, then do a hasField('field_fully_booked') to avoid an error if that field doesn't exist.

This relies on magic methods, see https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

And yes, I did not use a type safe check on purpose. There are cases where type safety makes sense, but entity field values are not type safe, it actually makes your code more error-prone, for example if you'd change the value with API and did a = 1, then your method would return FALSE.


You should use the Finder module; I haven't used the D7 version yet, but the Drupal 6 version worked well for my needs.


What are these mysterious core.xxx files doing in my site's root?

They are core dump files; they are files created when a program has terminated abnormally (crashed).


How can I add my field of his type of material to be used in the rule

I hope it is for D7
I was facing same issue some months ago, I assume that you want tocheck the Boolean value of the fields?
please confirm that is that you want to do.

To compare to different entites I did following

You might not need to add these module to achieve what you want, but they are always good to know.

Drupal Commerce extra conditions

Drupal Commerce Extra Rules

Gives you more options when working with drupal commerce and conditions
Drupal Commerce extra rules - Well it gives you more rules to play with.

But for taxonomy term, Rules would just work out of the box.

The logic would be
a "Data comparison" condition, specify the field name, and enter "1" as the value. If the field doesn't appear in the list of fields, first add an "Entity has field" condition, and select the field there. Then add the "Data comparison" next.

Data Comparsion
Condition, give the field name you want, give the value 1.
If you cant find your field. You will need to add it in the above condition as "Entity has field" - or specifying "Content as type".
Then you will choose the operator which should be == (equals)
Add Data comparsion.
(Field might have to be direct input mode)

Hope it helps


How to index content from the Feed Aggregator?

The core aggregator module doesn't implement hook_update_index(), so your options here are to either do a bit of coding in a custom module to expose the contents of the aggregated feeds to the search module, or, to use the Feeds module.

I would recommend using the Feeds module, as this allows you to store imported feeds as nodes, which are then automatically included in the search index.


Why I cannot export vocabulary terms via Features?

You need to use the module uuid_features.

It is both possible to export individual terms by listing the ones you want or you can export all terms with the vocabulary:

Enable uuid_features
Go to admin/config/content/uuid_features
Check the boxes of the Vocabularies under "Exportable Taxonomy term bundles"

If you want to export all terms then check the "Auto detect uuid terms" option, so future additions / changes will be added.

If you didn't select the "Auto detect uuid terms" option: Do a drush fc and you will see a new item "uuid_term", get the list of components and do a drush fe FEATURENAME uuid_term:THETERMSUUID1 uuid_term:THETERMSUUID2 (gets really long, hence the "Auto detect uuid terms" option)
If you selected the "Auto detect uuid terms" option: you just need to export the taxonomy so do a  drush fe FEATURENAME taxonomy:VOCABNAME

Sorry about the odd bulletted list, trying to represent two options in one list.


Your route:

regportal_user.orders:
  path: '/user/{user}/orders'
  defaults:
    _entity_view: 'user.orders'
    _title: 'Управление заказами'
  requirements:
    _custom_access: '\Drupal\regportal_user\Controller\RegportalUserController::accessOwnOrders'

Your controller:

  /**
   * Checks access for a regportal_user.orders route.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessOwnOrders(AccountInterface $account, $user) {
    if ($account->id() == $user) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }


The easiest way would be to use the http://drupal.org/project/admin_menu module.

It has an option to move the tabs into the admin menu bar.
Set it by going to the admin menu settings page (admin/config/administration/admin_menu) and checking the "Move local tasks into menu" option.

For users gien access to the admin menu, you should remove access to the drupal toolbar module, or they will have 2 toolbars.

You could even disable to toolbar module and just use admin menu.

If you want to keep using the toolbar module instead of the admin menu module, you can remove the tabs from the page.tpl.php file in your theme and then print them elsewhere.

I don't know off the top of my head how you would go about doing that though.


How do I filter a view with a contextual filters on a custom date field?

In the arguments follow the pattern

20130904--20130930

for date range between 4th September and the rest of the month.


Filter three views blocks by the same filter

Views Attachment Displays are the way to go, because they are like Blocks but have special options for accepting contextual or exposed filters from the View they are attached to.

Create a Views Page Display with your Text and Date exposed filters, and show Upcoming information there (through the usual Filters).

In the same Views create a new Display of type Attachment. In the Attachment settings set:
    Attach to the Page from the previos step,
    Attachment position to After
    Inherit exposed filters to Yes
    Override the Filters to display Current info, and override fields if they are different from the default

Repeat the procedure for adding another Attachment, only this time for the Past information.

You can override the Fields, Filters and Sorting individually for each of those individual displays, while Exposed filters will be applied to all at the same time.

Format can also be overriden for each display. Just make sure you first set it to "This attachment (override)" and Save, even if you have to save the same Format (Table for example). Then under Format settings select your Grouping fields. Although IIUC the Grouping field will be the same in all displays.

The Page you created will show all 3 views results, one below the other, and all will react to the Exposed filter, assuming your 3 different structures share those same fields you have exposed.


How to override form element templates from custom module

Got it working. First you have to copy the default form element template into your module's /templates folder. For example:

$ mkdir -p modules/custom/MYMODULE/templates
$ cp core/themes/stable/templates/form/form-element.html.twig modules/custom/MYMODULE/templates/form-element.html.twig

Now rename it to something you want. For example:

$ mv modules/custom/MYMODULE/templates/form-element.html.twig modules/custom/MYMODULE/templates/form-element--foo.html.twig

Edit the file to match your needs. For example remove or change the

 tags. Finally in your module's MYMODULE.module file add the following two hooks.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * This hook adds a new theme suggestion for all radio form elements.
 */
function MYMODULE_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {

  if ($variables['element']['#type'] == 'radio') {
    $suggestions[] = 'form_element__foo';
  }
}

/**
 * Implements hook_theme().
 *
 * This hook registers a new theme in your module. It will
 * automatically look for the template in your module's /templates folder.
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'form_element__foo' => [
      // base_hook is important!
      // Otherwise your template won't know what to render.
      'base hook' => 'form_element',
    ],
  ];
}

Only thing left, I find, is to have the form ID added to the template suggestion as well, so that we could target only this one form's elements. As now this template will be taken into account for all radio form element wrappers. Independent from what form they are in. But unfortunately I couldn't find the form ID inside the form_element's $variables.

Hah, you simply could add a class to your radios and identify them by that later.

$form['radios'] = [
  '#type' => 'radios',
  // ...
  '#attributes' => ['class' => ['foo']],
];

And then the hook_theme_suggestions_HOOK_alter could look like that:

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

  if ($variables['element']['#type'] == 'radio' && in_array('foo', $variables['element']['#attributes']['class'])) {
    $suggestions[] = 'form_element__foo';
  }
}

Now the custom template would only be taken into account for your specific radios.


How to create rule to redirect an admin after log in to an admin specific node?

My guess would be that your rule weights are not as they should be.  If your rule that matches the admin role fires first and your rule that matches all authenticated users fires second then admins will always be redirected to node/90.

Check on the weights.  In your case, you want the more specific rules (the one for admins) to fire second.  So you need to make its weight larger than the more general rule.

Does that make it work for you?  I don't think you should need a custom module for this...

Also - disable the custom module while you're testing this out, to make sure the two are not interfering.


Is there any way to tell when a user's password was changed?

It is not possible to tell from the database it-self when user changed his password.

The user password in Drupal 7 is stored in users table with the following columns of interest:

pass - User's password (hashed).
access - Timestamp for previous time user accessed the site.
login - Column which tells you timestamp for user's last login.

However there are few workarounds:

If you've got logging enabled (dblog or syslog), Drupal logs when particular user has logged in. This should point you to the IP address (whether it's different as usual).
On live environments, periodical backups of database should be a must. Depending how often you do the backups, compare different dumps focusing on particular user and his password, for example:

gzcat db-dump-2017*.sql.gz | grep -w users | grep -w pass | grep specific_user

Note: Above command attempts to stream compressed dump of database in order to find value of pass column from users table for the given user.

Then check which database dump has the new changed password. From there you can check the logs (e.g. from watchdog table) for this user. Especially check IP addresses, requested URLs and authorization attempts (whether successful or failures).


Form hook not found through module_hook_info in module subdirectory

Thanks to Clive I found module_load_include(), which is used to load files when working with a form. I moved hook_forms() back to my main module's file and now load the mymodule1.form.inc through there, like so:

/**
 * Implements hook_forms().
 */
function mymodule1_forms($form_id, $args)
{
    module_load_include('inc', 'mymodule1', 'mymodule1.form');
    $forms = array();

    $forms['mymodule1_foo_form'] = array(
        'callback' => 'mymodule1_foo_form',
    );

    return $forms;
}

Now all my forms are loading correctly (again), over both mymodule1 and mymodule2.

The one thing I'm not sure about, that whether this could have been achieved without redundantly declaring the form callbacks to their same-named form IDs.


WSOD on deploy: failed to open stream: No such file or directory

There is a file permissions overview on this page of how all file permissions should be setup. If you will scroll down to the bottom of the documentation page there is a shell script that you can install and run on an entire Drupal installation that will fix all file permission issues. That should fix any problems that OP was having.


menu_get_active_title() should be the function you are looking for.

function menu_get_active_title() {
  $active_trail = menu_get_active_trail();

  foreach (array_reverse($active_trail) as $item) {
    if (!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
      return $item['title'];
    }
  }
}

It should work for menus for which the menu type contains the flag MENU_LOCAL_TASK (which includes also the MENU_DEFAULT_LOCAL_TASK menu type).

The function is also defined in Drupal 7.

Update: I noticed that for menus like /node/%node/view, menu_get_active_title() returns the title for /node/%node.
The following code should return the correct title also in those cases, including in the case the title is given by a title callback. I just tested on Drupal 7; I don't actually have Drupal 6 on the test site I use.

$item = end(menu_get_active_trail());

if (!empty($item['title_callback'])) {
  $args = array();
  if (!empty($item['title_arguments'])) {
    foreach ($item['title_arguments'] as $value) {
      if (is_int($value)) {
        // Get the value from the menu item map.
        if (!empty($item['map'])) {
          $args[] = $item['map'][$value];
        }
      }
      else {
        $args[] = $value;
      }
    }
  }

  $title = call_user_func_array($item['title_callback'], $args);
}
 else {
   $title = $item['title'];
 }


Using more than one function for a batch surely works, as one of the test functions for the batch API contains the following call.

batch_set(_batch_test_batch_3());

_batch_test_batch_3() contains the following code.

  // Ensure the batch takes at least two iterations.
  $total = 10;
  $sleep = (1000000 / $total) * 2;

  $operations = array();
  for ($i = 1; $i <= round($total / 2); $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(1, $total / 2, $sleep));
  for ($i = round($total / 2) + 1; $i <= $total; $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(6, $total / 2, $sleep));
  $batch = array(
    'operations' => $operations,
    'finished' => '_batch_test_finished_3',
    'file' => drupal_get_path('module', 'batch_test') . '/batch_test.callbacks.inc',
  );
  return $batch;

What is wrong in your code is how you set $batch['operations'].

The correct code is the following one.

$operations[] = array('test_function1', array($new_node));
$operations[] = array('test_function2', array($new_node));

$batch = array(
  'operations' => $operations,
);

batch_set($batch);


Only show the amount of views in Advanced Forum

Also, the view count on nodes is permission based, so you can deny the view permission to everyone and then it will only show for UID 1.


Commerce Module - Changing product in a display node makes the image revert back to default

Haven't found a solution to this, but a workaround I am using is to disable the 'enable as attribute' of both list fields, this makes it so there is only one list in the add to cart form. The list will have a option for each product that the node references, so if you have a lot of products, this can create a long list.

To do this, go to producttype > manage fields > edit (list field) and turn off 'enable this field to function as an attribute field on Add to Cart forms.' Then save. You have to do this for each list field.

I will edit if I find a direct solution.


How do I define a Route with multiple different paths?

cool:
  path: 'api/v1/{dynamic}'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

Then in your controller

public function doItAction($dynamic) {

  if($dynamic == 'foo' || $dynamic == 'foo_bar') {
    // your code
  }

}


How do you add custom help text to content entry/edit screens unrelated to field?

I usually do this with a form_alter myself in PHP code or I use the help entry for a Field.

Recently I found out about the Markup module. I recommend you try it out. I have no added it to any of my projects yet, but it's on my todo list.

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.

  The module does not add anything to the $node object for the content
  being created, and utilizes form_alter to remove unnecessary fields
  from the '_content_admin_field' form when this widget is being
  created.


How to completely wipe and rebuild drupal menus?

I have been looking a while for a solution to the problem to rebuild Drupal menus until I stumbled upon a Drupal issue that helped me. My solution (in a php script) is the following:

db_query("DELETE FROM {menu_links} WHERE module = 'system'");
db_query("DELETE FROM {menu_links} WHERE menu_name = 'management'");
menu_rebuild();

This could also be done by entering the queries through phpmyadmin or something alike:

DELETE FROM {menu_links} WHERE module = 'system'
DELETE FROM {menu_links} WHERE menu_name = 'management'

And then rebuilding the menu structure. If you use the devel module, you can achieve that by visiting the page /devel/menu/reset. I you don't have the devel module, I'm not sure how to rebuild the menu structure.

Don't forget to backup your database before you try this.


Changing the text "Add to Comment" in a given content type

You missed a key ['title'] in the array.

$build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');

Make sure you follow the naming conventions while creating a custom module, or if you are doing it from theme replace the custom from custom_node_view_alter with the theme name (e.g. garland_node_view_alter for garland theme).

You can eliminate the extra check (for a while) of the content type for a while to check if the solution is working.


How do I find all objects under an object?

I tried the following command, and it returns the expected output.

drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1));'

The only case where I get NULL as output is when I pass to Node::load() a node ID that doesn't exist.

The fact Node::load() loads the data from the database doesn't matter; in fact, the method still returns an object of the Node class.

Drupal\node\Entity\Node::__set_state(array(
   'in_preview' => NULL,
   'values' =>
  array (
    'vid' =>
    array (
      'x-default' => '1',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'revision_timestamp' =>
    array (
      'x-default' => '1465363710',
    ),
    'revision_uid' =>
    array (
      'x-default' => '1',
    ),
    'revision_log' =>
    array (
      'x-default' => NULL,
    ),
    'nid' =>
    array (
      'x-default' => '1',
    ),
    'type' =>
    array (
      'x-default' => 'page',
    ),
    'uuid' =>
    array (
      'x-default' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
    ),
    'isDefaultRevision' =>
    array (
      'x-default' => '1',
    ),
    'title' =>
    array (
      'x-default' => 'Test',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'created' =>
    array (
      'x-default' => '1465363684',
    ),
    'changed' =>
    array (
      'x-default' => '1465363710',
    ),
    'promote' =>
    array (
      'x-default' => '0',
    ),
    'sticky' =>
    array (
      'x-default' => '0',
    ),
    'revision_translation_affected' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
    'body' =>
    array (
      'x-default' =>
      array (
        0 =>
        array (
          'value' => '
Test.

',
          'summary' => '',
          'format' => 'basic_html',
        ),
      ),
    ),
  ),
   'fields' =>
  array (
  ),
   'fieldDefinitions' => NULL,
   'languages' => NULL,
   'langcodeKey' => 'langcode',
   'defaultLangcodeKey' => 'default_langcode',
   'activeLangcode' => 'x-default',
   'defaultLangcode' => 'en',
   'translations' =>
  array (
    'x-default' =>
    array (
      'status' => 1,
    ),
  ),
   'translationInitialize' => false,
   'newRevision' => false,
   'isDefaultRevision' => '1',
   'entityKeys' =>
  array (
    'bundle' => 'page',
    'id' => '1',
    'revision' => '1',
    'uuid' => '88E2D589-473B-4FE9-9A5A-F1F768A5E4E8',
  ),
   'translatableEntityKeys' =>
  array (
    'label' =>
    array (
      'x-default' => 'Test',
    ),
    'langcode' =>
    array (
      'x-default' => 'en',
    ),
    'status' =>
    array (
      'x-default' => '1',
    ),
    'uid' =>
    array (
      'x-default' => '1',
    ),
    'default_langcode' =>
    array (
      'x-default' => '1',
    ),
  ),
   'validated' => false,
   'validationRequired' => false,
   'entityTypeId' => 'node',
   'enforceIsNew' => NULL,
   'typedData' => NULL,
   'cacheContexts' =>
  array (
  ),
   'cacheTags' =>
  array (
  ),
   'cacheMaxAge' => -1,
   '_serviceIds' =>
  array (
  ),
))

Even running drush php-eval 'var_export(\Drupal\node\Entity\Node::load(1)->toArray());' (i.e. using the toArray() method you tried) gave me an output different from NULL. In this case, using a node ID that doesn't exist, you get a Call to a member function toArray() on a non-object error.

array (
  'nid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'uuid' =>
  array (
    0 =>
    array (
      'value' => '994535DB-7C4E-42F2-94CE-576DA3E9FC0B',
    ),
  ),
  'vid' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'langcode' =>
  array (
    0 =>
    array (
      'value' => 'en',
    ),
  ),
  'type' =>
  array (
    0 =>
    array (
      'target_id' => 'page',
    ),
  ),
  'title' =>
  array (
    0 =>
    array (
      'value' => 'Test',
    ),
  ),
  'uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'status' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'created' =>
  array (
    0 =>
    array (
      'value' => '1466285938',
    ),
  ),
  'changed' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'promote' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'sticky' =>
  array (
    0 =>
    array (
      'value' => '0',
    ),
  ),
  'revision_timestamp' =>
  array (
    0 =>
    array (
      'value' => '1466285973',
    ),
  ),
  'revision_uid' =>
  array (
    0 =>
    array (
      'target_id' => '1',
    ),
  ),
  'revision_log' =>
  array (
  ),
  'revision_translation_affected' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'default_langcode' =>
  array (
    0 =>
    array (
      'value' => '1',
    ),
  ),
  'path' =>
  array (
  ),
  'body' =>
  array (
    0 =>
    array (
      'value' => '
Testing a Drupal function.

',
      'summary' => '',
      'format' => 'basic_html',
    ),
  ),
)

Also, remember to fully qualify the class with its namespace, or add a use \Drupal\node\Entity\Node; line before using the class.

Using drush php-eval 'print json_encode(\Drupal\node\Entity\Node::load(1));' I just get {"in_preview":null} because json_encode() doesn't prints out all the object properties.


What urls does a page manager intercept?

It should work the same as hook_menu() implementations and also react when additional path elements are passed to it.

Basically, when you have a request like A/B/C, the menu system first looks for A/B/C, then A/B and finally A until it finds a match.


Filters and relationships data from a display to another within the same view

On your "subprocess" display, you need to add a relationship to the process that is referencing that subprocess. Then add a contextual filter of the process id using the relationship you created. Finally, add a field "Id" in the "process" display and pass the process id as contextual filter in the global view field (check the replacing patterns).


How to add organisation to the Drupal.org user profile?

As an example, have a look at my profile on D.O., which contains this link.

So make sure you have a similar Organization created there, which you can do via Create Organization, which is the link you can also find on Organizations.

If you're not the current owner (or something like that) of such organization, then you need to think of a way to get that Organization created around there. I don't remember any validation (when I registered the one I refer to), but what I would do:

Check with the organization you want to refer to if they are OK with getting such registration.
Have them complete such registration, or ask permission that you do it for them (and have them QA review it afterwards if needed).

If it's a huge organization, it may be a challenge to get approval from such organization, eg to find the right person to ask, and then get the actual approval. In that case, as an alternative, maybe you create something anyway about that organization, but without mentioning their actual name, and only using information that is considered as not confidential? But keep in mind that some companies may not want the world to know that they use Drupal ... eg for competitive reasons ...

Extra hint (for future occasions): try to make it part of contract negociations, something that they confirm that they are aware (and will not object) that you will register them as a company (if they are not yet registered). Possibly adding an appropriate annex to your contract with the details of that registration. It'll slow down contract negotiations, but that's probably the best moment to get approval. If needed offer them some kind of reduction on your rate to make them accept it. And of course, also explain the added value to them for being listed there (like free advertising?) ...

Note: there is also a Marketplace FAQ which may give you more ideas to get an organization registered correctly.


term field permission for authenticated user

I have found the answer of my own.

I edit the field there in the file extension I had entered like this "png, gif, jpg".

I changed it to "png gif jpg". insert the space instead of the comma and it solved my problem.


The id is a plugin ID. You either need to define your own views argument plugin and change the id to that or alter the plugin definition and replace the class there.

The first will just update a specific field, the second would replace the plugin everywhere where it is used.


Why won't JS fire on ubercart checkout page and how do I fix?

Only solution I came up with for this was to create a block, assign a blocktheme and in the tpl.php file put the JS. Then assign the block to only show on that page. Bit of a work-around, but it did work.


When should I use methods, get() and magic offset

If there is a specific method - as for $node->getType() - I'd recommend using this one. Obviously that's never the case for dynamic stuff like fields - for that $node->type->value would be the recommendation.

Edit: $node->get('type') is just a more verbose variant of $node->type - both get you the "type" field object.


How to render taxonomy in page template?

Use following code to display manually taxonomy terms:

$vocabulary = taxonomy_vocabulary_machine_name_load('vocobulary_name');
if ($terms = taxonomy_get_tree($vocabulary->vid)) {
  $tags ='';
  foreach ($terms as $term) {
      $taxonomy_path = taxonomy_term_uri($term);
      $tags .= l($term->name, $taxonomy_path['path']);
  }
}


I fixed this problem by myself. Please note the mistyped column type name integer which is now int:

function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'int',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}


What is the difference between normal filter and contextual filter in views?

In simplified language to understand.

Normal Filter: Normal filter takes the fixed data from the available data. For example, you have created a views with Content: Title which will show all the title of nodes available on the site. But if you provide the Filter: Content type(Articles), then it will show only the Node title of Articles. Hence here filter, filters all data and gives only data which belong to Articles.  So this is the Normal filter.

Contextual Filter: Now, Sometimes, you do not have the fixed filter value, suppose, Logged-in-user, value available in URL, Author name of currently loaded page. So, this kind of filter values are dynamic and keep changing, so Contextual filter provides the way to solve this. To visualize this you can see the following UI image of contextual filter. Which has mainly two section.

1. WHEN THE FILTER VALUE IS NOT AVAILABLE

2. WHEN THE FILTER VALUE IS AVAILABLE OR DEFAULT IS PROVIDED.

Now, in the first option WHEN THE FILTER VALUE IS NOT AVAILABLE itself defines what is Contextual filter is- So, Contextual filter SAYS to you,
"I can fetch value from following listed areas(as you can see in image), you select from  where shall I fetch. And I will take it as Filter value."

Example to understand Contextual filter:
Now your site has the Taxonomy terms- BMW, AUDI, HONDA.
So, in fixed value filter you can take only one value. But, what you will do when that value is keep on changing based on browsing.

So, suppose, I select contextual filter and select Taxonomy term ID from URL So, if URL will have BMW is will take BMW as filter, If URL will have AUDI it will take AUDI as filter value. So, filter value keep on changing here, hence Contextual filter provides the way for this.


Image upload broken when editing content

Make sure the file directory exists at sites/default/files and make sure it is writeable by the web server. For this you need to go to the file directory if you are familiar with terminal and type chmod -R 775 files when in the directory that contains the file directory. otherwise in an FTP client like Filezilla right click the file and click file permissions and change the permissions there.  You may also need to check that this folder files/imagecache/product exists and is writeable.


Your can probably add a rule of this kind :

The event is : Before saving content
Restrict by type : your content type

Then add a condition : Text comparaison then select your field with the Data selection like this node:field-example:0:name and match the International value. The rules will fire if all theses conditions passes


Delete button not working in Checkout page

Have never done something of that sort but what I assume is, once you move ahead with checkout, a order is created with status IN CHECKOUT or something like that.

So until a product is there in cart, you can remove that & but once you enter into checkout & order id with other details is created...product can't be removed. Maybe someone from Drupal Commerce maintainer can confirm more on this..


Try like this:

$to = 'ABCD@example.com';
$subject = 'Email in PHP';
$message = 'This is a test email message';
$headers = 'From: ABCD@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers, 'ABCD@example.com');


How do I add a file upload field to user profile?

Use Content Profile.

By default Content Profile puts the additional fields in a tab on the profile page. If you want them to be all in one page use Account Profile


Set entity reference field in form to readonly

Perhaps it's because you're referencing a language where it isn't necessary, try one of these:

$form['field_testreference']['#access'] = FALSE;

or

$form['field_testreference']['#attributes']['readonly'] = TRUE;


Drupal nginx configuration. PHP files being downloaded

I created a really long guide on how to set-up Perusio's nginx config. (EDIT: We turned it into a wiki so anyone can add. Also I forgot to link.) The config itself is excellent and well worth a look. If you couldn't get it working before, hopefully my guide will help.

Ok so here we go.

When you use either of the following expressions for a location block in nginx:

=
^~

Then it will stop searching for more matches immediately after it hits one of them. It checks = with priority then all the other 3 expressions at the same time in the order of the nginx config file.

So in my case it was finding ^~ on update.php and install.php and stopping the search immediately. This means it never runs php processing on the files and so they're downloaded instead of opening. Adding the php logic to the location blocks, means nginx then runs the php as well as blocking them for all bar me.

      location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        if ($uri !~ "^/default/files/") {
            fastcgi_pass 127.0.0.1:9000;
        }
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /srv/www/website/public$fastcgi_script_name;
      }

      location = /update.php {
          allow 127.0.0.1;
          deny all;
          fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
          fastcgi_pass 127.0.0.1:9000;
          include /etc/nginx/fastcgi_params;
      }

      location = /install.php {
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME /srv/www/mysite/public$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:9000;
            include /etc/nginx/fastcgi_params;
      }

You might note that I've also changed to = from ^~. This is because = is always picked with priority and prevents me from accidentally breaking this later. Choose = and avoid the difficulties I'm about to mention below.

Another useful point: I don't think nginx can ever match two location blocks. It'll pick the more specific one.

Stuff that doesn't quite make sense

Lastly I don't quite understand the priority order of the 3 expressions. If I put *~ in the update block in the example above, it chooses the php block (which has ~), apparently case sensitive overrules the more specific match? This seems weird and isn't mentioned in the docs. If I use ^~ it works as expected.

If anyone has found a great explanation of location I'd love to see it because I'm not sure the docs make perfect sense.