There's nothing different from 7.x with db_query(), it returns a result set where you can fetch results from or loop over it. Refer to the database API documentation.

However, there are even less reasons for doing a direct database query in 8.x than in 7.x, and doing the query by hand is very likely going to be more complicated because of the data tables.

Use entity query instead:

<?php
$uids = \Drupal::entityQuery('user')
  ->execute();
?>

Executing an entity query always returns entity IDs which can then be loaded:

<?php
$users = \Drupal::entityManager()->getStorage('user')->loadMultiple($uids);
// Shorthand if you know that you have users:
$users = \Drupal\user\Entity\User::loadMultiple($uids);
?>


Please try this:

function hook_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'form-id') {
   if(arg(0) == 'node' && arg(2) == 'edit'){
     drupal_set_title('Upload Edit');
    }
    else{
     drupal_set_title('Upload'); }

  }
}


When you download and install Drupal, it will install inside the directory that contains the files. So if you download Drupal into public_html and the directory with the Drupal files is called "drupal" it's going to install in public_html/drupal. Depending on what server you are running, you will need to identify the new webroot. In this example, you would change the webroot from public_html to public_html/drupal. The folks over at StackOverflow or your hosting company should be able to help you with your specific server settings for your new Drupal root.

Alternatively, you may be able to copy all the contents from the unzipped folder containing all the Drupal files into the webroot, but I've never tried that because I like keeping Drupal in it's own root.

Also, check sites/default/settings.php and see what it says for your Drupal root.


How can I integrate a stemmer with Search API?

It is possible to use the Porter Stemmer module with other modules besides the Drupal standard search. I have done it before (with Views exposed filters).

In your module, you could either invoke the porterstemmer_search_preprocess() function or just copy its contents into your own function. And then pass your search terms to this function. E.g.:

function your_function_for_preprocessing_text($text) {
   // Include porterstemmer (change accordingly).
   module_load_include('module', 'porterstemmer');

  // Convert text to lower case, and replace special apostrophes with regular
  // apostrophes.
  $text = drupal_strtolower(str_replace('’', "'", $text));

  // Split into words
  $words = preg_split('/(' . PORTERSTEMMER_BOUNDARY . '+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

  if (!count( $words )) {
    return $text;
  }

  $has_pecl_stem = _porterstemmer_pecl_loaded();

  // Process each word, skipping delimiters.
  $isword = !preg_match('/' . PORTERSTEMMER_BOUNDARY . '/', $words[0] );
  foreach ($words as $k => $word) {
    if ($isword) {
      if ( $has_pecl_stem ) {
        $words[$k] = stem_english($word);
      }
      else {
        $words[$k] = porterstemmer_stem($word);
      }
    }
    $isword = !$isword;
  }

  // Put it all back together (note that delimiters are in $words).
  return implode('', $words);
}

As I said, I have used the Porter Stemmer to stem all the terms entered in a Views exposed search. However, you'll still need to find the right hook in the Search API module to pre-process the text before the search query is run against the database.


I ended up using hook_ENTITY_TYPE_access():
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\Core\Session\AccountInterface;
use \Drupal\Core\Access\AccessResult;
use \Drupal\Core\Access\AccessResultInterface;
/**
 *
 * Implements hook_ENTITY_TYPE_access().
 */
function my_module_user_access(EntityInterface $entity, $operation, AccountInterface $account) {

  // Deny access to user profile for other members if the user hasn't accepted the terms
  if (!$entity->id() === $account->id()
      || !$entity->hasField('field_profile_visibility')
      || $entity->get('field_profile_visibility')->value === NULL) {
    \Drupal::messenger()->addWarning(t('The profile is not visible because this user has not accepted the terms of this site yet.'));
    return AccessResult::forbidden();
  }
  return AccessResult::neutral();
}


You could put your form element with the suffix into a container forms element. The container can also have states:

$form['format_document_container'] = array(
  '#type' => 'container',
  '#states' => array(
    'visible' => array(
      ':input[name="select_service"]' => array(
        array('value' => '1'),
        array('value' => '2'),
        array('value' => '3'),
      ),
    ),
  ),
);

$form['format_document_container']['format_document'] = array(
  '#type' => 'radios',
  '#options' => array(
    'yes' => t('Yes'),
    'no' => t('No')
  ),
  '#title' => t('Should we format your document?:'),
  '#required' => TRUE,
  '#default_value' => 'no',

  '#suffix' => 'markup for the help image',
);


Sorting by "aggregation type: count" is not working

This issue has been resolved in the development snapshot version 7.x-3.x-dev.


Is it a good idea to load the css files from page.tpl file instead of .info file

It is bad idea, on so many levels I'm sure I can't list all.

Conditionally included stylesheets will get cached by various proxies and served with no respect for original conditions.
Modules like CDN will not be able to work on your CSS files to speed things up.
Aggregation and cache modules will stop working as well.
Search engine bots will get confused and may think you are trying to trick them by serving different version of a page to bot, and other one to bot disguised for an user - risk of google ban.
If, in future, someone will redefine page.tpl.php for certain content types, you will have the same file described in many places - easy way for inconsistency and styling bugs.
CSS provided by modules might end up in other position to your own than they are now, this can cause hard to diagnose display bugs.


How can I access location information via rules, to include the City of a node in an email?

The Location module defines tokens for each piece of info (see below from location.tokens.inc)

So based on this, [node:location:city] should work for a single value, or [node:location:city:0] for the first value if there were multiple values.

  $location['name'] = array(
    'name' => t("Location Name"),
    'description' => t('Location Name (If there are multiple locations, N is the iteration, starting with 0).'),
    'dynamic' => TRUE,
  );
  $location['street'] = array(
    'name' => t("Street"),
    'description' => t("Street (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['additional'] = array(
    'name' => t("Additional"),
    'description' => t("Additional (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['city'] = array(
    'name' => t("City"),
    'description' => t("City (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province'] = array(
    'name' => t("State/Province"),
    'description' => t("State/Province (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['province_name'] = array(
    'name' => t("State/Province Name"),
    'description' => t("State/Province Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['postal_code'] = array(
    'name' => t("Postal Code"),
    'description' => t("Postal Code (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['latitude'] = array(
    'name' => t("Latitude"),
    'description' => t("Latitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['longitude'] = array(
    'name' => t("Longitude"),
    'description' => t("Longitude (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country'] = array(
    'name' => t("Country"),
    'description' => t("Country (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );
  $location['country_name'] = array(
    'name' => t("Country Name"),
    'description' => t("Country Name (If there are multiple locations, N is the iteration, starting with 0)."),
    'dynamic' => TRUE,
  );


Shopping cart delete button is not removing the correct line item.

Sounds to me like both of your forms on the page have the same form ID and use the same numeric key (likely 0) to identify the first item in the form. Thus when you submit it, Drupal doesn't know how to differentiate which form was submitted and makes a best guess, removing the 0th item in that form.

Alternately, if your configuration is generating a form within a form, that's invalid HTML and would explain a similar confusion on Drupal's part for the processing of the form. You would need to find an alternate method for getting the secondary form on the page, such as using the block system to embed the second form on the page.


You could set something like this up, by using Rules+Mime Mail+IFTTT.

Set up a recipe in IFTTT that

Gets triggered when it receives an email by a specific address
Posts on Pinterest as a reaction, using the attachment in the email
https://ifttt.com/channels/email/triggers/50-send-ifttt-an-email-tagged

Configure Rules to send an email on an appropriate event, e.g. node updated/created

You need to use the Mime Mail to get the option to add attachments to your outgoing email
Check out this video for further information: Learn Drupal - Send email with attachments via Rules
You may need to configure your Drupal instance to use SMTP authentication on yor outgoing server to make it work with IFTTT. The PHPMailer module will probably help you with this.

Hope this helps, good luck!


Is there a way to remove tabs inside panels?

From memory, I believe the answer is no, because the tabs are rendered outside of the area that Panels is responsible for.

If you use Panels everywhere, then you can simply leave the tabs out however, "In panels". If you don't, the rendering is probably happening in page.tpl.php instead.


How can I survey anonymous users before they can read content?

Thanks for the help.

I ended up using the rules module along with rules url argument module.

I used the rules module to watch out for anonymous users, and query strings of "?surveycomplete=yes". I did this check for all nodes of my desired type that did not have a node reference to a webform.

If a user was anonymous and did not have the query string, then I redirected to the webform that the node was associated with.

To make the webform redirect appropriately when it was completed I changed the redirect location to the original node with the query string appended.

The downfalls with this approach is that every node that there is a 1 to 1 relationship for content to webforms when a many to 1 would be nice. Also, anyone could technically by pass the survey via appending the query string.


Allow authenticated user to create an article

Go to admin/people/permissions and check the permission "Article: create content"
and maybe on a block create a link for them called create content.


How can I show a parent page's field on all subpages?

For posterity, here’s the solution I came up with.

I turned my Banner Image into its own content type, used the nodeblock module so it would automatically be usable as a block, and then just scoped that block to myParentPage and myParentPage/*.

It’s not the elegant solution I wanted, I was hoping to give the user a one step process that would also keep them from creating top level pages without a banner image. But it gets the job done, so I’m happy enough.

Thank you Kevin for getting me on the right track!


By default it is and condition

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result->condition('ur.rid', 6, '<>');

// if you have devel installed check this.
dpq($nids_result);
$nids_result = $nids_result->execute()->fetchAll();

debugging the query with dpq will tell yuo the exact query that you can run on phpmyadmin and can see what you are missing.

Updated:

if you need query like

SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {users} u ON n.uid = u.uid
INNER JOIN {users_roles} ur ON u.uid = ur.uid
WHERE ( (ur.rid <> :db_condition_placeholder_0) OR( (ur.rid <> :db_condition_placeholder_1) AND (ur.rid <> :db_condition_placeholder_2) ))

Code will be :

   $nids_result = db_select('node', 'n');
   $nids_result->join('users','u','n.uid = u.uid');
   $nids_result->join('users_roles','ur','u.uid = ur.uid');
   $nids_result->fields('n', array('nid'));
   $db_or = db_or();
   $db_or->condition('ur.rid', 7, '<>');
   $db_or->condition(db_and()->condition('ur.rid', 7, '<>')->condition('ur.rid', 6, '<>'));
   $nids_result->condition($db_or);
   $src = $nids_result->__toString();
   dpm($src);


You want #limit_validation_errors. Setting this value to an empty array will mean that nothing is validated when the button is clicked.


How do I limit a taxonomy dropdown exposed filter to the terms used by nodes in view results?

Like you can already read on the bug report from Drupal.org which you've copied from, a good solution is to use Views Selective Filters. It does exactly you're asking for.


Use taxonomy path for a node's path alias

Using pathauto, it should be quiet easy with a pattern like :

Normal way :

news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

With hierarchy :

news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:parents:join-path]/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

In your case, this should work

[node:{NAME_OF_TAXONOMY_FIELD}:entity:url]/[node:title]


You're on the right track, but you're missing another Relationship.

You've added the Relationship that points to a referenced Page. Now you can show that Page info in your views, but that isn't what you want. You want to show all other articles that reference that page (siblings).

To do that you need to add another Relationship that goes in reverse, from Page back to article: Content using field_page_reference and make it use the first Relationship (this is where the matching is happening!).

Then modify your ID Contextual filter to use the second Relationship.

Now you'll have a list of all articles that reference the page that is referenced on the article you're currently viewing.

That includes the current article BTW, so if you want to exclude it from the list you have to add another ID Contextual filter "Content Id From URl" but don't use any Relationships and under More select Exclude.


Custom text output for entity reference fields

Two different options here (there are probably more!):

Use the linkit module in combination with wysiwyg and, say, the tinyMCE editor. This allows users to insert node reference links into wysiwyg text areas.
a.  Create a textfield for the link text in addition to the entity reference field.

b.  In the template file for the content type (node--CONTENT_TYPE.tpl.php), output the links manually, something like:

$path = 'node/' . $node->YOUR_ENTITY_REF_FIELD['und'][0]['target_id'];

$link_text = $node->YOUR_LINK_TEXT_FIELD['und'][0]['value'];

print l($link_text, $path);


Prevent Serialization or Unserialize via ODBC

In normal circumstances you shouldn't edit raw database tables to make changes; there's an extensive API in place which you should use instead (whether that be via the UI, through custom code, interacting via REST, whatever).

Updating tables manually means you deny module hooks the chance to run, potentially leaving your site in an inconsistent state. Not to mention the fact that caches won't be invalidated, leaving your front-end inconsistent for a time.

To directly answer your questions:

A) I'm not sure what you mean by 'datasets' here. If you mean, how do you update a bunch of values for a bunch of entities (e.g. nodes) in one go, then the Views Bulk Operations module should be useful.

B) The data you're referring to is serialised using PHP's serialize() function. You can decode it with unserialize(). I can't comment on how you'd do that in, for example, Excel. Perhaps you could write VBA functions to mirror serialize()/unserialize() and apply them to the incoming/outgoing data?

C) You can't stop Drupal from serialising that data, it's baked right in. Well, you could theoretically do it, but it would be an awful lot of work. You'd probably also find the need to change a lot of contrib modules who rely on the known schemas.

D) I haven't used it personally, but I've heard good things about the Data module. Might be worth checking in to. Feeds might be of interest too.

To sum up: Providing users the ability to make changes to the site by directly manipulating database tables, outside of the API, isn't really one of Drupal's goals (or not one that I've seen mentioned before). If anything, I'd imagine they want to discourage that for the reasons I've mentioned above.


Form displays without  after page renders

$attachment_form = drupal_get_form('invite_attachment_form');
echo drupal_render($attachment_form); //That should work

see https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7.x


theme_get_settings() was removed in Drupal 7. Instead, use theme_get_setting(). This works:

<?php

if (theme_get_setting('toggle_logo')) {
  $image = array(
    'path' => theme_get_setting('logo'),
    'alt' => 'my logo',
  );
  print theme('image', $image);
}

?>

theme_get_setting() will get the current theme's setting, but if you want an arbitrary theme's setting, you can use the optional second parameter as described in the API docs. I used theme_image() to make it less fragile.

But if you can avoid the use of the PHP filter, you really should: consider creating a small custom module that creates a block with the code instead.


Can't get custom content type page template to load

I'm totally an idiot. I tried this code previously but it didn't work, which is why I ended up with the code above (also didn't work).

I realized that in the code I tried the first time I failed to change the first line to my theme's name:

<?php
function thisshouldhavebeenmythemename_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__node_' . $variables['node']->type;
  }
}
?>


How to programmatically add a filter that requires a relationship to a view

I figured this out by a stroke of luck after posting this. Here is what I did:

// Get a list of all relationships on the view display
$relationships = $view->get_items('relationship', $display_name);
// In case there are no relationships, set this to null by default.
$last_relationship = null;
if (!empty($relationships)) {
  // @todo: is the last relationship always the one whose ID goes with the returned entities?
  $last_relationship = array_pop($relationships);
}
// Filter out the (un)desired item.
$options = array(
  'operator' => '!=',
  'value' => array('value' => $id),
);
if ($last_relationship) {
  $options['relationship'] = $last_relationship['id'];
}
$view->add_item($display_name, 'filter', $view->base_table, $view->base_field, $options);


Separate Display for Start date and End date using Date module

There a few options. If you're comfortable with code you could add a preprocess hook to duplicate the date field and manipulate its configurations. That is a little heavy-handed and hard to maintain.

With the Panels suite of modules (particularly panelizer module) you get the ability to do things like take over entity view modes. Then you can place fields as "panes" as many times as you want with different configurations.


How do I output HTML from a text_long field in Twig?

Normally you would configure the display of the field in UI.
You can do this in code by using the render element processed_text.
PHP
  $build = [
    '#type' => 'processed_text',
    '#text' => '
Hello world
',
    '#format' => 'full_html',
  ];

TWIG
In twig you would use instead of the extremely unsafe {{ event.getExternalDescription | raw }} this code:
  {% set build = {
    '#type':   'processed_text',
    '#text':    event.getExternalDescription,
    '#format': 'full_html',
  } %}

  {{ build }}

The safety of the text format depends on the configuration of the text filters and the content of the field. Apply the same security considerations as you would for text formats in ckeditor.


Get all available promotions for specific commerce product

You can do it via commerce_order.price_calculator service:
$context = new Context($this->currentUser, $this->currentStore->getStore(), NULL, [
    'field_name' => $items->getName(),
]);
/** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
$purchasable_entity = $items->getEntity();
$adjustment_types = array_filter($this->getSetting('adjustment_types'));
$result = $this->priceCalculator->calculate($purchasable_entity, 1, $context, $adjustment_types);

//Get promotions
$promos = $result->getAdjustments();


How can I get Elysia Cron to run every 15 minutes?

Given the explanation in your question about how you've set things up, at least one reason your external cron does not ping Elysia Cron is that you've got the key wrong, or that the key is missing.

You need to up look the right key. Navigate to Elysia  » Settings  » Installation Settings  » Cron key and copy the key has you find there so that your Cpanel setup to looks like this:

http://example.com/sites/all/modules/elysia_cron/cron.php?cron_key=ZvMtg5HAaRzjz5NtkwoDs0F3jOWrbpIX5JVi3ACJl7Q

Note: Use the actual key you find on your site - not the dummy key I use as an example.


How to change the field label in an API response

Go to field settings of the Rest export view, add Alias for each field, Save.
That's it. You're done


Webfm and views; can I create a view that has a list of links to the files?

Actually just started working on this myself this morning.  The answer is yes, you can, but as far as I've read into it, the view can't be part of another view, i.e., you have to create a separate view just for WebFM files.  You'll see it when you go to Views > Add > View Type.

Like I said, I just started working on this this morning, so I haven't gotten any further than that, but HTH.  Maybe post progress here for sharing?  Funny that your question came up in teh Googles.


You can get the hostname, "drupal8.local", directly from the getHost() request:

$host = \Drupal::request()->getHost();

In some cases you might want to get the schema as well, fx https://drupal8.local:

$host = \Drupal::request()->getSchemeAndHttpHost();


How to change the user-profile.tpl.php file to a customized outline like Linkedin for Drupal 7?

You can utilize views module to achieve what are you looking for, with some CSS styles.

While using views you have two options view user information:

Option 1:

Create block view (Users)
Select user fields you want to display
Then add Contextual filters (User: Uid)
From the configuration page make sure to select Provide default value
Then from Type drop down menu select User ID from logged in user.
Then apply changes.
Save view.
Under Structure -> Blocks locate the new created view in content region
Configure the block to appear only on the user account page user and users/*
Then you need to clear the original drupal content in the user view account page by apply this custom module.

Code:

function mymodule_menu_alter(&$items){
  $items['user/%user']['page callback'] = 'mymodule_user_view_page';
}

function mymodule_user_view_page() {
  return array();
}

Option 2:

Create page view (Users)
Apply steps 2-6 as Option 1
Add Path user/%user under Page Settings
Save view.


How can I programmatically recalculate an order total after changing the billing country

I've recently run into the exact same problem as you after changing the shipping address in an ajax call.

commerce_order_calculate_total() was the function that got everything working as expected for me.

You may or may not also need to use commerce_cart_order_refresh().

First try without but if you are still not seeing it updated then try both.

If possible run these functions directly before your actually sending the order total value to be rendered.


X-Drupal-Cache header not always appearing on page

The behavior you're seeing is the result of having a browser cache. After the first request, your browser caches the document and keeps track of its  signature through the Etag/Last-Modified headers.

Upon subsequent requests, the browser makes a request to the server with the If-None-Match/ If-Modified-Since headers. If the document hasn't changed, the server returns a HTTP 304 Not Modified which tells the browser it's okay to serve its cached version of the page.

Because cURL doesn't have a caching mechanism, X-Drupal-Cache always appears; it needs to go directly to Drupal each time for the document.


Difference between hook_page_alter and preprocess_page?

The difference is their purpose.

hook_page_build() and hook_page_alter() are used to remove, alter, or add elements at the page level.
The $page array passed to hook_page_alter() contains the top level elements for each block region. By default they are the following ones:

page_top
header
sidebar_first
content
sidebar_second
page_bottom

An example of implementation could be the following one:

function mymodule_page_alter(&$page) {
  // Add help text to the user login block.
  $page['sidebar_first']['user_login']['help'] = array(
    '#weight' => -10,
    '#markup' => t('To post comments or add new content, you first have to log in.'),
  );
}

The preprocess functions are called to alter the variables that are passed to the template file. They cannot change the structure of the page, but they can alter the content of some elements of the page changing the content of those variables.
For example, the Overlay module removes the primary tabs when the page being visualized is the overlay.

function overlay_preprocess_page(&$variables) {
  if (overlay_get_mode() == 'child') {
    unset($variables['tabs']['#primary']);
  }
}


DB queries fast, Apache response slow, high PHP CPU

I would suggest trying to use drupals caching to cache the page and installing a php caching system such as APC or OP cache (if using php 5.4 or higher for OP caching) and this should speed up significantly.  If you really want a performance hit then try using varnish to cache the pages.

The reason is by default apache does not do a very good job rendering pages in the sense of requests per second and can significantly increase when caching and exponentially increase using varnish caching.

So in short the following is good for performance:

PHP:
1. ) APC cache or OP caching.
2. ) Varnish caching
3. ) MYSQL caching such as memcache


how to override the HTML of the search results page?

Hope this will help you,

In Drupal 7, you can also achieve this

Using theme_search_results OR theme_search_result to override search results page.

theme_search_results : invoked for the search result page.

OR
theme_search_result : invoked to render a single result

Both these theme functions used in a template file (search-results.tpl.php and search-result.tpl.php).

Source


Ok i solved that problem my own. I have deleted the Drush Version 7.x and installed the 6.x Version. it works like a charm.


How do I define a custom html.html.twig file?

If you want to return 'render element' this would be 'html':

'render element' => 'html',

But you probably don't need this, better return the base hook so that drupal fetches the variables from the hook html:

function mymodule_theme() {
  return array(
    'html__ajax' => array(
      'base hook' => 'html',
    ),
  );
}


Override module function in my custom module?

The error is how you define the parameters, which should be defined as custom_mixpanel_defaults_alter(&$properties, $account).
PHP 5 automatically passes by reference any object passed to a function, but not the arrays. Since $properties is an array, you need to make the reference explicit.

Generally speaking, when you see a call to drupal_alter() like drupal_alter('node_view', $build), and you need to implement that alter hook, check the second and third parameter are object or arrays; in the case they are array, you need to explicitly declare the parameter as reference. In this case, hook_node_view_alter() is defined as hook_node_view_alter(&$build).


How can I implement OAuth based login, just like drupal.stackexchange.com offers?

Stack Exchange uses OpenID for single-sign-on, which is not the same as OAuth.  The good news is, OpenID is built-in to Drupal core.  The downside of using the core module is your visitors must know the URL of their OpenID provider.  Most people already have at least one OpenID provider, but don't know it.

To solve this problem, you could try OpenID selector, which offers a login selector similar to SE.


Using Fivestar to list items that are 'trending' (highly rated in the last week)

Fivestar uses voting API. Voting API stores the individual votes and the total aggregates. You'll either have to create your own aggregates or calculate it "on the fly".

If you have lots of ratings in a week you'll be better off calculating your own aggregates. I would take a look how voting API does the calculation and copy that to your own module. Then modify it to only aggregate votes in the last week.

If you don't have a lot of ratings you can do it in views. Create a view of your type "watch detail". Add relationship "content: votes", require relationship, value type "percent", vote tag (whatever vote tag you are using for those fivestar ratings).
Then add filter "votes: value" >= 80 (gives you all 4 + 5 star ratings), "votes: timestamp" > "-1 week". Check to make sure you'll see the correct ratings show up.

Now turn on aggregation, add "nid" and use "count distinct" to show the number of ratings for each node. Then sort by that value.

Turn on query caching to make sure the view renders quickly for future requests.


How to add outer div to Profile2 profile including link set in #prefix

The Profile2 modules implements a profile2_form_alter hook that you can implement in a module. Say you have a module called kelley_profile2, then the function you want to implement is

/**
 * Implements hook_form_profile2_form_alter().
 */
function kelley_profile2_form_profile2_form_alter(&$form, &$form_state) {
  // Check profiles key exists in $form_state.
  if (array_key_exists('profiles', $form_state)) {
    // Iterate through each profile type and add prefix.
    foreach ($form_state['profiles'] as $type => $profile) {
      $form['profile_' . $type]['#prefix'] = '';
    }
  }
}


How to embed my webiste Header(logo, menu) for each of my panel variant

Create a block with the required Header and then assign that to your content regions in panels. I think that should be it.

And yes, you can theme your block as required using block--block--[block-id].tpl.php templates.


Just a quick answer to my question for other drupal noobies making the same error as I have.  There seems to be a bit debate between installing stand alone ckeditor or installing ckeditor via durpal's wysiwyg module (convenient for installing multiple wysiwyg editors, if need that level of choice).  For more info read this.

At the risk of drawing wrath, with drupal, "more modules" = "more chances for errors and conflicts" so I am go with the stand alone ckeditor install.

First install the ckeditor drupal module, from the drupal project page.

Then, download the BASIC ckeditor script library from ckeditor.com .

NOTE: DO NOT ATTEMPT TO ADD PLUGINS AT THIS POINT, JUST DOWNLOAD THE PLAIN, VANILLA, CLASSIC DOWNLOAD. This is what caused the error above, some plugins do NOT "play nicely" with drupal.

After you have the download of the plain ckeditor script library downloaded, place into the  /sites/all/libraries/ directory, so that you end up with /sites/all/libraries/ckeditor/ckeditor.js  file structure.

Then in your drupal site go to /admin/config/content/ckeditor  and edit the "Global Settings" , so that the "Path to ckeditor" is  %l/ckeditor (sites/all/libraries/ckeditor) and the "Path to plugins" is %m/plugins (sites/all/modules/plugins)

NOTE: By default ckeditor points to a web address (CDN) for the "path to editor" value, which is mighty inconvenient if you work offline on a local dev server without internet from time to time.

Save Configurations

Assuming your install was successful, meaning that you did not have any red text drupal messages at /admin/config/content/ckeditor page complaining about missing libraries, you can go to /node/add/page and see if your locally installed ckeditor is working properly. If it loads, you are good to go.

Now for the fun part, adding all those plugins that made your mouth water, but you couldn't add before you downloaded the ckeditor script library.

Go to ckeditor.com make a list of all the plugins that you desire for your local, stand alone editor, then download each plugin individually.

Extract each plugin that you downloaded to your sites/all/modules/ckeditor/plugins folder.

NOTE:  DO NOT extract the plugins folder located in the drupal sites/all/libraries/ckeditor/plugins folder... all your neat plugins and hours of work will be wiped out when you update ckeditor in the future.

After all your plugins are extracted, edit your "ckeditor.config.js" file located at sites/all/modules/ckeditor.

look for "config.extraPlugins = '';" and enter the name of your plugin.  For more than plugin, separate each plugin with a " , " .

For more details on plugin installation READ THE DOCUMENTATION HERE.

I highly recommend, adding plugins one at a time and testing in your browser, so that you can easily remove the mean plugin that won't play nice with others.

At this point go back to /admin/config/content/ckeditor and edit INPUT FORMAT that you want to use with ckeditor.  Look under "Editor Appearance" and scroll down, your added plugins should appear as checkbox options. Select the ones you want...then get back to "drupaling" :-)


How do I show a progressive number such as "Item 1 of termName", "Item 2 of termName"?

I know that you can set the format to html ordered list and group by the tag, but that will number the items automatically as in a standard ordered list with no control of the placement or prefixing with "Issue #". See Number items in a grouped view, resetting counter with each group, for example.
I think the views_php module with some custom coding could possibly work. I'll admit I have difficulties in getting parameters to reset effectively at times, but perhaps your mileage will vary.


User order views does not display orders for user despite permission

You've most likely edited the View to include a new relationship - perhaps from line items to products - that adds an access check to the View's results that the user doesn't pass. If this is the case, open your View's "Advanced" fieldset, edit the "Query settings", and check the box to "Disable SQL rewriting".


Minutes in date value displayed never the same as value entered

Well, turns out the discrepancy was due to a bad date format ... I was using "m" for the minutes instead of "i".

My bad !


How do i use views with a custom entity?

If you used entity API module, then this is done pretty much out of the box, see my blogpost on Integrating entities with Views for more details.

If you didn't use entity API module or don't want to, you can make the views integration yourself using hook_views_data.


Possible to make admin's flags worth more points?

Flags work like an on/off switch. Depending if the Flag is global or not, that on/off switch can apply to every user (each user can have a separate room w/ the lights on or off), or globally - every user is in one room, with only one light bulb, and one light switch.

Basically what you're asking is: is it possible to turn on the lights on twice?

No. In our light bulb analogy, that Flag switch doesn't come with a dimmer option ;)

What Rules allow you to do is aggregate the count of the Flag "votes" by multiple users (when not using global flags), and execute an action based on the sum of user "flags". But that is not what you're looking for.


How to get all terms with services module?

You need to grant permission for Perform unlimited index queries at admin/people/permissions. Alternatively, you can set this in settings.php:

$conf['services_taxonomy_term_index_page_size'] = 200;


Programmatically check the checkbox of an exposed filter

I was finally able to achieve what I need via the hook_views_pre_build() hook.

Please let me know if this is wrong or if there is a better way, but from what I can tell this is the best way to achieve this.

function module_views_pre_build(ViewExecutable $view) {
  $termId = 357;
  $view->setExposedInput(['field_name' => [$termId => $termId]]);
}


How to render multiple values of node reference in the form of an ordered list without views?

In D6, you could do something like this:

print '
';
foreach ($node->field_whatever as $foo) {
  print '
';
    $bar=node_load($foo['nid']);
    print l($bar->title, 'node/' . $bar->nid);
  print '
';
}
print '
';

In D7 you'd have to throw in the node language stuff and there might even be something more exciting built in as well but I think they all use divs instead of lists.  (In both you could also create a content field template for this instead of hardcoding it in your node template)


How to make a reset form button without type 'markup'?

Type should be reset, not button.

  http://www.w3schools.com/tags/att_button_type.asp

You right, there is no such type. I was able to get this working with 2 submit buttons and return false (similar to your original implementation).

function drupalform_form($form, &$form_state) {

  $form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
    );

  $form['submit_button1'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    );

  $form['reset_button'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
    '#validate' => array(),
    '#attributes' => array(
        'onclick' => 'this.form.reset(); return false;',
        ),
      );

  return $form;
}

If it still doesn't work there is this alternative solution: How to reset specific form elements


Use the Role Delegation module.

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.

  The module also adds an assign all roles permission. Enabling this
  permission for a role is a convenient way to allow the assignment of
  any other role without having to check all the assign ROLE role
  permissions in the Permissions page.

  If an administrator has the administer users permission, a role
  assignment widget gets displayed in the account creation or editing
  form, and bulk add/remove role operations become available on the user
  administration page. Otherwise, if s/he has at least the access user
  profiles permission, the module adds its own Roles tab to the user
  profile so that roles can be assigned.


How to redirecting add to cart form in drupal commerce programatically?

Check if you have any redirect rules enabled under admin/config/workflow/rules, which is force redirecting you to cart page.

As a solution you can have your custom redirection rule and disable the existing redirection rule, an example redirection rule which redirects to node/2 path after adding product to cart.

{ "rules_add_product_to_cart_redirect" : {
    "LABEL" : "Add Product to Cart Redirect",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "add-to-cart-redirect" ],
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [ { "redirect" : { "url" : "node\/2" } } ]
  }
}

In case you import the above remember to change the redirect path from node/2 to your thank-you page.


What can I do to improve the size of csv file that can successfully be imported via Feeds and Commerce Feeds

The 403 HTTP code translates to access denied, which doesn't points to a problem in the size of the CSV file. Since it's using the batch API, which splits up the job in smaller chunks, it doesn't look like that it is the size of the file that is the problem. You should investigate the watchdog (dblog) and see if you can find the root cause.

This is the best answer I can provide with this limited information.


Most providers block smtp ports, I had to use a mail redirection service when I set this up.

If the message gets through after 15 minutes though, I suspect you have a  mail server misconfiguration. Nowadays, I usually go for a much simpler approach, I use google's smtp server to send the emails.

An easy way you can test if port 25 is blocked is by connecting by SSH to a remote server, then trying to telnet on local server port 25.

telnet mail.port25.com 25

If the port is open, you should get a response similar to this:

Trying 69.63.149.30...
Connected to mail.port25.com (69.63.149.30).
Escape character is '^]'.
220 mail.port25.com (PowerMTA(TM) v4.0) ESMTP service ready

Another thing to check, if you are using qmail make sure the trigger file has proper permissions. qmail/queue/lock/trigger should be prw--w--w qmails:qmail.


I think you need the Node Queue module with the Smartqueue Per User.

Although it's not listed on the front page, you can now get the 6.x-2.x-dev version which does the multiple lists (or queues) per user.

I've also got a patch to make it work with the latest version of Node Queue.

This module might appear flaky because few sites use it and the issue queue is stale, but it really does work the way it's supposed to. We're using that 6.x-2.x-dev on a production site with premium content and it gives us NO problems whatsoever.


Insert a collapsible fieldset or region in a panels layout

The best I've come up with so far is a custom module's hook_form_alter to create a fieldset and move fields in.  Note that in order to avoid something like:

Notice: Undefined index: field_txt_student_id in ctools_entity_form_field_content_type_render() (line 96 of [...]/sites/all/modules/contrib/ctools/plugins/content_types/form/entity_form_field.inc).

because the field is moved and unset(), it is not known by ctools to have been moved (or something).  Its render function does basic data sanity checking but then goes with the assumption that this field still exists by name where it was before the alter.

To get around that, instead of unset()'ing the original field, set it to a non-kind-of-field per this thread.

//  unset($form[$fieldname]);
$form[$fieldname] = array('#language' => NULL);

Would love to hear what other solutions exist!  I spilled my "solutions that don't work" in a comment on your original question.


How to Apply Panelizer on already created nodes of a particular node type?

The module's lead maintainer, merlinofchaos, responded to this on drupal.org; in short, it's only possible if using the IPE, there's an option to make the changes global i.e. affect the default configuration, otherwise the changes have to be made via the entity's Panelizer tab, e.g. admin/structure/types/page/panelizer.


how to create template of user register, login and forget password in drupal 8?

Yes it same as drupal 7.

For example:

We are using page--user--register.tpl.php for registration page template in D7. In D8 changed to twig extension page--user--register.html.twig.

You can enable debug mode in D8 so you can easily see the twig file need to use in your case. You can refer Drupal 8 custom page template to see how to enable debug mode.

Some links how to override the template files.

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

https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates

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


Use Timeago date format for less than 24h ago only

Do users really sit on a page for a long enough time, that these dates need to be updated via javascript? Most of them will click on something and end up reloading the whole page at some point. So perhaps, a php solution is an option too?

You could achieve the php solution by using the Custom Formatters module.

If you create a new php type custom formatter, with the following code (make sure it's a datestamp type):

$element = array();
foreach ($variables['#items'] as $delta => $item) {
  $unixstamp = $item['value'];
  $time_since = mktime() - $unixstamp;
  if ($time_since < 86400) {
    $date_str = format_interval($time_since);
  }
  else {
    $date_str = format_date($unixstamp, 'custom', 'jS F Y');
  }

  $element[$delta] = array(
    '#type' => 'markup',
    '#markup' => $date_str,
  );
}
return $element;

When creating the formatter, make sure you select field type 'datestamp'. Once the formatter is created, then in the manage display tab of your content type, set the field to use this formatter.

If you don't have your date stored as a separate field, you might be able to apply the custom formatter to the node modified time, by installing the Display Suite module.

If you don't want to use any of these modules but want to hack some php into your theme or something, you can still use the same logic above with format_interval and format_date functions.

Hope that can help.


How to notify a user who's mentioned in a comment?

You can do it this way:

Copy the function function mentions_get_mentions($text) from mention module repo, It's defined on line 359.
Unfortunately I can't say if the regex from mention module actually works for user's with space in their name, and the function doc comment is not helpful either. So you could use your own regex

What kind of regex?

#\s?@([a-zA-Z0-9 ])+(?|[^a-zA-Z0-9 ]|$)#

How did I do it?

#                  : Identifies beginning of the RegEx pattern.
(?|^|[^a-zA-Z0-9]) : match any non-username chars or beginning of subject string.
@  : A plain @ char is needed.
([a-zA-Z0-9 ])+    : match any username char after a "@" including whitespace.
(?|$|[^a-zA-Z0-9]) : match any non-username chars or ending of subject string.
#                  : Identifies ending of the RegEx pattern.

Now all you have to do is to write a custom rule, pass it a text variable, and get list of user entities (or uid's) back. You could make sure users who matched through regex actually exists in database too.

A few more notes

A ? in regex causes the group NOT to appear in matched groups. Useful when you need to define a group but don't need it in the array of matched strings.
^|[^a-zA-Z0-9] means beginning of subject string or (the | is or) any char which is NOT (said by ^ in []) in ranges a-z, A-Z and 0-9.

Does this regex have bugs? yes

The returned user name(s) from regex can have an space at the end of their name, you could trim each name. It will be easier than to fix it in the regex pattern IMO.
It displays a funny character in my shell when matching an string with unicode characters in them. preg_match supports such multi-byte characters though, and the u flag dis not work.

But again first check the function from mentions.

References:

Mentions module
PHP preg_match doc
Writing custom rules for drupal, Rules DEV doc
Writing custom rules, A blog tutorial

one more thing I couldn't find in google right now: there is a module for rules which provides text tools, I think it had regex matching and you wont need a custom module.

What is this "Regex" you're talking about all the time anyway?

RegEx stands for Regular Expression. It's a search pattern and is extremely very powerfull. While itself can be complicated (sometimes), many task which usually take a lot of time and effort to be done, such as parsing a text, can be done using regex in one line!In this case we are looking for usernames in a paragraph in order to turn them into links. First we describe what a username looks like (the text patterns of username): any part of text which begins with letter, followed by a sequence of more letters and numbers.
Then we write it as a RegEx (What I've done here) and later extract usernames by passing both text and RegEx pattern to preg_match function and taking usernames array back (the function is preg_match).
If I want to talk about all the benefits it wont fit in here, so I suggest you a little search on duckduckgo. It's a handy tool to have, a powerful one try to learn it :)


Hook to trigger when a field collection item is being deleted

What you should do instead of an API call on delete is create a job with the QueueAPI in Drupal to create a job for processing later. In that job, pull the ID from the record (stored in the job) and do the API call. If the status failed, requeue the job.

I can’t write all the code out for you but there are plenty of QueueAPI examples for D7 out there.

https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7.x

and

https://rbayliss.com/blog/drupal-queue-api/

Are great starting points.

You could then create a custom Drush command that processes  these jobs as fast as you desire. Note the section in rovs post that deals with “failed” states of a job and not removing it from the queue. That is key.

This will let Drupal function normally and defer errors in the remote system to you to work through.


You probably need to index the referenced entity Name* (assuming you want to search on name) as a field instead of just simply the entity ID (which is what entity reference fields actually store). The pattern should look something like the following on the 'fields' page:

field_yourfield:entity:name


Content type permission to specific users

The core's built-in support for node access control is rather course, and to control a specific role's access to view a page, it is not enough to go to admin/people/permissions to set permissions, since there is only a global setting for "View published content" that apply to all published content.

However. to give the permission to Create new content (node/add), there is no need for an extra module, since all other permissions, i.e. Create, Edit, Delete, is managed by the Drupal core and there are per-role settings in the built-in permissions interface.
First, just to make sure content is visible, navigate to admin/people/permissions and make sure you have the permission View published content checked for the authenticated user role.

Then, just below it, locate the check boxes to "Create new content" for the content types you want users beyond the administrators to be able to create, and check those for the roles you want to have this permission granted (ditto with the Edit and Delete permissions).

Also make sure new content is Published. If content is not Published, the only user that has access to it us the super admin user.

To set the default to Published for a new content type, navigate to Administration → Structure → Content types. Then click on the edit link for the type you want to configure- Locate the "Publishing option" tab. and make sure that there is a tick mark for "Published" under "Default options".

If you need fine grained access control beyond this, you need to install a node access control module.

The module I recommend for this is Content Access.  It let you control access per content type and user role.

To set the per content access settings, navigate to Administration → Structure → Content types. Then click on the edit link for the type you want to manage, and then on the Access control tab. This takes you to the control panel for role based access control settings. The screen dump below  shown how do set this for the built-in content type "Basic page":

After setting the permissions the way you want, click "Submit".

There is a nice tutorial about installing and configuring the Content Access module on YouTube. (Thanks to @shrish for bringing this to my attention.)


How can I label content in views as "new"?

I have some suggestions, ranked below sort of from simple to complex.

You can simply add a static text field to the view, write "New" in the text field, and then filter the view to contain only content from the period you want to have the "New" label on them.
If you want the same list to also display more content, create an attachment display in the same view, override the text field and the date filter, and set the display to attach after the first one.
Use the Theme information in the view to directly override the views output. Find the content id in the template, load the node, and check the creation date.
Render the content through a view mode instead of on a field by field basis. In the the node-template, you can now check the creation date of the node and output the label. This solution would possibly benefit from an added 'per-view-mode' theme suggestion.


How to make a checkbox field required when a radio button is selected.

In form alter use this code

function my_module_form_alter(&$form, &$form_state, $form_id) {
      $radio = $form['#node']->field_radio['und'][0]['value'];

      if($radio == 1){//if
         $form['field_checkbox']['und']['0']['value']['#required'] = TRUE;
         //OR
         $form['field_checkbox']['und']['0']['#required'] = TRUE;
      }
}


Using "Rabbit Hole nodes" and "Facebook Like Button"

Perhaps consider using Page Manager (part of Chaos Tools) to redirect users instead of the Rabbit Hole nodes module.

On the Page Manager admin page (Structure -> Pages) edit the node/%node page
Make a an HTTP response variant that redirects the user to site/#node-NUMBER when they are trying to reach site/node/NUMBER.
Set the selection criteria for that variant depending on the user agent (i.e. don't use this variant when facebook is looking).  This will  require a custom php rule.

There is an excellent Page Manager tutorial here.


$node is already available in page.tpl.php on node pages without you having to do anything. See the documentation


Views relationships with two views blocks

In this case I think you need one view who shows title, date and body.

So now you will have a full list of all the news and through jquery you can do something like this.

 $('.field-name-body').hide(); //it hides all the body fields.
 $('.views-row').click( function() { // The body is a children of the row.
$('.field-name-body').hide(); // it hides all the open body fields if there is one.
  $(this).children('.field-name-body').show();
});

Do you want something like this?
Fix the css with more specifications (view name, block name...)
With the css you can do the style you want.

If you want to have two different blocks you need to show in one view all the title fields and in the other view all the body fields.
You don't need contextual filter for the second view (a part from the company id). You will show all the body fields and then hide them.

Now you need to change the files views-view-unformatted.tpl copy it from views/theme, paste it into you template folder inside your theme and rename it with the name of the view.
To find the name of that view, you have to open your view, on the third column you click on theme and you will see the files and the suggested name to specify that view (views-view-unformatted-YOURVIEW-BLOCK_1.tpl or something like this). Do it for both views block, they have to be different, one could finish with block_1 and the other with block_2.
Clear the cache after you rename the files.
In the views you can add the node id and exclude it from display.

This is views-view-unformatted.tpl

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

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

AND YOU CAN MODIFY ADDING THE ID IN THIS WAY WITH $view->result[$id]->nid;

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

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>" id="<?php print $view->result[$id]->nid; ?>"> // in the body view use body-id
    <?php print $row; ?>

<?php endforeach; ?>

So, now again the js

$('.field-name-body').hide(); //it hides all the body fields.
$('.field-name-body:first').show(); // It will open the first news.
$('title:first').addClass('active');// add class active to the first title
$('.title').click( function() { // The body is a children of the row.
$('.title').removeClass('active'); // remove class active to all the title
    $('.field-name-body').hide(); // it hides all the open body fields if there is one.
    $(this).addClass('active'); //add class active to the clicked element
    var activeBody = $(this).attr('id'); //find the id of the clicked element
    $('#body-'+activeBody).show();
    });


I think this is a good example for using custom formatters.

I Recommend you to use the custom formatters module as you cant get a fast result, but if you think this is useful, you should check the Field Formatter API to make more complex sollutions.

Install the module, and import this example:

$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'test_body';
$formatter->label = 'test body';
$formatter->description = '';
$formatter->mode = 'php';
$formatter->field_types = 'text_with_summary';
$formatter->code = '$output = "";
foreach ($variables[\'#items\'] as $item) {
  if ( $item[\'summary\']) {
    $output = $item[\'summary\'];
  }else{
     $output = $item[\'value\'];
  }
}
return $output;';
$formatter->fapi = '';

it doesn't do all the job, but i think it can be enough for you to complete it.

Then go to your view and select the formatter for the body field.


What is the deal with config collections?

Collections are for configuration overrides. Mainly used for translations, but could be used for other purposes as well. You can list the available collections in your Drupal installation, starting with the default collection (empty string):

$collections = \Drupal::service('config.manager')->getConfigCollectionInfo()->getCollectionNames();

More info https://www.drupal.org/node/2268523


Below are the steps without touching the files and using the drupal admin interface.

Go to admin/config/search/metatags/config/global:frontpage/edit
Add the Page title, Description etc and Save
Refresh the front page and check. Done !!


There are many different ways to add markup to a form in Drupal 8.  In your build array, you could add a wrapper element, and then nest the form within:

$build['wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'my-form-wrapper', 'class' => ['my-form-wrapper']],
];

$build['wrapper']['form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

Alternately you could add a '#prefix' and a '#suffix' to your form.

$form['#prefix'] = '
';
$form['#suffix'] = '
';

Or you could use a template for your form and add it to your theme, using the suggestion form--form-id.html.twig and add custom markup there.  (Be sure to replace underscores with hyphens in the template name.)

  <form{{ attributes }}>
    {{ children }}
  </form>
</dv>


Why can't I add an existing field to the user accounts on Drupal 8?

Yes this option has been removed, a field cannot be shared across entity types.

You can, however, add the same field again, I.e. use the same name. Whilst they will share a name, they will be separate fields.

The reason for this is storage. In drupal 7, field storage was separate to entity storage, which meant a mismatch. In drupal 8, entity storage also handles field storage. This means if for example mongodb wants to store an entity and it's fields as a single blob/document - it can. On drupal 7 this would have required two blobs, one for the entity and one for the fields.


It looks like you are using adminimal as admin theme, so go to themes/contrib/adminimal_theme/css/adminimal.css and paste this code in the bottom.

.toolbar-icon.toolbar-item {
  display: none !important;
}

It should do the trick.


Copy path to variable in array using Kint

It seemed there was no solution so I just copied the search_krumo module and changed it a bit so it works with Drupal 8 and kint and made search_kint.

I've only just done the first push so isn't showing as a download yet; and there is only a development snapshot release, at the moment, but it's something to get started with.

So far, it has worked well with my testing.

EDIT: search_kint now has a full release.


How to load aggregated styles / js in an 'external' script via DRUPAL_BOOTSTRAP_FULL?

Here's the gist of it (w/ commentary).

<?php
// ... your code
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// get current theme and it's variables
$current_theme = variable_get('theme_default','none');
$themes = list_themes();
$theme_object = $themes[$current_theme];

// uncomment to display structured information about $theme_object
// var_dump($theme_object);

// get current theme path
$theme_path = dirname($theme_object->filename);

    // get path of each stylesheet from current theme
  $final_stylesheets = array();
    if (!empty($theme_object->stylesheets)) {
    foreach ($theme_object->stylesheets as $media => $stylesheets) {
      foreach ($stylesheets as $name => $stylesheet) {
        $final_stylesheets[$media][$name] = $stylesheet;
      }
    }
  }
  foreach ($final_stylesheets as $media => $stylesheets) {
    foreach ($stylesheets as $stylesheet) {
            // will print relative path to the stylesheet
            // here you can wrap each stylesheet in <link type="text/css" ....> tags
            // and compose the output for hte head section of your script
            print $stylesheet;
    }
  }

    // Do same for scripts
  if (!empty($theme_object->scripts)) {
    foreach ($theme_object->scripts as $name => $script) {
      $final_scripts[$name] = $script;
    }
  }
  foreach ($final_scripts as $script) {
    print $script;
  }
?>

all you have left to do is to wrap each $stylesheet and $script in appropriate tags and insert that into the head.


Solution for Drupal 8 that worked for me:

  create sites/default/files/styles folder manually
  set its permissions to 775
  create .htaccess file in this folder with following content:

<Files *>
  SetHandler none
</Files>


Line breaks with theme settings textarea

Try to use "text_format" type.

 $form['foo_example'] = array(
   '#type'          => 'text_format',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
   '#format' => null, //I think "null" saves the default text format of your website. If you want to see your changes you must put a dynamic value.
 );
}

NOTA BENE: the values saved by this type of textarea, is an array with "value" and "format" keys:

$var_saved = array(
'value'=> 'something',
'format' => 'full_html', //could be filtered_html, plain_text or any custom text format you've created.
);

//in your field definition
'#default_value' => $var_saved['value'],
'#format' => $var_saved['format'],

I didn't test it for your case, but choosing the right format, will normally output the text with respect of the rules chosen for that format type.

If I understood well your problem...


How to Bulk delete the document from solr without actually deleting the node?

I found the answer on exploring the apache solr module,

STEP 1

Select the nodes from the node table alone or by joining the apachesolr index entities table,

// Check for unpublished content that wasn't deleted from the index.
  $table = apachesolr_get_indexer_table('node');

 // Select the nids from the node table
  $query = db_select($table, 'aien')
    ->fields('aien', array('entity_id'))
    ->condition('n.nid', 0);
  $query->leftJoin('node', 'n', 'n.nid = aien.entity_id');
  $nodes = $query->execute()->fetchAllAssoc('nid');

STEP 2

Chunk it to some limit and call the apachesolr_index_nodeapi_mass_delete function

      $node_lists = array_chunk($nodes, '100', TRUE);
  foreach ($node_lists as $nodes) {
    watchdog('Apache Solr', 'On cron running apachesolr_nodeapi_mass_delete() on nids @nids', array('@nids' => implode(',', array_keys($nodes))), WATCHDOG_WARNING);
    if (!apachesolr_index_nodeapi_mass_delete($nodes, $table)) {
      // Solr query failed - so stop trying.
      break;
    }
  }


Display Ubercart Attributes and Add To Cart button in separate locations on product node page?

Create a new product template for your product node type.


Error: Cannot redeclare class becuase of entity self reference

Ok so the problem was in the namespace:

namespace Drupal\mymodule;

From my observation (can't find this in the Entity API documentation entities are supposed to be placed in the src/Entity (which I did) which imposes the Entity namespace. So fixing the namespace solved my issue.

namespace Drupal\mymodule\Entity;

What a stupid way to spend a half of a day. Looks like I'm too used to class loaders that will simply not find the class if you place it in the wrong directory.


Access denied to my route, created in module.routing.yml

The issue, as mentioned in the comment was my indentation.  I will leave this for anyone that may run into this issue.


How can I name the template file for the edit page of a certain content type?

function my_theme_name_theme($existing, $type, $theme, $path) {
  return array(
    'story_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'node-story-edit'
    )
  );
}

This code from here worked for me, for example for the story content type.


The way I've handled this is by adding a extra $_GET parameter to the end of the lightbox link url-s. For example if the url is http://www.example.com/somepage then you could turn it into http://www.example.com/somepage?lightbox=true. This can be done via javascript if it's troublesome modifying the view - might even be more suitable so that users with javascript turned off will get a better template. Then you can tell Drupal to use a different template for lightbox content this way:

function mytheme_preprocess_page(&$variables) {
  if (isset($_GET['lightbox']) && $_GET['lightbox'] == TRUE) {
    $variables['theme_hook_suggestions'][] = 'page__lightbox'; // page--lightbox.tpl.php
  }
}


You could go to admin/config/people/accounts and uncheck "Require e-mail verification when a visitor creates an account." Then create a new email rule for users who are not "Travel Agency". If you still need to require e-mail verification before the user logs in then check out the Mail Control module.


Large ecommerce sites that are built on drupal

Drupal Commerce sites:

http://www.eurocentres.com/en
http://www.commerceguys.com/customers/showcase

Ubercart  sites:

http://www.topsite.com/best/ubercart

High profile sites:

http://www.infomagnet.com/content/high-profile-high-traffic-drupal-websites

Government sites:

http://govfresh.com/2010/02/5-government-sites-using-drupal-effectively-for-open-government-initiatives/


Views removes style attribute in "Rewrite Results"

Yes, Views does block style attribute for security reasons. Class attribute is allowed.

Here's one long discussion about it https://drupal.org/node/853880 and some other ideas for workarounds Add style attribute to view fields.


Commerce: Setting Custom Form Default Values

The trick is to use

function hook_field_widget_addressfield_standard_form_alter(&$element, &$form_state, &$context) { }


How to create (& pre-populate) multiple “field collection” fields on an ajax call

The form needs to be build again after items_count is changed.

function MYMODULE_form_alter (&$form, &$form_state, $form_id) {
  if($form_id == 'MYFORM'){
    $form['#attributes']['id'] = 'MYMODULE-form-ajax-wrapper';

    // Handle triggered ajax element.
    if(!empty($form_state['triggering_element']['#array_parents'][0])) {
      if ($form_state['triggering_element']['#array_parents'][0] == 'field_node_reference') {
        $form_state['field']['field_collection_entity'][LANGUAGE_NONE]['items_count'] = '3';
      }
    }

    // Add ajax callback.
    $form['field_node_reference'][LANGUAGE_NONE]['#ajax'] = array (
      'callback' => 'MYMODULE_ajax_rebuild_form',
      'wrapper' => 'MYMODULE-form-ajax-wrapper',
    );
  }
}

/**
 * Ajax callback, rebuilds and returns the entire form.
 */
function MYMODULE_ajax_rebuild_form ($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}


how to use panel to display content types but using condition?

Create two blocks in Views, one that shows the Liquor info with a contextual filter of the nid, then a second block that lists stores again with contextual filter and a relationship to the nid of the liquor (with whatever field you are using to relate the store to the liquor).

Once your Views blocks are in place, you can then add them into your panel using the Content tab, then selecting the Content cogwheel on left top corner, then select Add Content, then in the dialog box look under Miscellaneous, you will see your Views blocks listed, add them and you're done!


max-age 60s is pretty low for the frontpage. Does the data really update that frequently or is it just that it could update but usually it doesn't happen every minute?

One possible approach to solve this would be to fetch that external data on a cron job that runs every minute. If and only if you detect a change, you invalidate a cache tag, which invalidates your frontpage. This approach is interesting when the data does not actually change that often most of the time. Because your cache is valid as long as possible.

And it has the added benefit that you do not rely on the external system when users are actually accessing your frontpage. Your block simply delivers the data from state which you update in the cron job.

That said, if you do want to influence the max-age header, then you need to implement your own Response subscriber. You could also use a module like https://www.drupal.org/project/cache_control_override, but you have to carefully test different pages to see if it might disable caches in more places than you expect, e.g. a language switcher block can currently do that.

  And uninstall the Internal Page Cache, it caches even uncacheable responses like this and you don't need it if you use Varnish

If and only if you have cache tag invalidation configurated and integrated with Varnish. If not, my recommendation would be to use the internal page cache module and set the default external max-age to a very short time, e.g. 1 minute. Then varnish can cache responses for that long and will revalidate against the internal page cache after that time.


What you're seeing is the result of the Drupal service container failing to create a service because its cached definition doesn't match the class anymore: An extra constructor argument was added (in this change), and Drupal is not passing that argument.

This is a typical error that can happen after updating modules. Make sure to completely empty your cache manually. You might be able to do this using drupal cr all or drush cr or by visiting the admin backend, but not if the service is already loaded during bootstrap. In that case, try to empty the cache_container database table directly.


Add profile name field into the user page

You can print the user name when a user is logged in using something like this...

<?php print t('Profile of '); print l($user->name,'user'); ?>

Which will display "Profile of John Smith". (This will only print the name of the user that is currently logged in)

When viewing another users profile, their name is printed as the page title. I haven't tried this myself, but you could just print the title again, with the additional text around it.

To do this...

Profile of <?php print $title; ?>

Should do the trick, as long as it is only printed on the /user page. You should add the code to your custom user-profile.tpl.php. This will print the name of the users page you are looking at, instead of the currently logged in user.


Is it possible to override configuration with yml files?

No, you can't override with YAML files.

But, all configuration is YAML. You can edit them manually with single export and then import again, you can do a mass export and then change the exported files (then you even get a diff of the changes that you can confirm).

You can also use drush cedit yourmodule.settings or drush cset yourmodule.settings some.key the_value (or the export/import commands for editing configuration.

None of those touch the YAML files in your module.. those are only the starting point and are then imported into the active config store of a site, after which they can be edit with the mentioned tools.


Since the dot syntax can mean a lot of different things, try to make it more clear by using the array syntax:

{% set the_variable = 'mytheme_myblock' %}

{% if page.header_first[the_variable] %}


Is there any method (function) in drupal which gets called after nodes being created.

You are looking for hook_node_insert()

This is from API page:

  Respond to creation of a new node.

  This hook is invoked from node_save() after the database query that
  will insert the node into the node table is scheduled for execution,
  after the type-specific hook_insert() is invoked, and after
  field_attach_insert() is called.

function MyModule_node_insert($node) {

  if($node->type == 'article') {
    //your code here
    custom_func();
  }
}

function custom_func() {
  //your code goes here
}


You can try using Profile Complete Percent module..

Project page says

  Profile Complete Percent (PCP) is an add-on to the core Profile module
  or the Profile2 module. It allows administrators to select profile
  fields as mandatory for a user to achieve a 100% profile completeness
  status.


Here are some resources if you opt to use Migrate Framework in 7.x to do this (which is how I would personally approach it).

https://www.drupal.org/project/migrate
https://www.drupal.org/project/migrate_source_json
https://www.drupal.org/project/migrate_plus

There are examples in Migrate/Migrate Plus on getting it setup. It looks like migrate_source_json was deprecated in favor of migrate_plus, but I included it for any historical references in it's issue queue.

There is probably a solution via Feeds as well but as stated, I am not experienced with Feeds.

If you can convert your format to CSV, there is also this one off module, Taxonomy CSV.


Is that possible with rules?

I'm a bit familiar with the (amazing!) Rules module. But to my knowledge the current answer to this question is No, Non, Neen, Nein.
More info

Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some (scary) quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

Start here if you wonder how to contribute.

One never realizes what has been done, only what remains to be done ...


Is there any way to force a custom block in the Custom Block Library to invalidate cache on edit update?

I came across this question in the related questions sidebar on my question that seems to be the same issue with out-of-the-box core blocks:
Block cache not clearing on save?

The accepted answer from @4k4 on that question seems to confirm the issue, but doesn't hook in to the block save to invalidate the cache like I was thinking, but mentions, as one possible workaround, adding this to the theme:

function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($variables, $variables['content'}['#block_content']);
  }
}

I don't know if this is the best answer, but it's simple and straightforward and seems to work at the moment, though it's a wonder that this would need to be done at all.  It's probably less of a hack than what I was thinking.


taxonomy_select_nodes() is returning an empty array because there aren't nodes using that taxonomy term, since that function doesn't return the nodes using any children of the taxonomy term passed as argument. This is also what a taxonomy term page does.

It could be the database table used from the function doesn't contain any data, simply for the fact the taxonomy_maintain_index_table persistent variable is not set to TRUE. If that is the case, then variable_get('taxonomy_maintain_index_table') returns FALSE (or an equivalent value). A persistent variable can be overridden from the settings.php file; that is the reason I am not suggesting to check the database.

As side notes:

The page--taxonomy.tpl.php template is used not only for taxonomy/term/<term id>, but for any path under taxonomy, for which there isn't a taxonomy term associated. I would rather use page--taxonomy--term--%.tpl.php that is surely associated with a taxonomy term.
If you are calling a function, and want to use the default value for some of its parameters, just leave them off. Instead of calling taxonomy_select_nodes() as taxonomy_select_nodes(arg(2), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')), call it as taxonomy_select_nodes(arg(2)). What you are doing is assigning TRUE to the $pager local variable, FALSE to $limit (another local variable), and an array to $order; those values are also passed as arguments to the function. So you are setting local variables to pass arguments to a function, and you are passing the default values for those arguments. Keep in mind that in PHP, a function arguments are only positional, differently from Ruby, for example.


hook_file_download() is invoked in two occasions:

When Drupal is verifying the users have access to the file they are trying to download

function file_download_access($uri) {
  return count(file_download_headers($uri)) > 0;
}

When Drupal is returning the headers for the file to download (and then the data for the file to download)

function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

In both the cases, the function invoking the hook is file_download_headers().

function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

Watching the Drupal code, I cannot assure the hook is always called twice in row, during the same page request; if it were so, you could take the necessary action when the hook is invoked for the second time.

I would rather change the callbacks for $directory_path . '/styles/%image_style' (where $directory_path contains the value returned from file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath()), system/files/styles/%image_style, system/files, and system/temporary to verify when a file is going to be downloaded, and log what happening.

This is not going to change in Drupal 8, as it doesn't split hook_file_download() in two hooks.


Other modules that provides chat room are

DrupalChat does not require an additional server component/server. This ease installation but can become a performance issue as PHP/Apahce are not a good fit to efficiently server chat-like application. If scalability is an issue, it supports a more robust solution based on Ape's Ajax Push Engine. The module description implies that the module allow other backend to be written.
Drupal Strophe provides XMPP chat integration in Drupal. It only supports the ejabberd server.
Chat Room doesnt require an additional server component/server. The author is working on a Node.JS integration module aimed to be used by the D7 version of Chat Room to solve the scalability issue.


Challenging Rules question ... also because there seem to be some things in it that don't match with Rules terminology or functionality. Read on for more details ...

Part 1: Refinements of your question

  Rules: Event user has logged in won't trigger rule

This is a pretty confusing title: Rules Event "User has logged in" should always be triggered ... when a user logged in. If that's not happening, then that seems ike a Rules-bug. Therefor I think a better title is "Why is my Rules Action not executed when using Rules Event 'User has logged in'?". If you agree, please edit your title like so.

  I can set any event to trigger a rule ... the rule is never triggered.

Rules Events are triggered by Rules, "you" cannot "set" them. Using custom code you may enhance Rules to trigger "custom" events to be triggered by Rules. Since this question is not about custom code, I assume you wanted to say "No matter which Rules Event I try to use ... the rule is never triggered".

  ... two rules triggered by the same action

Rules are NOT triggered by an action, they are trigger by a Rules Event.

Advice: Rules is all about Events, Conditions and Actions (ECA for short). You really need to think with those 3 crucial terms when using Rules ... And rephrase your question accordingly.

Part 2: Attempt to answer your question

What might explain what's happening

Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Rules debugging

You clearly have a combination of rules that need some debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Obviously, if you have more then 1 rule (like 3?), you may want to  make it like Bingo1, Bingo2, Bingo3. Depending on the order they are shown, you also know the order of execution. Stupid, but simple and efficient (I think).

For more suggestions about Rules debugging, refer to  "How can I display the value of a variable inside a condition?"

Use Conditional Rules

In your case there are 2 rules involved that are triggered by the same Rules Event (= after user acount is updated). But how do you know in which "order" (which Rule gets executed first)? There might be some logic in rules somewhere to find the answer to that question.

But instead of searching for that answer (or hope the order matches with what you'd hope), I simply use the Conditional Rules module in such cases. Not only does it allow me to merge multiple rules together in a single rule (= much easier to maintain, etc), but "I" am in full control about the actual Rules Conditions (within a Rules Action!), and I can set the order of them in the way "I" want/expect them to be. You can use Conditional (if/else) logic within the Rules Action, or you can also use Switch logic.

For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework.


You can add a filter on nid or title. If you want to, you can add a contextual filter (top right) and let the filter work with the url.


How to programatically access the value of a taxonomy term reference?

As the taxonomy term is a reference the value (or label) is not stored in the user entity, just the target_id. So you need to use:

$termreference = $account->get('field_termreference')->target_id;

This should be your code:

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

$account = User::load($account->id());
// Returns the correct value.
$textfield = $account->get('field_textfield')->value;
// You need to use the target_id to access to the value.
$termreference = $account->get('field_termreference')->target_id;

Now you need to search the label:

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termreference);
$name = $term->getName();

Your taxonomy label (name) will be in $name.


sharing authentication within two drupal distributions

This method comes with a list of caveats, but it's possible to simply share the users table across multiple installations via a table prefix array in settings.php.

  Example: Sharing Users
  This example shows how to share users. The
  users from a master site prefixed with 'master_' are shared to a slave
  site prefixed with 'slave1_'.

$db_prefix = array(
    "default" => "slave1_", // the prefix for tables that are not shared.
    "users" => "master_",
    "sessions" => "master_",
    "authmap" => "master_",
    "sequences" => "master_",
    "profile_fields" => "master_",
    "profile_values" => "master_",
);


Getting Error 324 (net::ERR_EMPTY_RESPONSE) when saving changes to content/views/modules

So, after a few days of trial and error, I managed to fix this problem. (Although I still am not really sure what caused it...)

The fix that I found was to disable modules until the problem disappeared, then to re-enable those modules. That was it. The problem has not resurfaced for the past few weeks.

Now, some details: I first attempted to fix the problem on my "sandbox" server, disabling modules one at a time with the hope that the problem would go away. It did, and I noted which module(s) were the last to be disabled. However, taking that information back to my main site did not help. Instead, I disabled modules in bulk (everything that could be disabled on a first pass; i.e. all modules not required by another module). After a few passes, the problem did indeed disappear. I'm not sure what caused it or why. If my searches while trying to fix it were any indication, nobody else knows either. Just a quirk of Drupal 6 I suppose.


Within $items of your iscrizione_rules_event_info(), you used iscrizione_evento. So in your iscrizione.module you should refer to that. Try this variation of it:

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

$items['conferma/%'] = array(
'title' => 'Conferma Iscrizione',
'page callback' => 'iscrizione_evento',
'page arguments' => array(1),
'access arguments' => array('access content'),
);

return $items;
}

function iscrizione_evento($arg) {
echo $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('iscrizione_evento', $arg);
}

Maybe it would also help if you'd slightly adapt the readability of your code, by not using iscrizione_evento for different things. How about, eg, these variations of it:

menu_iscrizione_evento.
rules_event_iscrizione.


Node Post Date equals to selected date only not time?

Install the date module and enable the "Date Views" module, which is a sub-module of the date module.
To your view add the filter "Date: Date (node)".
For the "Date selection form element" option set it to whatever you like.
For the "Filter granularity" option set it to "Day".
Set the "Starting year" option to whatever is relevant.
For the "Date field(s)" option select "Content: Post date"
For the "Method" option, generally leave it set to "OR"
Click the apply button, then continue to configure as you would normally.


Filter criteria are not working with featured content blocks

First of all, in this case you don't need to add your filters to a new filter group, because views will use AND by default.

I don't see a filter for your taxonomy term. You should add one (see in the attached images).

For the content types you need just one filter, you can select which content types to filter on inside the filter.


How can I mass delete multilingual strings when I know only the page that added them?

drush sql-query "delete from locales_source where location = '/ja/mypage'"

Or delete by strings, for examples if all strings you want to delete contains "hoof" :

drush sql-query "delete from locales_source where source like '%hoof%'"


Performance - custom php block or views to use in panels

Personally, I don't worry about performance of little things like this.

You also don't need to resort to Views to get this information.

If you are using the Node template page from Page Manager, then you can

edit the page
select the variant
edit the content
click the gear on the panel you want to Add Content
click the Node tab
click Node Title

This will then be a normal panel pane that you can place as you need it.  This is one trick to get node content above the page title on complicated layouts.


CCK migration From Drupal 6 to Drupal 7: Which tables can I delete?

As far as I can see, the tables that are safe to be removed (if they are not removed from an update function) are the ones matching the content_* pattern, which are not used anymore in Drupal 7.


if you look at /core/lib/Drupal/Core/Render/Element/Radios.php  you'll see it's not a render element, but a form element.

You can't use it without putting it in a form. If you search the code base for extends FormBase, you'll see many examples of forms that you can start from in building your own form, many of them quite simple.

For example:
/core/modules/system/tests/modules/form_test/src/Form/FormTestProgrammaticForm.php


CKEditor custom plugin to add richcombo select list

You should really be extending CKEditorPluginBase and implement getButtons method. This is likely why you don't see it in the administrative interface, but in a vanilla CKEditor test, you do.

https://api.drupal.org/api/drupal/core!modules!ckeditor!src!CKEditorPluginButtonsInterface.php/function/CKEditorPluginButtonsInterface%3A%3AgetButtons/8.2.x


Can't get the module quick edit to work (have some error screenshots)

On the quick edit drupal page it says,

  Works with any Drupal 7 site (requires the Entity API, CTools and
  Libraries API (>=2) modules, plus the Underscore.js (>=1.5) and
  Backbone.js (>=1.0) JavaScript libraries). If in-place WYSIWYG editing
  is desired, you must also use the CKEditor module.

You need to download and install the libraries module

Then you need to create a libraries folder in sites/all folder. So it looks like this sites/all/libraries

Then you need to download the Backbone.js and Underscore.js and put them inside the sites/all/libraries folder.

I also see you have some other errors, which is not Quick Edit related. Must be from some other module you installed.

What the errors are saying is that you need to create a custom CK editor http://ckeditor.com/builder and make sure you include the Shared Space and Source Dialog plugins. So under avalable plugins (right column), scroll and find these plugins and click on the left arrow to include them on your CK editor build. Then scroll all the way down, checkmark the I agree to terms box and click on Download. Then you need unzip and put the ckeditor folder in your sites/all/modules/ckeditor/ folder. So it will look like this sites/all/modules/ckeditor/ckeditor


Try this:

$node = node_load($context['data']['node']->nid);
token_replace("[node:story-page-number]", array('node' => $node));

If $context['data']['node'] is already a node, then you may skip the node_load() call, and simply assign $node = $context['data']['node'];

Edit: Sorry, I didn't try your example in code.  You need to include the token type in your token names. In mymodule_tokens(), check to be sure that $type is 'node', and then look up $node from $data['node']. Note that you are using the Drupal 6 hook_token_values(); you should use the D7 hook_tokens().  Use the implementation of node_tokens() as a guide.

References

hook_tokens()
token_replace()


How to add flat rate in Drupal Commerce?

Check "Shipping methods" tab (or go to .../admin/commerce/config/shipping/methods). Flat rate should be listed here.

If not double check that flat rate module is enabled?

-edit-

When viewing page Store > Configuration > Shipping there is few tabs like "Shipping services" and "Shipping methods" but below them is another set of tabs, which should include "Flat rate" and should be chosen before Add a flat rate service link becomes visible on that page.


I just had a similar issue (June 2014) with Views UI. The ajax interactions on the 'style settings' simply stopped working so click on 'customize field HTML' and nothing happened. Hence finding this post/tip. I went to the Modules/JQuery configurations screen (http://website.co.uk/#overlay=admin/config/development/jquery_update) and instructed the Admin Pages to use JQuery v 1.5 (instead of the current 1.10). All View UI interactions then worked fine again.

Adding this extra note for anyone that might find that handy. Thanks to Vintorg and other repliers for the solution.

Q.


I think you should be able to do this fairly easily, without even involving views or contexts!

Here's how you can do it:

Just like you said, you can create a new Entity Reference field that will point to the relevant webform.  I'd make this field an Autocomplete (Tags style) field:

When you're setting up your field, make sure to select that it should only pull from your Webform content type:

When you've created the new field, make sure you hit the 'Manage Display' settings on the content type that includes this webform reference.  Here's where the real magic is going to happen: you can have this new referenced entity (which is your webform) be displayed not as a link, but as a rendered entity.  Which means you can just automatically display the webform under or above your node, or whereever you choose to output it.  In my case, I made it the very last field (so it displays under my node), and here are the exact settings:

Now test:
If you go to create a new content type, you should be able to just start typing in the title of the webform you want to attach (such as "Contact Us"), and all the matching webforms will pop up - just choose the right one, save, and it should appear under your node.

Voila!

Let us know if it works for you.


How to implement a cron job for every minute and every 5 minutes?

hook_cron()

  The engine will then call the hook whenever a cron run happens, as
  defined by the administrator.

In other words, hook_cron gets executed after a cron run happens. So if you have cron set to run once a day, then your hook_cron script only gets executed once per day. So you need to set cron to run every 5 minutes or less.

A better alternative, I suggest you use a module like Ultimate   Cron which allows you to schedule different cron run times for different cron tasks. This way, cron doesn't run every single task every 5 minutes and instead it runs your specific task only.


Search for duplicate or similar node titles when creating content?

There is module Uniqueness , it does exactly what you want. It allows you to enable for any content type, and you can configure checking on node add or edit or both.

  Uniqueness module provides a way to avoid duplicate content on your
  site by informing a user about similar or related content during
  creation of a new post. A UI widget is added to the node/add form that
  does asynchronous searches on inputted fields (like the node title or
  vocabularies) and returns the titles of similar content.


How to make a "term reference" > "taxonomy vocab" display alphabetically in a content type?

Change the order (weight) of the terms within the vocabulary to be alphabetical.

I've just tried this and it works in D7.23 using a 'Term Reference' field. To test this I ordered terms into non-alphabetical, saved the vocabulary, then created a node. Terms were in the order I'd specified. I then 'reset to alphabetical', saved the vocabulary and created a node. Terms were now in alphabetical order.

I found your question title confusing as it talks about terms reference but then the question itself mentions node reference. Please edit the question and clarify.


Is hook_translated_menu_link_alter() thought to be used only on translated menu links?

Take a look at Devel, it uses hook_translated_menu_link() along with hook_menu_link_alter() to add a destination query to the end of a few of the links.

http://drupalcode.org/project/devel.git/blob/0ca6cc9bd5e2cf650717b73e8938b88726d0ebbd:/devel.module

Line #331 - devel_menu_link_alter()
Line #342 - devel_translated_menu_link_alter()


how to check in ajax form callback if form for failed validation

function popover_ajax_callback($form, &$form_state) {
  $errors = form_get_errors();
  if( $errors ) {
    // error detected, do something
  } else {
    // everything is ok
  }
}

but your return value is not ok. You need to return an renderable array. You may want to try someting like this:

return array('#markup' => '
' . $form_state['values']['first']['field_firstname'] . '
');