Is it possible to display more than one node in a page?

From our comment conversation...

Try this in your pageshow handler:

function tung_intro_pageshow() {

  // Load the fist node and inject it.
  var nid = 13;
  node_load(nid, {
    success:function(node) {

      var title = node.title;
      var content = node.content;
      $('#' + 'my_node_' + nid).html(content).trigger('create');

      // Load the second node node and inject it.
      nid = 3;
      node_load(nid, {
          success:function(node){

            var title = node.title;
            var content = node.content;
            $('#' + 'my_node_' + nid).html(content).trigger('create');

          }
      });

    }
  });
}

Not the most elegant solution, but a workaround nonetheless. A more ideal solution is dependent on the outcome of this: https://www.drupal.org/node/2601764


How to dynamically change the text of the Global: result summary based on exposed filter on Views?

I took the liberty of writing a little module for accomplishing what you asked for, I found it an interesting problem.
You can access it here:

https://www.drupal.org/sandbox/stefanos.petrakis/2666048

Hope this helps


Ajax request return field without name attribute

The attribute name is missing because you have replaced the select element in ajax callback. You just need to update the #options

function insttance_ajax_fill_content($form, $form_state)
{
    $i = $form['count_field']['#value'];
    $content = getAllContentByType($form_state['values']['export_what']);

    $form['export_data']['#options'] = $content;

    return $form['export_data'];
}


How to know current active installation profile like standard/minimal etc. on existing drupal site?

If you go to /admin/reports/status, under Drupal if you see something written after Drupal version, that's your installation profile. If there is nothing, that means it is Standard profile.


How to trigger an email for a buyer or seller who has not performed any activity for 30 days or more?

Finally i got the answer here:
https://www.drupal.org/project/inactive_user

The inactive_user module provides Drupal administrators with a way to automatically manage inactive user accounts. This module has two goals: to help keep users coming back to your site by reminding them when they've been away for a configurable period of time, and to cleanup unused accounts.

And another possible solution is:
Using rules for more advanced functionality would involve something similar to the following

Create a new Rule Set that passes the User and (possibly) a Date argument

Add a Check a truth value condition that verifies something like [user:user-last-login-raw] + 2592000 < [user:date-in-tz] (2592000 is 30 days in seconds)

Add a Send a mail to a user action

Save that rule set and then do the following:

Create a new triggered rule for User has logged out event
Add a Schedule "your rule set" action and pass +30 days as the Scheduled evaluation date


Listing all entries of a specific content type within a panel

If you can at all avoid it, the direction you've started in is not the solution you want. Panels is not for handling content, but context.

What you want instead is a Views content pane. Explaining Views in detail is beyond the scope of this post, but here's the general outline.

Install Views and Ctools.
Enable "Views UI" and "Views content panes".
Create a new View
Add a filter on node type so you get only the right content type.
Add title as field. Then repeat the View creation above but add the rest of the fields.
Go into Panels and add both Views in their respective regions.

Much much more info about Views in Taming the Beast: Learn Views with NodeOne.


I believe I've found an answer to this problem.

Using the Feeds Tamper module, I can add use the Entity Fields Query Finder plugin to lookup against any other field belonging to a particular content type.

In my case I'm saving the lookup key I need in a field, and then matching against that field & content type.


I'd look for cheap shared hosting. Make sure you get PHP and MySql and some kind of temporary URL.


How to modify a form to have some field surrounded by 'Details'?

I did it this way (thanks to @4K4 to put me on the right direction):

$form['fileDetails'] = array(
  '#type' => 'details',
  '#title' => $this->t('File'),
  '#weight' => 8,
);
$form['file']['#group'] = 'fileDetails';

$form['link']['widget']['0']['#type'] = 'details';

And I get this:


Copy values from taxonomy term field to new text field in content-type

According to me you can achieve it by doing something like:

Creating a PHP script which: Get all terms related to a node and then create a comma separated value for them and then store this as value of your new field in database.

You need to iterate over all nodes and the run following code to get all terms

$result = db_query(
SELECT ttd.tid, ttd.vid, ttd.name, ttd.description, ttd.weight
FROM taxonomy_term_data AS ttd
INNER JOIN taxonomy_index ti ON ti.tid = ttd.tid
WHERE ti.nid= :nid
ORDER BY ttd.weight, ttd.name',array(':nid' =>$node->nid));

Or you can use Drupal code as well for doing the same

$node = node_load(arg(1));
if ($node != NULL) {
$field = $node->field_my_vocabulary;
$lang= $node->language;
$terms_all = $field[$lang];
foreach ($terms_all as $term) {
$terms[] = $term['tid'];
}
return implode('+', $terms);
}

Now assign this vale to you new field.

The above code is not tested by me, but I hope it can do what you want with no/little modification :)


Cannot run drush rsync - PHP Fatal error in sitealias.inc

Found an error in my alias files. I had a space between SQL username and password.

$aliases['devyau'] = array(
  'uri'=> 'dev.[sitename]',
  'root'=> '/var/www/vhosts/dev.[sitename]/',
  'db-url' => 'mysql://[username]: [password]/devDBname',
);


Assuming the custom form sits in its own page. You can rewrite the output of the field, using replacement patterns, in the view to pass the required information as part of the url.

Then using hook_menu, define parameters to pass to the form

function hello_world_menu() {
  $items=array();
  $items['hello_world/%/%'] = array (
    'title' => 'My Custom Form',
    'page callback' => 'hello_world_form_function',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}


$user not updating and "Validation error, please try again." on form in block

Just to answer my own question. In this answer to another question, Berdir mentions that Drupal 6 will not update your block information. The example given to do it in code is here but I just updated the cache field to -1 (BLOCK_NO_CACHE) in the blocks table.


setting content to display on a basic page

set up a block view with all your classifieds and then  via admin/structure/blocks find your classified block and configure it to show on your basic page.


how to create user view with last login zero or never logged in

Yes, after long search i got a suitable answer
If i put in operator is equal to value 1970. it gives me result
basically 1970 consider as a zero value.


You don't set the path when creating a content type. Once you create a "basic page" content type (or use the one that comes with the "standard Install" of Drupal core), you can then create a basic page by going to node/add. Then in the vertical tabs at the bottom of the node creation page, you will find a tab called, "URL path settings". In there you can manually specify a path. If you wish to avoid having to manually adding a path for every node, use the Pathauto module.


Link to a custom entity settings page does not appear at /admin/structure

Please revise your file:

  yourmodule.links.menu.yml.

and verify if exists the parameter

  parent

A complete example

  yourmodule.admin_content:
  title: Content
  description: 'Find and manage content.'
  route_name: system.admin_content
  parent: system.admin_structure
  weight: -10


Storing data for every country for an interactive chart

I did something similar sometime ago.
My svg had a path per country with each path being identified by a unique id (namely the country name camelcased). These were stored directly in the template.
I created a taxonomy with all the country ids, and a content type for the user-contributed country data, with a reference to the country-ids taxonomy.
After that I used EntityFieldQuery to get the list of country-ids with published data, so as to display them highlighted in the map.
Then on click of a country I'd retreive the country data via an AJAX request and display it besides the map using jquery.

Beyond my original implementation you could probably load all data via EntityFieldQuery and then just handle it via javascript without further requests.

Does that make sense to you ?


Can't save settings after copying site to new server

I had to enable Mod Rewrite.
sudo a2enmod rewrite
If you're having this issue, also check that your .htaccess files copied over to the new server (I've wasted countless hours chasing this).


How to disable Ubercart order mail notification?

You can disable the Rule (Configuration -> Workflow -> Rule):
E-mail admin checkout notification.

About the second question, you can customize the Rule:
E-mail an order update notification
to email the store owner when the order changes status AND when the status is equal to "Payment received"

Hope this helps


What message is throwing InvalidArgumentException(s) in my contact forms?

You're most likely passing an object or an array to a translation function call. The t() function expects a string as it's first parameter (see the function spec on drupal.org). Search for places where you call the t() function.

More information on how the translation functions are used in D8 can be found on the translation api page on drupal.org. This will give you an idea of how and where you could have translations so you can check those places in your code.


How do I limit validation errors to submission buttons?

I did exactly the same but we were wrong in the usage of #limit_validation_errors.

The reason why this is failing is that we're not using properly #limit_validation_errors. This issue has nothing to do with Workflow.

During the form validation, if this property is set (validation errors are limited), Drupal core will remove any non validated form values from the form state, so only values that passed validation will be left for submit callbacks.

For Drupal 8:
http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Form/FormValidator.php#n147

For Drupal 7:
http://cgit.drupalcode.org/drupal/tree/includes/form.inc?h=7.x#n1193

My solution was to add a custom validation that will be executed at end of all validations, and in there remove all form-related errors:

/**
 * Removes all validation errors that could happen when saving a draft
 *
 * @param $form
 * @param $form_state
 */
function my_custom_draft_validation($form, &$form_state) {
  $errors = form_get_errors();

  if (!empty($errors)) {
    $messages = drupal_get_messages('error', TRUE);

    // Remove error messages originated during the form validation
    foreach ($messages['error'] as $error) {
      if (!in_array($error, $errors)) {
        drupal_set_message('error', $error);
      }
    }

    // Remove all form errors
    form_clear_error();
  }
}


If the subsites are spread across multiple sub/domains, you can use domain to display a different set of nodes per-domain.


relative path in blocks - multilingual - does not work

There are 2 components in the multilingual Drupal WRT which language to show: Content and Interface. /page-in-french refers to Content, /fr/ refers to the Interface language.

Without some additional "guidance" Drupal will link to exactly the link you tell it to. In D7 translations of nodes are new nodes (with different IDs) so it makes sense there is nothing to show for /page-in-french since there are no nodes in English with that name.

Use multilink to redirect to content in language matching the interface language

If you want to make the Drupal be aware of language context in such a way to redirect to a relevant content translation to match the interface language use Multi-Language Link and Redirect (MultiLink).

It works by enabling it on the text Input filter you're using.

It comes with a special syntax to include links to nodes [NID:text] but you don't have to use it! The redirect will work even for HTML links with classes and IDs. Which means you don't have to edit the links you already have.

If you want to control which text to display in the link
you can do this in your English block:

Custom English text

and this in your Spanish block:

Custom Spanish text

The href attribute stays the same, only the link text changes.

If you want to display node title as the link text (the title of the relevant language translation) you can rely on Multilink syntax:

[34: $]

where the 34 is the NID of the English node $ represent relevant node title. This will display node 34 on the English side with node 34 title, and on the Spanish side it will display whichever node is the Spanish translation of node 34, and the link text will be the title of the translated node.

Check your Languages Detection and selection settings

Make sure you have URL set as the first enabled option. This will make sure the redirect respect the Interface language you're using.

If you give advantage to the User option, and a user has Spanish set in their profile, they would never be allowed to see English pages, as long as they're logged in they'd always be redirected to Spanish.


How to add a image style to an image in a template file?

The docs page has it pretty much covered but here's an example if you're struggling:

$style_vars = array(
  'style_name' => $style_name,
  'path' => $image_path,
  'alt' => $alt_text
);

$image = theme('image_style', $style_vars);

$link = l($image, $url, array('html' => TRUE));


db_query with where clause not returning anything

Try:

$taxonomy_term = taxonomy_term_load(40848); // the 40848 is the term id
$field_items = field_get_items('taxonomy', $taxonomy_term, 'field_data_field_country_feed');


How do you go about using contexts and a menu page callback?

Take a cue from metatag_context_entity_prepare_view() in that patch.  You need to stuff your desired term entities into the metatag_context_entities static variable in your page callback like so:

drupal_static('metatag_context_entities', array('taxonomy_term', $terms));


Updating taxonomy vocabularies with Rules?

Try the rules action "Set data value."  If the user includes a taxonomy reference field, you should be able to add or remove it this way.

Alternatives:
I'm not sure what you intend to use the vocabulary of usernames for, but it is straightforward to use the views module to generate a list of users by role.

Alternately, I have been using the flag module-- the latest Drupal 7 beta features rules integration-- to automatically flag users upon adding or removing roles.  You may be able to use flags instead of a vocabulary.


How to organize this: traders have fruits and recipes too

I would look into using the references module, you can reference one content type from another, for example on a ingredient page such as white wine, you could reference Spaghetti Aglio as a "you can make this from this ingredient".

Then on a traders content type you can refer to the ingredients etc


Showing all Sibling nodes that share the same Taxonomy term in Drupal 7

Try to add validator when filter value is AVAILABLE or Default is provided:


This is displayed in html.tpl.php in the variable $head. $head is added to the variables in template_process_html by using drupal_get_html_head(). In that function, you can see that hook_html_head_alter() is called.

There can you remove these.

However, note that these links can be important for SEO, to avoid that a search engine thinks that you have duplicate content on your site, if for example a node is available through node/nid and the alias.


Unsubscribe users from Simplenews from a specific Newsletter category

I think it should work. Use hook_simplenews_unsubcribe_user which will

/**
 * Invoked if a user is unsubscribed from a newsletter.
 *
 * @param $subscriber
 *   The subscriber object including all subscriptions of this user.
 *
 * @param $subscription
 *   The subscription object for this specific unsubscribe action.
 *
 * @ingroup subscriber
 */
function hook_simplenews_unsubscribe_user($subscriber, $subscription) {

}

Add this in your custom module. I think $mail and $tid will be available in $subscrption variable.

function module_simplenews_unsubscribe_user($subscriber, $subscription) {
  simplenews_unsubscribe_user($mail, $tid, FALSE, 'website');//$tid -s your genral category tid.
}


View of nodes and all their taxonomy terms

It would help if you could include a screenshot of your view. But based on your post (I am assuming each term only has one icon), it seems like you may need to aggregate your view. If this is a Drupal 7 site, I also recommend using the module Views Merge Rows, which allows you to choose a separator for when there are multiples after grouping.


How to increase the value of the field nid in the node table in database?

Forcing the import to use the ID of the other system will break the sequential nature of the drupal nid.  You should add a textfield on the receiving site to hold the old site id and let drupal assign new ones.


How do I show the "Your Cart" link in my Rules message

Just add a link to

your cart

It will show the user's shopping cart.


How to Change "USER has no blog entries" Text

You have to isolate first exactly where this text is coming from. From your description, it sounds like you're using the core blog module which has this line here:

https://api.drupal.org/api/drupal/modules%21blog%21blog.pages.inc/function/blog_page_user/7

else {
  drupal_set_message(t('!author has not created any blog entries.', array('!author' => theme('username', array('account' => $account)))));
}

So the correct string you want to use (and what your string override in settings.php will be looking for) is

!author has not created any blog entries.

Using the string overrides module or your settings file, its easy then to change this text to whatever your like


How can I create this sort of path structure?

Okay, I've just had a look at my old test site and I can see that I'm using the following syntax:

[field_locations-term-raw]/[term-raw]/[title-raw]

This displays like so:

/grange-over-sands/holiday-apartments/test-property

The location comes before the page type (accommodation) here, which I'm aware of, but now the path is displayed perfectly! I've previously deactivated the Domain Access module, so I can only assume that it was DA that was causing my paths not to show correctly.

This leaves me with a new question,though, which I'll start separately.


Cache SOAP search results from external web service

I suppose you could hack together a module that queries the external site and then populates an Apache Solr search database, then you could simply use the Apache Solr Search module on read-only to look at the data on your site...


Why are no tests shown on testing overview?

Instead of using

files[] = tests/*.test

in mymodule/mymodule.info
it should be

files[] = tests/mymodule.test


Drupal doesn't detect my MySQL installation

You need to have the PDO driver for MySQL installed for Drupal 7. This is indeed different from Drupal 6. Instructions are at http://drupal.org/requirements/pdo. I hope those instructions are sufficient for you.


Check the "name" attribute of your search return checkbox by inspecting it within your browser. You may find the name="" isn't actually name="search_return". It may instead be name="search[search_return]" or something similar. So you need to update your states code to whatever the name is


Local simpletest drupalGet() always gives "returned 0 (0 bytes)"

This error means that your test cannot reach your website.

I had a similar issue using something based on docker for drupal. For me the solution or hack the hosts file on the php container and change to point the domain you want to test to to the ip of the proxy server, in my case traeffik.

So in my host file I had something like this:

172.18.0.5      domain.internal

once that is done you can use curl to test the connection:

curl -v domain.internal

In my case I had an issue with a self signed certificate.

Rebuilt URL to: https://domain.internal/
Trying 172.18.0.5...
TCP_NODELAY set
Connected to domain.internal (172.18.0.5) port 443 (#0)
ALPN, offering http/1.1
successfully set certificate verify locations:
CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: none
TLSv1.2 (OUT), TLS handshake, Client hello (1):
TLSv1.2 (IN), TLS handshake, Server hello (2):
TLSv1.2 (IN), TLS handshake, Certificate (11):
TLSv1.2 (OUT), TLS alert, Server hello (2):
SSL certificate problem: self signed certificate
Closing connection 0
curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

However this should allow you to run your simpletest(s) in your browser.

Ideally there should be a way to configure this in your docker-compose file but I am not sure how?


How to Add more option for type radios use Ajax in Drupal 8

Here is the complete code example:

<?php
/**
 * @file
 * File: src/Form/MyExampleForm.php
 * Contains \Drupal\mymodule\Form\MyExampleForm.
 */
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyExampleForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'example_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['wrapper'] = array(
        '#type' => 'container',
        '#attributes' => array('id' => 'data-wrapper'),
        );

    /* // or:
    $form['wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Example title'),
      '#tree' => FALSE,
      '#prefix' => "
",
      '#suffix' => '
',
    );
    */

    /* // or:
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    */

    $form['wrapper']['data_media'] = array(
        '#type' => 'radios',
        //'#title' => 'Title',
        '#options' => array('aaa','bbb','cccc'),
        );
    $form['wrapper']['more_data'] = array(
        '#type' => 'button',
        '#required' => TRUE,
        '#value' => 'Show more',
        // @see: https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.3.x
        '#ajax' => array(
          // The callback to invoke to handle the server side of the Ajax event.
          'callback' => [$form_state->getBuildInfo()['callback_object'], 'ajaxLoadMore'],
          // or: //'callback' => [$this, 'ajaxLoadMore'],
          // or: //'callback' => '::ajaxLoadMore',
          // @see: http://api.jquery.com/category/manipulation/
          //'method' => 'replace', // May be: 'replaceWith' (default), 'append', 'prepend', 'before', 'after', or 'html'.
          // The HTML 'id' attribute of the area where the content returned by the callback should be placed.
          'wrapper' => 'data-wrapper',
          ),
        );
    $form['wrapper']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Confirm'),
        );

    return $form;
  }

  /**
   * Ajax handler for loading more radio options.
   */
  public function ajaxLoadMore(array &$form, FormStateInterface $form_state){
    // Add more options for radios.
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#value'] == 'Show more') {
      $form['wrapper']['data_media']['#options'] += array_merge($form['wrapper']['data_media']['#options'], ['bbbb']);
    }
    return $form['wrapper'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#type'] === 'submit') {
      if (is_null($values['data_media'])) {
        $form_state->setErrorByName('data_media', t('Please select the option!'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your form has been submitted.'));
  }

}


How to assign "Edit" permission per Webform?

It actually can be done by "Enable per content node access control settings", which is under "Structure > Content types > Edit Webform > Access Control".


Drupal 7 Module to Set image src to a URL

I think you're looking for Remote File Source.

  Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.


How allow moderators to give a rebuke to user

You can use Flag module for that. You can set flag for users or posts created by users or something else as per your requirement.

Use rules to set rule on flagging & their counter value. There is very nice tutorial series on flag here by Johan Falk. You can see his rules tutorials to have better understanding about setting rules based on flagging.


How to tell what module is running from a function call?

You could get the calling function from calling debug_backtrace(). Another way would be to pass it in:

_rest_api_do_request(__FUNCTION__);

However, either seems like a bad pattern. It's fine for debugging, but a function shouldn't require knowledge of what it is calling it. That's an unnecessary dependency.


Create shipping charge based in produc weight' with Drupal commerce module?

Easy, create two rules, one where the condition is that the total weight is more than 1 pound and one where the condition is less than or equal 1 pound.

You can setup the rest of the rules to be the same, with only the price (CPP) being different.


Go to /admin/structure/menu/manage/main-menu/edit and click "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized. "


Runing PHP Code inside region.tpl.php file

I believe you cannot render main menu in this way within a region, the variable is not there. You could try with:

$main_menu_tree = menu_tree(variable_get("menu_main_links_source", "main-menu"));
print drupal_render($main_menu_tree);

Even better, I would recommend that you simply render the output of the particular region properly and add the menu dynamically from Blocks administration.

To render a region in your theme shortly, you need to define a proper region in your theme's .info file (eg. my_region) and render it using print render($page['my_region']); in the .tpl.php file. I hope this guide will help you: https://drupal.org/documentation/theme


I went through the same case, reinstall the search and entity modules. And try to install search_api using Database Search Default module and after installation, uninstall the database search Default module. Boost taxonomy name to 8 or 13. Then it should work.


How to alter the languages available in a form

OK: found the answer for anyone else. In D7, the i18n implements a callback that happens AFTER the form is rendered, so you need to add a callback as well. So:

function example_form_node_form_alter(&$form, $form_state) {
   $form['#after_build'][] = '_example_form_node_form_alter';
}

function _example_form_node_form_alter($form, &$form_state) {
  //example_language_list returns an array in the form of ("en"=>"English") etc
  $form['language']['#options'] = example_language_list($form['#node'], TRUE);
  if (!i18n_node_language_options($node, 'required')) {
    $form['language']['#options'] = array(LANGUAGE_NONE => t('Language neutral')) + $form['language']['#options'];
  }
 return $form;
}


Found a solution here - https://www.drupal.org/forum/support/module-development-and-code-questions/2019-08-03/menu-item-children-not-rendered-in
I needed to change "Number of levels to display" under the Navigation block to Unlimited


How to make a comment only visible to the commenter before approval?

Things you need to know:

hook_node_view
hook_query_TAG_alter
db_or

Step I read code.
Step 1: find function comment_node_view this function define element comment in array render of node.
Step 2 find line 711
$node->content['comments'] = comment_node_page_additions($node);//define comment

Step 3 go to function comment_node_page_additions see code.
if (($node->comment_count && user_access('access comments')) || user_access('administer comments')) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    $comments_per_page = variable_get('comment_default_per_page_' . $node->type, 50);
    if ($cids = comment_get_thread($node, $mode, $comments_per_page)) {
      $comments = comment_load_multiple($cids);
      comment_prepare_thread($comments);
      $build = comment_view_multiple($comments, $node);
      $build['pager']['#theme'] = 'pager';
      $additions['comments'] = $build;
    }
  }

Step 4 If user is anonymous $node->comment_count = 0. so condition is false. Don't add comment. (Problem 1)
Step 5 function comment_get_thread
if (!user_access('administer comments')) {
    $query->condition('c.status', COMMENT_PUBLISHED);
    $count_query->condition('c.status', COMMENT_PUBLISHED);
  }

this function return array store cids (all comment of node) with condition status is published (don't get comment of user is anonymous) Problem 2.
Problem solving
Problem 1: Use hook_node_view to set $node->commentcount != 0 (require this function run before function comment_node_view. You can set weigh of module (sure test with value is -1) or name of module start with a or b (not sure)).
/**
 * Implements hook_node_view().
 */
function ModuleName_node_view($node, $view_mode, $langcode) {
  global $user;
  if ($user->uid == 0 && $node->comment_count == 0) {
    $node->comment_count = 1;
  }
}

Problem 2
You need alter this query to get comment published or current user is author of comment. To do it i need hook_query_TAG_alter.
You can write a custom module with code:
/**
 * Implements hook_query_TAG_alter().
 */
function ModuleName_query_comment_filter_alter(QueryAlterableInterface $query){
  global $user;
  if (!user_access('administer comments')) {
    $conditions = &$query->conditions();
    foreach ($conditions as $key => $condition) {
      if (is_array($condition) && is_string($condition['field'])
        && $condition['field'] == 'c.status'
        && $condition['value'] == COMMENT_PUBLISHED) {
        unset($conditions[$key]); // unset condition comment is public
        $or = db_or();
        $or->condition('c.status', COMMENT_PUBLISHED);
        //$or->condition('c.uid', $user->uid); this case for require use login to comment
        $or->condition('c.hostname', $user->hostname); // Ip of user
        $query->condition($or);
        return;
      }
    }
  }
}

NOTE: All the users have the same IP are seeing comment.


You can't do relative paths, all paths must either be from the Drupal root or based on the namespaced path to your 'templates' directory: https://www.drupal.org/node/2143557.

I would avoid "from the Drupal root" and use namespaces, at least until https://www.drupal.org/node/2291449 is resolved.

{% include '@mytheme/parts/footer.html.twig' %}

  Edit: If you want to pass additional arguments for loop or for
  checking some vars to your included twig template you should write
  in this way:

{% include '@mytheme/includes/form-block.html.twig' with {dog: true} %}

Edit: Now that https://www.drupal.org/node/2291449 has been committed you can also do:

{% include 'footer.html.twig' %}

See https://www.drupal.org/node/2369981 for why you saw the file name as a string instead of a helpful exception.


You can install Devel module and enable "Display $page array" on Devel settings page (/devel/settings).

Or you can implement hook_page_build() to get $page array:

YOURMODULE_page_build(&$page) {
  print_r($page);
}


How do I show all "songs" that reference an "album" (for example)?

Thanks for this comment pointing me to the EVA module.  Here are the exact steps I had to take in Drupal 8, which is slightly different than Drupal 7.

Steps for Drupal 8:

Make sure your reference field is already set up (e.g., the Song entity has a field referencing an Album)
Install and activate the EVA module
Add a new view (Manage > Structure > Views > Add View)
Type in the view name, and in View Settings, set it to show Content of type Recording (i.e., the "child" entity).  No need to "Create a page" or "Create a block".
Under the Displays heading will be a label called Master.  Click the Add button just to the right of that.
Select "EVA", not "Entity Reference" (this is a difference from Drupal 7)
Under Displays > Format, I like to change "Unformatted list" to "Table".
Under Display > Entity Content Settings, change "Entity type" from "None" to "Content".
Change "Bundles" from "All" to "Album" (i.e., the "parent" entity)
Under Advanced, add a "Contextual filter".
Search for the field which links Recording to Album (i.e., the field in the child entity which references the parent), and select it, and click "Add and configure contextual filters".
Under "When the filter value is not available", select "Provide default value" and choose "Content ID from URL".
click "Apply".
If you know the ID of an album (parent entity), you can enter it in the parameter in the "Preview" section to make sure it is working as expected (you will need to pre-populate entities to test this).
Click "Save" under the "Display" section for the view.
A message should show up: "The view ___ has been saved."
Clear all caches (Manage > Configuration > Development > Performance > Clear Cache > Clear All Caches).
Navigate to a sample parent entity, and the child entities should show up on that page.


How do I add onclick Google Analtyics custom event "add to cart" to add to cart button in Drupal Commerce?

Sorry for updating, but you can easily add code before sending form!

It's in sites/all/modules/uc_ajax_cart/js/uc_ajax_cart.js:70

Just put your request after

beforeSubmit : function () {


How to disable the first option of select form element

Drupal by default doesn't allow for this, so you'll need to do two things:

Override theme_select()
Create your own callback the create the options
Change the way you define your select options in your form definition

Overriding theme_select():

function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . custom_form_select_options($element) . '</select>';
}

Create your own callback the create the options:

function custom_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice) && !isset($choice['data'])) {
      $options .= '<optgroup label="' . check_plain($key) . '">';
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option value="' . check_plain($key) . '"' . $selected;
      if(is_array($choice) && isset($choice['disabled']) && $choice['disabled'])
      {
          $options .= ' disabled';
      }
      $choice = is_array($choice) && isset($choice['data']) ? $choice['data'] : $choice;
      $options .= '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

Change the way you define your select options in your form definition. Turn the option into an array with two keys:

data: The display value of the element
disabled: A boolean indicating whether to disable the element

Example:

$form['select'] = array(
  '#title' => t('Pick something'),
  '#type' => 'select',
  '#options' => array(
    'yes' => array('data' => t('Yes'), 'disabled' => TRUE),
    'no' => t('No'),
  ),
);


Changing from a Profile to Standard profile after the installation

I figure out how to do it. You will need to use the Profile Switcher module in order to achieve moving from one profile to another one.


Content type Text field as Geolocation source field in View

Map formatters usually only take geolocation data in order to display them (latitude and longitude for example). There is a way to "convert" a textual address into geolocation data with the help of a Geocoding service.

So you do have to create a geolocation field. You can set it to automatically take the address and convert it to points on a map, and you can hide this field from users. It's a problem though if the address someone enters isn't correct in some way.

With the geodata ready in that field you can set your views map to use that field as the source for geo points on a map.

Here's a comparison of modules that can help you with this: Comparison of Mapping modules.

It seems your best bet is Geofield Well Known Text and Geocoder.


Drupal-to-Drupal data migration Taxonomy issues

Well, this is a couple years' old now, but thank you doodirock for tickling my memory on this. You need to configure that field's source_type value to 'tid'. I'm doing so in code, but I believe that you can set this in the UI. The code you need is this:

$this->addFieldMapping('field_news_categories:source_type')
  ->defaultValue('tid');

In my UI view, this row appears like this:

Where 'tid' is the value input.

As the documentation points out:

  source_type: If the option value is 'tid', then the incoming value is assumed to be a valid term ID in the destination Drupal instance. Otherwise, it is assumed to be a term name (the default behavior). Note that you'll want to set this to 'tid' if the mapping has a source migration (the sourceMigration() method is used on the mapping).


Can't uninstall module because of checkbox field

You could create a custom form and set all the field values to NULL in the submit handler.

For example:

<?php

namespace Drupal\mymodule\Form;

use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class TestForm extends FormBase {

  public function getFormId() {
    return 'test_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [
      'test' => [
        '#type' => 'submit',
        '#value' => 'Clear field values',
      ],
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $query = Drupal::entityQuery('node');
    $query->condition('type', 'menu_link_content');
    $result = $query->execute();

    $nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

    foreach ($nodes as $node) {
      if ($node instanceof Node) {
        $node->set('your_field', NULL);
        $node->save();
      }
    }
  }

}


You do not have xpath parser inside your mapping, which is required for the XML feed you are using, as it is in XML format.

The Xpathparser is a little confusing at first, but basically in your mapping, map all the XPath parser values to your values within your Content type you're importing too.
Then on /import it should be where you assign your XML field values from the feed to said Xpathparser values, AKA your CT fields.

Flush all caches then go back to your parser settings and click XPath XML parser.

Inside your mapping your source should be xpathparser:0 and then you can map it to what field it should go to from your associated CT(set in Node processor settings). Do this for ever field from your CT which you want a value coming into.

Then when you go to /import there should be a dropdown called XPATH PARSER SETTINGS click on that. there will be a context field, give the context field the value of //requisition. (Optionally you can set this up on the Feeds settings under the Xpath XML parser Settings IF you have already set up your mapping)

The context is  where you want the feeds importer to start importing tag data from. You want the context to be //requisition so you can grab the tag values from within it. (example job_id). Then map the XML field in the XML file to said field.

Example: title = job_id, and Body = rendered_job_posting.


drupal_http_request redirect is not a fully qualified uri. Throws missing schema error 1002

I was trying to dump out the results coming back from my API call one step too early  and before the redirect (to present the token) had taken place so inside Drupal it didn't appear as if anything was happening.


Send Registration Emails To Non-Administrator role / Rules Data Selector By Role

I highly recommend you don't do this, but if you put the following code into a file rules/src/Plugin/RulesAction/SystemSendEmailToRole.php then it'll give you a new action where you can enter the machine name of the role you want to send to (e.g. "myadmins") and it'll do what you want (I tested it, it works though no money back & no guarantee!):

https://gist.github.com/stevepurkiss/9b36eb79311d16c65e8d4d0ba9f1854b

All I did was copy the send email action, swap the 'to' string field to 'role', then load up all user ids with that role, foreach loop through them and insert their email address one by one as it loops through.

Looks like it could be extended to cope with multiple roles like the original code copes with multiple email addresses but this is the best you get in the half hour since I saw your post, and for free ;)

Of course it'll break if you update rules, there's no guarantees, but I did a bit of Rules 7->8 upgrading actions a couple of years back so know my way around a little. Not a lot, but a little ;)

Please also consider supporting rules too, this stuff doesn't appear from thin air, it's a collaboration!

HTH

Steve


I want to send the username of the person submitting the form along with form data

You don't pass $user to the submit function.

Instead, you add a declaration of the global $user object to the start of the submit function to bring it into scope.  Like this:

function input_simple_form_submit($form, &$form_state) {
  global $user;

  // Display a message upon successful submission.
  drupal_set_message(t("Added @color @TV_Show", array(
    '@color' => $form_state['values']['color'],
    '@Name' => $form_state['values']['TV_Show'],
  )));
  $id = db_insert("TestForm")
    ->fields(array(
      'color' => $form_state['values']['color'],
      'TV_Show' => $form_state['values']['TV_Show'],
      'SubmitBy' => $user->name,
    ))
    ->execute();
}


How to correctly add meta tags to custom menu items?

You can do this manually by using drupal_add_html_head(); in your menu's callback function

<?php

function mymodule_home_page() {

  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'custom meta info',
      'content' => 'test content',
      'attributes' => 'D7',
    ),
  );
  drupal_add_html_head($element, 'Test');

  return 'hello';
}
?>

or some modules will allow you to add custom paths.


Altering button title it becomes inactive

Your mistake is this line:

$form['actions']['submit'] = array(

It replaces original button with your own brand new array. Nothing in it, except what you put there. Original node form have submit function connected directly to a button, but you destroyed that with this line.

Instead of deleting original array and creating new one, consider simply altering values you need altered, like:

$form['actions']['submit']['#value'] = t('Activate');


You can connect a external database inorderto let Drupal Know about it:

$databases['external']['default'] = array(
  'database' => 'custom_database',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Then you can connect to that database:

/*
* Switch to external db
*/
\Drupal\Core\Database\Database::setActiveConnection('custom_database');

/*
* Get connection
*/
$db = \Drupal\Core\Database\Database::getConnection();

Then do you stuff and don't footgrt to switch again to the standard database:

/*
* Switch back
*/
\Drupal\Core\Database\Database::setActiveConnection();

You can store your external database info into a content type programatically and the show in views.


Uncheck the Use the default logo supplied by the theme option you find under the Logo image settings section. Don't forget to clear the cache.


Search/filter box for Views on separate page

Hope you know, in views there is one option called "EXposed form in Block"

Just enable this option then you can display the exposed filter block anywhere.

Hope this one helps you


In add filter criteria "user" not coming from FILTER list in add views

It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.


The issue is you're not using things correctly. You should never call blocks directly from templates. Use regions in templates and add blocks to them from GUI, or you can expect IDs to get messed up. Block IDs are based on the order blocks are prepared for display (see implementation of drupal_html_id function), and each time you mess up with the block display mechanism, and go around it, their numbers may change.

If you call block directly because you need to place a block in two places, see answers to Place a block in multiple regions question. Or, if it's a Views block, simply clone block display.

To reliably style a block, you can use Block Class module to assign a class that will not change the way ID does. Alternatively, you can use answers to How to add id to a block to manually override IDs - just be careful to keep them unique if you want JavaScript to continue to work.

Note that not only IDs will get messed up when you call block directly, but also things like permissions and cache settings may get compromised.


If I'm reading the function correctly, search_reindex won't actually empty the search index - it just tells all modules that use search to start re-indexing content.

Uninstalling and re-installing the search module using the "unistall" tab at admin/modules will empty all of the search tables. You will have to temporarily disable all dependent modules to do this.

Alternately, you can empty these tables using the TRUNCATE mysql command. The tables needing to be emptied are search_dataset, search_index, search_total and search_node_links. You could also empty the tables using a database management tool - just be sure to leave the table structure intact - you want to empty the tables, not delete them.

You will then need to disable core search indexing to prevent the search index from filling back up. In your sites/default/settings.php file, you can add:

$conf['search_cron_limit'] = '0';

to prevent Drupal from adding items back into the index on cron runs (while still leaving the search module intact.)


How to add the placeholder in view exposed filter

You can simply add below code to form alter hook

$form['title']['#attributes']['placeholder'] = t('Keyword search');


I think this is a similar situation to a question I asked a little while ago.

I solved it by using hook_views_query_alter() to remove the fields I didn't need in the query.   In your case, it would probably look like:

function MYMOODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'MY_VIEW') {
    unset($query->fields['nid']);
  }
}

dpm() the $query to see what array keys are in $query->fields if that doesn't work.


Cannot find /libraries for installing ckeditor module

You can (need to) create it in the web root.


Different front page depending on previous selection for anonymous users

So... I think I have solved this, although cache testing has not yet been done (any thoughts on how to do this welcome!).

Credit to this post for the outline solution, and also to this one for D8 redirects.

First, I create a custom module called mysite_homepage_redirect - it needs the following mysite_homepage_redirect.services.yml file (apparently a priority > 200 means it gets fired before the cache):

services:
  http_middleware.mysite_homepage_redirect:
    class: Drupal\mysite_homepage_redirect\StackMiddleware\MysiteHomepageRedirect
    tags:
      - { name: http_middleware, priority: 250, responder: true }

Then we need the following in src/mysite_homepage_redirect/StackMiddleware/MysiteHomepageRedirect.php:

<?php

namespace Drupal\mysite_homepage_redirect\StackMiddleware;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Provides a HTTP middleware.
 */
class MysiteHomepageRedirect implements HttpKernelInterface {

  /**
   * Map of pages that should be redirected to from home
   * this coulde ultimately be put into config with an admin screen
   */
  private $navigation_map = array(
    '/employers',
    '/students',
  );

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs a MyModule object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The decorated kernel.
   * @param mixed $optional_argument
   *   (optional) An optional argument.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    $current = $request->server->get('REQUEST_URI');
    $source = $request->server->get('HTTP_REFERER');
    $host = $request->server->get('HTTP_HOST');

    //cut the host string out of the referer
    $x = strpos($source, $host);
    if($x) {
      $source = substr($source, $x + strlen($host));
    }

    $redir = isset($_COOKIE['mysite_homepage_redirect']) ? $_COOKIE['mysite_homepage_redirect'] : false;

    if($current == '/' && strpos($source, $host) === false && $redir) {
      $response = new RedirectResponse($redir, 302);
      $response->send();
      return;
    }
    elseif(in_array($current, $this->navigation_map) && $source == '/') {
      //need to use native setcookie() because user_cookie_save relies on the user module which is not yet loaded
      //expires in 30 days
      setcookie('mysite_homepage_redirect', $current, time() + 86400 * 30);
      \Drupal::logger('mysite_homepage_redirect')->notice("saved redirect cookie: " . $current);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }
}

That seems to work as expected. The cookie seemed the simplest way to save the redirect. Any further thoughts welcome!


Do we need to update every release sequentially to get to the latest version?

You do not need to update Drupal sequentially. The Drupal update system will run all the needed updates so that you can go from (lets say) 8.3.0 to 8.6.1 directly.

Regarding your question about "If we can update to 8.6.1 directly, how do we handle the case if a release like 8.5.4 requires changes to 'default.settings.php' but 8.6.1 doesn't require?" ... If 8.5.4 requires a change to settings.php then 8.6.1 will assume that those changes are there already.

Note: its a good practice to update core (at least for minor versions) so that you are always in a position to quickly apply security releases. The Drupal security team has recently decided to support the most recent 2 minor releases, but still...

Check out this further reading and also this


This won't work out of the box because Feeds is expecting a CSV but you can convert this to a proper CSV file using the Feeds Tamper module to modify the data before passing it to feeds.

However, the easier way to do this would be to just load the file back into Microsoft Excel as a delimited file, and then export it back as a proper CSV.


How to update the URL Redirect module v1.4 to its latest version without losing redirects?

You can update module to v8.x-2.3 and run drush updb or update.php. In 8.x-2.3 version all existing redirects get converted to an entity in an update hook.

/**
 * Migrate old redirect data.
 */
function url_redirect_update_8103() {

  $db_connection = \Drupal::database();

  if ($db_connection->schema()->tableExists('url_redirect')) {
    $query = $db_connection->select('url_redirect', 'ur');
    $query->fields('ur');
    $all_data = $query->execute()->fetchAll();

    foreach ($all_data as $key => $data) {
      $values = array(
          'label' => 'Migrated Redirect',
          'id' => 'migrated_' . $key . '_' . time(),
          'path' => $data->path,
          'redirect_path' => $data->redirect_path,
          'roles' => Drupal\Component\Serialization\Json::decode($data->roles),
          'users' => Drupal\Component\Serialization\Json::decode($data->users),
          'status' => $data->status,
          'message' => $data->message,
          'checked_for' => $data->check_for,
      );
      $url_redirect_entity = \Drupal\url_redirect\Entity\UrlRedirect::create($values);
      $url_redirect_entity->save();
    }

    // We can drop 'url_redirect' table once we confirm everything is migrated properly.
    // $db_connection->schema()->dropTable('url_redirect');
  }
}


Did you check what user is the owner of each of your folders in question ?
Use chown username:groupname to change owner/group of a folder.


Finding the Machine Name of an Module-based Field Added to $content variable

Install the devel module and use dpm($content) to inspect the content variable.

A good place to adjust the contents of a page in your theme is in a preprocess function.


How can i insert a comment form between parent comment and comment replies？

I don't know if it's correct way but maybe help somebody.

    function theme_preprocess_node(&$variables, $hook) {

$test_pid = array();
$test_cid = array();
$keys = array_keys($variables['elements']['comments']['comments']);

foreach ($keys as $k) {
    if (!is_numeric($k)) {
      continue;
    }
$pid = $variables['elements']['comments']['comments'][$k]['#comment']->pid;
$cid = $variables['elements']['comments']['comments'][$k]['#comment']->cid;
$test_pid[] += $pid;
$test_cid[] += $cid;
$variables['elements']['comments']['comments'][$pid]['#comment']->has_children = TRUE;
$last = $k;
}

// find all last children in comments
$Mcomment_children= array();
foreach($test_pid as $key=>$p){
    if (in_array($p, $test_cid)) {
         $Mcomment_children[$p] = $test_cid[$key];
    }
  }

  foreach($Mcomment_children as $last_children){
    $variables['elements']['comments']['comments'][$last_children]['#comment']->last_children = TRUE;
  }
  $variables['elements']['comments']['comments'][$last]['#comment']->last = TRUE;
}

In comment template file (comment.tpl) you can close div with children last. I used display suite but it's the same.

<?php if($comment->has_children !== true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>
  <?php if($comment->last_children === true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>


What is the hook to alter workflow access permissions?

There is no single hook that allows you to control who can see or edit a node in a specific workflow state. You might want to implement hook_node_access_records() to give out grants for a specific node and hook_node_grants() to check whether a specific user has that grant.

The result of your hook_node_access_records() implementation is stored in the database and checked via your hook_node_grants() implementation. Have a look at node_access() to see how the latter is done.

I cannot tell you off-hand what to use as realm and what to use as grant ID. The most important restrictions are:

the grant ID is an integer,
hook_node_access_records() does not know which user tries to access the node,
hook_node_grants() does not know about the node that is being accessed.

In your case, it seems reasonable to put the expected profile value into the "realm" (along with the module name for disambiguation) of your hook_node_access_records() implementation. Your implementation of hook_node_grants() would then check whether the user has that profile value and return the appropriate realms. Still you need to accommodate for the workflow state somewhere.


redirect to custom profile panel page of individual users

Panels provides a built-in way to override user profiles-- look for the link (disabled by default) in Page Manager called user_view (User Profile Template).  Instead of using your own custom profile page, enable this page override (User Profile Template) and make your changes to that panel.

Then, to link to user profiles, you can just use the standard user profile links, no rewriting needed.


Composer using old JSON for contrib module?

Im the maintainer of packages.drupal.org - I went ahead and deleted the invalid data out of the database, and this will install now.

I've also opened and issue on drupal.org to put more defensive measures in place. https://www.drupal.org/project/project_composer/issues/3076342

I think something must have changed in how permissive composer is with certain bad version constraints.


Not_compatible_with_d7 after installing User Points Contributed modules

The reason you see that error message is that the content of the votingpoints.info file is the following one.

name = Votingpoints
description = Rules integration for users earning points as they vote on nodes. With the rules approach, the node author can be assigned userpoints too.
package = Userpoints
dependencies[] = userpoints
dependencies[] = rules
dependencies[] = not_compatible_with_d7
core = 6.x

not_compatible_with_d7.module is reported as dependency of the module, and Drupal tells you that module doesn't exist.

What happened is that a Drupal 6 module has been committed in the Drupal 7 branch of the project; in this way, who wants to port the module for Drupal 7 can easily create a patch for the Drupal 7 branch of the project. The problem is with the script creating the archives containing the code of a Drupal.org project adds the like "core = 7.x" overriding the "core = 6.x" line added to the votingpoints.info file. This would cause Drupal to think the module is compatible with Drupal 7, which is not true.

The only workaround the authors of the modules found was to add, as dependency, a module that doesn't actually exist. That is the only thing that can be done, until the packaging script used from Drupal.org overrides the line reporting the Drupal version with which the module is compatible.


Adding custom field to apache solr drupal 7

The apachesolr module defines a hook that allows a search document to be updated before it is sent to the Solr server for indexing. Actually, I lied, there are two.

hook_apachesolr_index_document_build and hook_apachesolr_index_document_build_ENTITY_TYPE (for specific entity types).

<?php
/**
 * Implements hook_apachesolr_index_documents_build_ENTITY_TYPE().
 */
function mymodule_apachesolr_index_document_build_node(ApacheSolrDocument $document, $entity, $env_id) {
  // While indexing article node content
  if ($entity->type == 'article') {
    // Get the field value that needs to be indexed
    if ($fields = field_get_items('node', $entity, 'field_example_field')) {
      // Only need the first value
      $value = field_view_value('node', $entity, 'field_example_field', $fields[0]);
      // Add the value to the document to be indexed. ss_ prefix denotes a string type
      $document->setField('ss_index_field_name', $value);
    }
  }
}

The content is added to Solr via the line $document->setField('index_field_name', $value); While the example is very simple, this can be used to index values from complex relationships that wouldn’t normally be possible.

Any content that already exists in the index will need to be reindexed.

Now that that new custom field exists, it can be made available for the search results display. Using hook_apachesolr_query_prepare the search query can be altered, in this case to add the new field.

<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // Make 'index_field_name' available for search results
  $query->addParam('fl', 'ss_index_field_name');
}

The new field can also be used to filter search results, again using hook_apachesolr_query_prepare.

<?php
/**
 * Implements hook_apachesolr_query_prepare().
 */
function mymodule_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  // filter where 'index_field_name' = 'indexed_value'
  $query->addFilter('ss_index_field_name', 'indexed_value');
}


You can put php code in a block template and write something like:

$node = node_load($node_id);

and then access the specific field you want to show like:

print $node->title;
print $node->field_yourfield["und"][0]["value"]

Edit:

Also, you can modify the node template for the teaser, copying the node.tpl.php file in your subtheme (you can look how to make a subtheme here) and putting the html structure you want inside:

if($teaser)
{
...
}

There are other displays available for nodes other than page and teaser.


Is checking the value of $order->status sufficient to understand when an order has been completed?

All the checkout order statuses are prefixed with checkout_, so there is no need to check the state. Just bear in mind that in Commerce 1.x, an order may be moved into and out of that status multiple times. If you need to ensure an operation only occurs once per order, you can follow the core precedent of logging the timestamp for your operation in the $order->data array.


In view, add a sample no global "link" field foreach row

I find how do with this usefull guide

I created a custom field and I added it to my view. The content of my field is defined in the render method of the FieldPluginBase Class.

In addition, we can quicly and properly generate a FieldPluginBase Class and views.inc with drupal console (command 'drupal gpcf')


How to create add custom style to specific view in drupal

This is actually really easy with views. I am going to assume you are using Drupal 7 with Views 3. But this works almost the same in previous versions of both as well.

First, go into your view. On the far right expand the "Advanced" fieldset if it isn't already expanded. Then click on the "Information" link next to Theme at bottom of the list.

This will popup a modal that will display how to name your template files to replace the default template. It specifically allows you to modify different levels of the template. Find the level you want to modify. Then, while reading the list from left to right (right being the most specific) pick the name that is specific enough for your uses.

Next, go into the views module and find a copy of the bolded template file and copy that into your theme folder into a templates folder or into a custom module. Then give it the name you found above and make your changes.

Finally save it and flush the Drupal cache. Now when you go back to that information page it should show your new template file highlighted. This may require a few refreshes.

Now on another note, if you use the built-in field controls you can add custom CSS classes to help target the specific view and thus a specific button underneath it. You can also add specific classes to the view in the advanced section.

Though keep in mind drupal already gives us a ton of classes to each element, so you shouldn't need any of this just to target that view and a specific button within it.


Allow user to filter View by Month only using a D/M/Y date field

You can use Computed field and create other field on your content type, there Month will stored (calculated as PHP code: return date('m', {Date Field Value});, so you can easily filter by months in Views by this field...


Which node table in Drupal 6 stores the node published date, created date timestamps?

The node created and updated timestamps are stored in the base "node" table.

e.g

$result = db_query("SELECT nid, title, changed, created FROM {node} ORDER BY nid ASC LIMIT 10");

while($row = db_fetch_object($result)){
  // drupal_set_message($row->title);
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}


Display all taxonomy terms's ids associated with nodes in a view

Add field "All taxonomy terms". Then check the "rewrite output of this field" box, and in the rewrite box enter the token [term_node_tid-tid].


Just about the time you posted your question, the new Superfish features showed up in beta.  These features include a multi-column capability. You would want to use CSS to style it, but the multi-column capability comes through the configuration panel.

There is a nice tutorial here:
http://www.digett.com/blog/02/19/2013/superfish-mega-menus

Pay special attention to the limitation: the multi-column nature of the menu is enabled for the entire menu, and you have to explicitly indicate any menu items that are to be excluded.

Presently, the dev version is the most highly recommended by the developer, but leave yourself a way to back out, in case you hit a problem.

Also, pay close attention to the instructions for upgrading to v1.9

d


I found a solution: use a field group (Field Group) of booleans and set them as exclusive values (Exclusive value).


Drupal 7 can run on any PHP version between PHP 5.6 and PHP 7.3. For running on PHP 7.4, it's required at least Drupal 7.71.
Drupal 8 can run on any PHP version that is newer than PHP 5.6. For running on PHP 7.4, it's required at least Drupal 8.8.3.
If the site is running a version of Drupal that is older than Drupal 7.71, I would first upgrade PHP to PHP 7.3, and then upgrade to Drupal 8.
If the site is running on Drupal 7.71 or any newer version, you can upgrade to PHP 7.4, if you mean to upgrade Drupal to Drupal 8.8.3 or a newer version.
I would also test the upgrade on a local test site, as third-party modules you are using could cause problems with newer PHP versions.
It should be safer to upgrade to PHP 7.3, as there are backward incompatible changes in PHP 7.4 that required changing the code in Drupal 7; it's probable the same changes are required in third-party modules, but those changes are still to be applied to those modules.


You want to try using the Views Aggregator Plus community module.

The example from the Project page (very similar to your own):

  Say the original View based on raw database results looks like below.

Industry    Company Name    Turnover
IT          AquiB           $25,000,000
Clothing    Cenneton        $99,000,000
Food        Heiny           $66,000,000
IT          PreviousBest    $5,000,000
Food        McRonalds       $500,000,000

  Then with the grouping taking place on, say Industry, and aggregation
  functions TALLY, ENUMERATE and SUM applied on Industry, Company Name
  and Turnover respectively, the final result with a descending sort on
  the last column will display like below. Note that the module
  identified three groups. It also added a totals row, Views Calc style.

Industry        Companies            Turnover
Food (2)        Heiny, McRonalds     $566,000,000
Clothing (1)    Cenneton             $99,000,000
IT (2)          AcquiB, PreviousBest $30,000,000
Totals              5                $695,000,000

At that point I think you just need to play with output settings of that module ...


Expose Custom DB Tables to Drupal Views Error

The tutorial you linked to implements hook_schema() which means Drupal will want to take care of the table implementation for you.

I don't know this for definite but I think Views requires that the table be under Drupal's control when you're exposing custom data.

I don't know of a way to tell the installer to ignore the schema installation, so the simplest thing to do would probably be to rename the custom table temporarily, install the module (allowing Drupal to create the table), then import the data from the temp table into the newly created one.

If you then uninstall the module (not just disable), your custom table and the data will be lost so it's worth keeping a backup if you think that's likely to happen.


Drush suddenly stopped working for one site

I cannot answer why this happens, but I have a site that periodically does this with drush pm-enable.  I think this site has trouble doing the nightly module update check, and something bad gets cached.  A drush cc all always fixes it.


You have a tiny error in your code, the placeholder array should be

array(':title' => 'scrivimi')

not

array(':title' = 'scrivimi')


I found a solution, I wrote this in a preprocess function:

function THEME_preprocess_html(&$vars) {
  // Add body class if current url is configured to have header/footer hidden.
  $urls_to_test = array(
    $_GET['q'],
    drupal_get_path_alias($_GET['q']),
  );
  foreach (explode("\n", theme_get_setting('head_footer_hiding_urls')) as $url) {
    if (in_array($url, $urls_to_test)) {
      $vars['classes_array'][] = 'theme-hide-header-footer';
    }
  }
}


How can we edit www.example.com/user page?

The page at http://example.com/user has two purposes:

Showing the login form for the users who are not logged in
Showing the profile page for the users who are logged in

In the first case, there isn't anything that you can edit to change how the login form is rendered. What you can do is implementing hook_form_user_login_alter() in the theme you are using, or in a module, to alter how the login form is rendered. In this case, you can use the #prefix and #suffix properties to inject CSS classes to the form fields, and #attached to load a new CSS file containing the CSS styles you need.
The alternative is associating a theme function to render the login form, through #theme.

In the second case, with the exception of the template file used to render the page, there isn't any file you can edit to change how the user profile page appear. Editing the user-profile.tpl.php template file used by the currently used theme is the easier, and faster way to change how the user profile page appears.
The alternatives are:

Changing the page callback associated with the user/%uid path with hook_menu_alter()
Implementing hook_user_view() or hook_entity_view() to add items to the user profile page
Implementing hook_user_view_alter() or hook_entity_view_alter() to alter what the user profile page contains

See also Gisle Hannemyr's answer; if you just need to change the order in which the fields associated with a user account are rendered, or slightly changing how those fields are rendered, that is the answer for you.


According to Display TIFF image in all web browser unless you're on Safari, you will not be able to render the .tif image on your site.

Therefore, this more like a file rather than an image. If you want to upload it, for your field type use file instead of image.

If you plan to display/render the .tif image, you will have to convert it to a known image file: .png, .jpeg, .gif, etc..

Edit:

  Do we have any drupal module that can convert .tif to other image
  extension? – Govind

According to Henk's comment in Upload tif using image API there is a way:

  I was looking for a similar solution and found a working solution in
  Drupal 7 to upload, scale and display tiff images.

  Install ImageMagick module and its dependencies with ImageMagick tif
  support on the server

  Install Media module

  Use the media module as the widget type for your image type field
  because the regular image widget type does not support TIFF's, with
  that you should be able to upload tiff images in Drupal

  And i forgot...add the "change file format to : png" for your image
  style because only Safari is capable of displaying tiff's directly


How do I print breadcrumbs on page.html.twig?

The breadcrumbs are now a block. You have to go to the block layout and put them into a region. If you want {{ page.breadcrumb }} to work, you have to put them into the region breadcrumb.

This is the same for site branding and title, they all have moved into blocks.


Use PathAuto module

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

For learn how work with it read How to Use Pathauto in Drupal 8


Try removing the required line. Updated code:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['pdf_file'] = array(
    '#type' => 'file',
    '#title' => $this->t('PDF File'),
    '#description' => $this->t('PDF files only'),
    //'#multiple' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

Update: As upload fields can not be required in PHP, just make it required in JS/jQuery

Add this code to a JS file:

$( "#target" ).submit(function( event ) {
  if( $(".pdf-file-field").files.length == 0 ){
    alert("Please add a file");
    event.preventDefault();
  }
});

Note: Instead of "event.preventDefault()", you should also be able to use return false.


Render node fields and labels in node template

The label is in the field definition, you have to add fieldDefinition before label:

{{ node.field_myfield.fieldDefinition.label }}

To explain this, node is the node object. Content is the render array of the fields, that are build as configured in the view mode. In node you find the raw values and definitions of all fields of the node. In content you only find those fields that are in included in the view mode and they are already formatted as configured in the view mode. You also find each of the fields as object in content, but you cannot be sure, that the field is there, because if someone later removes the field from the view mode, your code will get a null value.


How can I rearrange a menu link programmatically?

You can rearrange a custom menu link when you set the 'weight' of the menu. See below code.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();


Should I replace Magento with Drupal for my e-commerce solution?

Having never used Magento, I'd say go with Drupal + Drupal Commerce ;-)

Check out the following articles though:

Magento vs Drupal Commerce
E-Commerce: Which CMS is better for e-commerce? Magento vs. Drupal? Others? (Quora)
Drupal Vs. Magento (eHow)
Magento vs Drupal Commerce (drupal.org)
Google ;-)

Drupal will allow you to import products with a combination of Feeds and Commerce Feeds or Commerce Migrate (the latter requiring a bit more work).

I think at the end of the day it comes down to your personal needs.  If you don't need a fully functional CMS (or CMF...make your own mind up), then better the devil you know; might as well go with Magento.

If you want a whole integrated solution, then Drupal is clearly the winner.  I'm pretty sure there are a couple of dev houses around where I am who are migrating sites from Magento to Drupal Commerce, but I've not heard of anyone doing it the other way around.

Lastly, depending on the complexity of your project you may have to get your hands dirty with Drupal too, but it's not that hard :).


Call Drupal PHP function from Javascript?

To get data from Drupal's database and/or produced in PHP, you need a page callback (in a custom module) that output the data without the full layout rendering. This is easily doable by printing the content of the page directly in your page callback instead of returning it.

If you want to retrieve nodes in AJAX, you can also use the Services module which provides JavaScript callable endpoints (REST, JSON over HTTP) for nodes, users, taxonomy terms, etc.

If you still want to work outside Drupal, in a standalone script, you should include Drupal's include/bootstrap.inc and call drupal_bootstrap() function to initialize Drupal environment (connect to database, load modules, session, etc.). You can select the phase to bootstrap depending on what you need from Drupal.

chdir('path/to/drupal/root');
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Drupal is fully loaded here, you can access everything.


Dynamic frontpage image changes every hour

Inside of views, over in its cache settings, you can choose TIME and then select one hour for the results and output. Then, if you have it show a random image, it will cache that and only select another image after that hour has passed.  This of course will be defeated if your page is cached, but if its cache lifetime is less than an hour, it will cache up eventually (I just made a pun lol)


How to disable payment cart pane when discount brings total to $0

I was able to fix the problem by modifying the "Free Order" payment method's Conditional Action. Free Order is the payment method associated with the Ubercart Free Payments Module and comes pre-loaded with a CA that checks the cart total to see if it is more than $0.01... if it is more than that, it negates that condition and does not allow the Free Order payment method in the cart.

I changed that CA to instead check whether the cart had the discount(s) in question. If the discount(s) was used, the cart pulls in the Free Order payment method, and it all works as expected.


This works for me:

<?php

$ch2 = curl_init("http://openexchangerates.org/api/currencies.json");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);

$json2 = curl_exec($ch2);
curl_close($ch2);

$currency = json_decode($json2);

return (array)$currency;


Is there a way to enable Basic Auth for only one specific type of node?

Probably there is no one here, that has tried the method you've described. I would start with a custom entity, use the basic auth or create a new authentication provider and apply this for the entity route. You can do this with drupal console within a minute.

And you don't need contrib code to configure access for the custom entity, because here you can do what you want in core. I wouldn't use an Access plugin from contrib, until there is a stable release.


The problem is caused by not installing drush_language in the correct directory.
If you stil have the problem:

First remove anything related to drush_language:

Go to your drupal folder and do drush pmu drush_language
Go to /drupal/sites/all/modules and delete the directory drush_language, if it's there.
check your system for a global drush_language: e.g. do updatedb & locate drush_language. Then delete any folders called drush_language.
Go back to your drupal root folder an do: drush dl drush_language --destination=./sites/all/modules/


How can I quickly re-save all the nodes on my site (to trigger a rule that activates on content update)?

VBO has an "Execute PHP code" action.
Run it, and input "node_save($entity);" (without the quotes) in the textbox.
That will do the trick, while handling the timeouts for you.


To add some custom event on flag/unflag actions in Drupal 8 you need to use Event subscriber:

public static function getSubscribedEvents() {
    $events = [];
    $events[FlagEvents::ENTITY_FLAGGED][] = ['onFlag'];
    $events[FlagEvents::ENTITY_UNFLAGGED][] = ['onUnflag'];
    return $events;
}

And then in onFlag() and onUnflag() methods you can implement your custom logic.

I just wrote a blog post with some code examples: http://dev.studiopresent.com/blog/back-end/perform-actions-flag-unflag-drupal-8


PHP query in a view will cause website error

You cannot directly insert values into queries in Drupal. They need to be escaped. You would want something like this:

$count_users_premium = db_query('SELECT COUNT(license_id) FROM {commerce_license} WHERE state=:active', [':active' => 'active'])->fetchField();


Search autocomplete - what is the proper way to make it work for more that 13000 nodes?

I have not run into this directly with Search Autocomplete, but have run into similar issues with Views autocompletion with very large node sets.  There are two things that have helped me in the past.

One, is to make sure your database is truly optimized, to eliminate that from any speed problems.  mysqltuner will give you a good starting point.

The second thing requires monkey patching misc/autocomplete.js to use your own version of Drupal.ACDB.prototype.search which uses a minimum search needle length to lower the initial result set.  TBH, I have done this before, but it was so long ago that I forget the details.

Also keep in mind that single word searches will be against the index (which has a MySQL index), but multiword searches are against the dataset, which is essentially a LIKE query, which can be slow.  Enable query profiling to see what is going on there.

This should give you a starting point.


Disable CSS and JS from a contributed module

I think setting the library to FALSE should work:

libraries-override:
  # Replace an entire library.
  simple_megamenu/base: false


How to translate strings in (programmatically created) custom module?

Potx is not yet ported to Drupal 8 but it can parse Drupal 8 modules.

You can install it as a drush command instead of a drupal module and then it should work fine on your Drupal 8 module.

What that doesn't support yet is extracing existing translations from a running site. Looks like people are working on a port in https://www.drupal.org/node/2356469 which supports that.


I just realized they are just printed to the command line and are not contained in the return value itself. So it is actually working. Since I was printing my variable directly for debugging it looked like it contained the messages as well.


Check the source code, maybe something is registering it via hook_entity_info_alter


How do you get field groups to render for a block_content entity loaded programmatically?

The field_group module does not currently support the block entities, see Does not work with blocks [2689501]


Try this:

on the view edit screen click on the display you want to theme
click on the "Advanced" tab so that it slides down
in the "Others" section click on the "Theme: Information" link
in the "Row style output:" section you'll see the template file names you can use, you are currently using the one that is bold, the last name is the most specific, i.e. something like views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php

simply copy views-view-fields.tpl.php from the "theme" directory of the Views module to the directory of your theme, rename the file and modify as you wish (and clear the cache)


How to count number of field collection items for a row in a view?

While it may be possible with just using Views. I find it easier to do this type of 2-step logic in Drupal with additional information.

For example use Computed Field module to store an integer value in the field on node save for a custom computed field called number_of_fc_values or whatever you want to call it. You then just count the number of field collection items on save using PHP.

For example your PHP could look like the following for the computed value PHP field, this example API usage is taken from https://drupal.stackexchange.com/a/84282/3279

$node_with_fc = node_load($node->nid);
$items = field_get_items('node', $node_with_fc, 'NAME_OF_FC_FIELD');
return count($items);

Now in your View you simply add your number_of_fc_values field to the field values for the row display.


Panels not showing default image set in Field settings of content type

This is an issue with CTools. Apply the patch from Default value of image field is not shown


What is the difference between using theme_table() and theme('table', array())?

It's not the same.

theme() function is some kind of wrapper for specified theme functions.

It's recommended to use theme() function instead of direct calls, so theme('item_list', array()) is the right way.


Done it!!  This works anyway:
[current-page:url:args:first]/[current-page:url:args:value:1]


To get the current route name, use:

$route_name = \Drupal::routeMatch()->getRouteName();

You can add the current page's route name as a variable in your theme's ".theme" file.  Add a _preprocess_page function like this, and clear the drupal cache.

/**
 * Implements hook_preprocess_page().
 *
 */
function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::routeMatch()->getRouteName();
}

Then you can access in page.html.twig like this:

{{ route_name }}

Note: \Drupal::routeMatch()->getRouteName() will sometimes return null.

If you are inside a class, to do things properly, you'll want to inject the route match service in the constructor and then call it this way:

$this->currentRouteMatch->getRouteName()

The constructor (and variable) will be like this:

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $currentRouteMatch;

  /**
   * Constructs a new ThemeTestSubscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $current_route_match
   */
  public function __construct(RouteMatchInterface $current_route_match) {
    $this->currentRouteMatch = $current_route_match;
  }

If it's a service class, you'd then pass it into the service in the yaml file in your custom module:

services:
  mymodule.service:
    class: Drupal\mymodule\MyCustomService
    arguments: ['@current_route_match']


Filename for the front page template file

In Drupal 7, you need two dashes in your filename; try page--front.tpl.php.


How to use curly braces in schema default value?

In your schema, for the field you want to serialize, you can add the key serialize => TRUE and use the drupal_write_record() function to write the field in the database. After, you have just to send a simple array()(without serialize()) and Drupal will do it by himself.

You can have more information in the documentation.


How do I access Session variables in Drupal that were set on non-drupal pages?

You also need to boostrap drupal before use drupal's sessions (here: Properly bootstrap drupal for standalone PHP file?)


Views Module "Page" and Contextual Filters

You are close. Remove the "Global: Null" contextual filter and configure your "content: nid" contextual filter this way:

WHEN THE FILTER VALUE IS NOT IN THE URL => Display all results for the specified field
WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED => Specify validation criteria, content, type: press releases

To get the press release links changed, you need to:
- add field "content: nid", exclude from display, and rearrange on top, above title
- edit title and remove "Link this field to the original piece of content". In "Rewrite results" check "Output this field as a link" and enter "press-releases/[nid]".


How to display fields horizontally in a node?

The default behavior of Drupal's field display is to wrap the content in DIVs, which are displayed as block-level elements by default, hence, one per line.

There are a number of different ways to solve for your display needs.

As Sidharth mentioned, displaying fields can be done via custom CSS. Typically you'd want to create a custom node.tpl.php for your theme and apply your CSS rules to those elements in your template.

Another solution, if you're not looking for custom templates for different node types, is the Field Group Inline module.


Permission to submit webform only for the author of the node

You haven't said if this is Drupal 7 or Drupal 8 but this should work for D8

It sounds like each author already has a user account on your website, so you can go to "Settings" on your webform and then click the "Access" tab (.e.g /admin/structure/webform/manage/FORM_MACHINE_NAME/access)

And in there you can restrict the ability to create submissions to a specific user(s) only


Which tables should be emptied when clearing database-stored cache manually?

In drupal 8 if you are looking for the safe tables that needs to be cleared manually then clear the tables starting with cache_   and also truncate the cachetags table too.

If you are using drush then use this command for clear cache-

drush cache-rebuild


How to generate a list of which Features are enabled in which Spaces?

Features are modules, and Views 3.x can make listings of enabled modules. But as explained in How to make a Feature available only to certain Spaces?, this is not possible, since modules are enabled site-wide.


Large amount of entity revision cleaning leads to connection abortion

It turned out what the real issue was. I didn't mention (thought it's not important) that this was actually a Drush command pointing to another multi site.

The actions took "too long" on the other site and by the time it returned with success, the default Mysql connection was timed out and couldn't write to the database anymore. (even tho the corresponding Mysql timeout settings were way higher than the actual amount of time that was spent on the other site)

We solved with with

$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes);
if (!is_resource($process)) {
  throw new \InvalidArgumentException("Could not execute `{$command}`.");
}
while (($status = proc_get_status($process)) && ($status['running'])) {
  $this->entityStorage->getQuery()->count()->execute();
  sleep(5);
}
proc_close($process);


If M1 is enabled, the .module file will be included on every page load anyway. And if M1 is a dependancy of M2, M1 will definitely be enabled if M2 is enabled.

It's only the other files (.inc, etc.) that might contain extra functionality that you'll need to load explicitly with module_load_include().


How to make the UserProfile Info availlable on a block

You need to use the global user object to get info about the currently logged in user, then pass that user object to profile_load_profile:

function THEME_preprocess_block(&$variables) {
    global $user;
    $user_profile = profile_load_profile($user);
    $variables['user_profile']= $user_profile;
}

(code is untested but should work)


After lot of search and test I have discovered where was the problem. If I enable Universally Unique ID module, I can't create/update entities. If I disable this module, all works good again. So the problem is with this module.

There is another open question about this issue in this link. So I think I should close this. Thanks.


What's the proper way to refer to all the code in `core/lib/Drupal`, or the code in `core/lib/Drupal/Core' or `core/lib/Drupal/Core/Foo`?

What you describe is correct, when you install Drupal, everything in the 'core' directory is considered the core set of Drupal files, or the bare minimum installation package.

The files in 'core/lib' is essentially all of the source code for the running system.  Personally, this is what "core" means to me.  The files (for the most part1) outside of that are the scaffold (or support files).

The files in 'core/lib/Drupal/Core' are called "Core", pronounced with a big C.  The files in 'core/lib/Drupal/Component' are called "Component", pronounced with a big C.  Confusing, yes?

"Component" are the set of files that Drupal uses, but don't actually rely on anything else in "Core".  For example, DateTimePlus and Time are two Components, that don't need anything in 'core/lib/Drupal/Core'.

"Core" are the set of files that Drupal uses, but are interdependent on each other, and also require "Component".  For example, DrupalDateTime relies on DateTimePlus (in Component) and the Language subsystem (in Core).

1Ignoring tests for this discussion.


How to check progress of sql-sync that hangs up?

Run with --verbose or --debug to see more and lots of output, respectively, or run with --simulate to see only the commands that Drush would run.

Another helpful thing to do with sql-sync is to run drush @mysite.es.remote sql-conf and drush @mysite.es.local sql-conf - this will print out the database records sql-sync will use for the two sites.  In your case, since you are getting to the y/n prompt, this part is probably working.


What you are seeing above is a bug in Drush where Drush cannot bootstrap the database of a Drupal site if the database credentials are correct, but the database itself is empty.  To fix this problem:

If your database is empty, run "drush site-install" to create a database.
If your database is not empty, check the settings of your database prefix, and make sure that it is correct.

This was recently fixed in https://github.com/drush-ops/drush/pull/1442.


You can use Panels, Display Suite and Context to build a different layout flexible and custom layout in your theme.
You can also build a custom theme with there layouts and switch the layout home page based on context. If you are planning for theme, you can write a subtheme for Omega, a HTML5 base theme, or can you choose the best base theme as per your need.


Behat test fails, unable to find Username field using @javascript

I bet you are either one:

Testing against a non-English site.
Having BigPipe enabled.
Missed to tag that scenario with @api.
Misconfigured Selenium.

To solve 1. you need to put the non-English strings into your behat.yml like so:
Drupal\DrupalExtension:
  text:
    log_out: "Sign out"
    log_in: "Sign in"
    password_field: "Enter your password"
    username_field: "Username"

@see docs Override text strings.

To solve 2. which can occur when BigPipe somehow changes the markup in an undesired way, you can try out the patch at https://github.com/jhedstrom/drupalextension/pull/325.patch.
@see pull request Big pipe compatibility follow-up

To solve 3. simply add an @api tag to your scenario.

To solve 4. you must point wd_host to http://dev.mysite.com:4444/wd/hub, since your base_url is http://dev.mysite.com.
wd_host: "http://dev.mysite.com:4444/wd/hub"


How can I list all Twig functions and filters with their description?

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21TwigExtension.php/class/TwigExtension/8 Twig functions have no descriptions. You can run getCallable on a twig function/filter object and then do $reflection = new \ReflectionFunction($callable); $doxygen = $reflection->getDocComment() to get the doxygen which is the closest to "description".


How do I add local tasks menu to a views page display

@Eyal was right. Some information:

Find the current route : /devel/routes gives you all the registered routes.
Or better : use the devel module & web profiler submodule to display the Symfony2 toolbar, you will have a lot of useful information, especially the current route.

  You should find a route name as view.my_page.page_1 for example.

Create a modulename.links.action.yml (or modulename.links.local.yml) with this content:

view.my_page.page_1:
  route_name: view.my_page.page_1
  title: My button title
  appears_on:
    - view.my_page.page_1


How to fix incorrect average ratings for Fivestar?

Truly correct way to fix it would be to salvage original IP addresses of voters from original database.

If you cannot do it, randomize. Assign each vote an IP from 127.0.0.0/8 range, that way you will not interfere with future votes and large number laws says you'll have pretty small number of duplicates, so averages should be about right.


Add "Sale" or "Discount" text to a product display using drupal commerce?

With Views Conditional you can make it that if Label Discount Name is equal to Sale then

 Otherwise output nothing.

Then do the same for Discount.

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

  Views conditional allows you to output text based on the result of the
  condition.


You should familiarize yourself with Drupal theming. Check out the Theming Guide.

Basically, you want to edit the CSS in the theme that's currently being used on your site.


Create a user via the Installation profile

If you still want a configuration form, then you can build upon the "Client step" and change the function brochure_client_form_submit($form, &$form_state) so that it suits your needs (all code is untested):

function brochure_client_form_submit($form, &$form_state) {

  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

If you don't need a separate configuration form during install, you can define a "formless" task like this:

/**
 * Implements hook_install_tasks().
 */
function mymodule_install_tasks() {
  $tasks['mymodule_setup_admin_account'] = array(
    'display_name' => st('Setup admin account'),
  );
  return $tasks;
}

function mymodule_setup_admin_account() {
  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

You still have to create the role and add it to the created user. If you have created the role prior to the user creation, then you can also pass it directly to user_save:

$account = array(
  'name' => YOUR_NAME,
  'pass' => YOUR_PASS,
  'mail' => YOUR_MAIL,
  'status' => 1,
  'init' => 'install profile', // Just an example
  'roles' => array(
    ROLE_ID => ROLE_ID,
  ),
);
$account = user_save(null, $account);

More on install profiles: How to Write a Drupal 7 Installation Profile