How can I prevent composer from detaching a module's head?

mradcliffe is correct:

  composer checks out the git commit hash rather than a branch if I recall correctly.

This is fairly easy to deal with though. For example, if your main branch is 8.x-1.x, then you do some work on detached head, you can commit the work on the detached head, which will give you a hash. You then check out the 8.x-1.x branch, and merge the hash. Since the detached head has the 8.x-1.x branch upstream, it can be merged back into that branch after you make your changes.

Example:

$ git status
HEAD detached at aa284c1
$ git add file.php
$ git commit -m "Committed file.php"
[detached HEAD ef37212] Comitted file.php
$ git checkout 8.x-1.x
$ git merge ef37212

If you realize early enough, you can actually just run git add on all your changed filed, then check out  the 8.x-1.x branch. Then you can continue to work there, or make a commit on that branch. Or you can even create a new branch from 8.x-1.x and continue your work in that branch.


All about that matter here.

Current options are:

Outline Designer
Weight
Nodeorder
Nodequeue
DraggableViews
Flag Weights
Sortable Grid Views Plugin
JQGRID


When using the Batch API should I create an operation per node?

Ok, so I figured out a better approach. Below I have listed my new code. The gist of it is that I decided to break it out in such a way that I will have one operation per 100 nodes that need to be fixed. I have 6,581 nodes that need to be fixed. So that means I need 66 operations to fix all of the nodes.

I created some calculations that determine how many operations I need to run. Then I set each operation to only process 10 nodes at a time (to save memory). Once an operation has hit it's max of 100 nodes it then tells the Batch API it is finished. This is part of what I was getting hung up on. I thought that max and finished referred to the entire batch process, not the current operation.

Theoretically I could create an operation for every single node that needs to be fixed. But this seems highly excessive, and a bit inefficient. It would increase the db calls quite a bit and the HTTP calls.

Another improvement I made to my code is to only return the node id field in the query instead of all those extra fields that I didn't need. This changed the query run time from about 7.5 seconds to about 0.24 seconds.

All in all I am much happier with the results.

function my_fixes_broken_body_nodes() {
  $results = db_query("SELECT n.nid
  FROM node n INNER JOIN field_data_body b ON nid = entity_id
  WHERE n.language != b.language AND status = 1
  ORDER BY created DESC");

  $count = $results->rowCount();
  $results = $results->fetchAll();

  return array('node_ids' => $results, 'count' => $count);
}

/**
 * Load the nodes with the broken language bodies and fix them.
 */
function my_fixes_broken_bodies() {
  $brokenBodies = my_fixes_broken_body_nodes();
  $brokenBodyCnt = $brokenBodies['count'];
  $operations = array();
  $limit = 10;
  $nodesFixedPerOp = 100;
  $count = ceil($brokenBodyCnt / $limit);
  $opCount = ceil($brokenBodyCnt / $nodesFixedPerOp);

  // Give helpful information about how many nodes are being operated on.
  drupal_set_message(t('There are @brokenBodyCnt nodes to fix. And we are fixing @limit nodes per call. So the operation will require @count HTTP requests.', array('@brokenBodyCnt' => $brokenBodyCnt, '@limit' => $limit, '@count' => $count)));

  //Setup the operations for the fixes
  for ($i = 0; $i < $opCount; $i++) {
    $operations[] = array('my_fixes_broken_bodies_op', array(t('(Operation @operation)', array('@operation' => $i))));
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'my_fixes_finished',
    'title' => t('Fixing broken node body language settings.'),
    'init_message' => t('The broken body fix is starting...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('The broken body fix has encountered an error.'),
  );

  return $batch;
}

/**
 * Batch operation for fixing the broken bodies.
 */
function my_fixes_broken_bodies_op($operation_details, &$context) {
  // Process nodes by groups of 10
  $limit = 10;

  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $brokenBodies = my_fixes_broken_body_nodes();

    // Save node count for the termination message.
    $context['sandbox']['max'] = 100;
    $context['sandbox']['node_ids'] = $brokenBodies['node_ids'];
  }

  // Retrieve the next group of nids.
  for ($i = 0; $i < $limit; $i++) {
    $row = array_shift($context['sandbox']['node_ids']);
    $node = NULL;

    //Load the node
    if (isset($row->nid) && !empty($row->nid)) {
      $node = node_load($row->nid);
    }

    //Make sure it loaded alright and then run operations on it.
    if (!empty($node) && is_object($node)) {
      if (isset($node->body['en']) && !isset($node->body[$node->language])) {
        $node->body[$node->language] = $node->body['en'];
        $node->body['en'] = NULL;
        node_save($node);
      }

      $context['results'][] = $node->nid . ' : ' . check_plain($node->title) . ' ' . $operation_details;

      // Update our progress information.
      $context['sandbox']['progress']++;
      $context['sandbox']['current_node'] = $node->nid;
      $context['message'] = check_plain($node->title);
    }
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }

  _my_fixes_update_http_requests();
}


How can I disable all the JavaScript scripts?

You don't necessarily need to turn off aggregation if you want to remove all javascript. You could for example remove the placeholder in the html template, then the (already aggregated) javascript won't be replaced in the html page:
function mymodule_preprocess_html(&$variables) {
  if (MODULE_get_headers()) {
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts']);
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts_bottom']);
  }
  $variables['#cache']['contexts'][] = 'headers:my-header';
}

You need a cache context for the request header. This doesn't work for the Internal Page Cache, though. So you need to uninstall this module or extend it to add the request header to the cache key.


Changing exposed filter doesn't rebuild SQL query

After 4 hours of fight with exposed filter I found my problem. I used drupal administration in Opera. After moving to Chrome everything works great.


Restrict media files to other users once uploaded

If you have Groups on your site with grouped access permissions, I would recommend using the Group module for less complex group permissions like this and OG for configuring more involved group permissions.

Using the Group module you will be able to section off the media and other content like this.

EDIT:
I suggest you configure Group functionality / permissions directly on the File / media entity, rather than just the nodes they are added / used from. Failing that, I believe you will have to (clone and) override the view that the media entity browser uses and do some filtering based on group(s) of the media file author.

Then try using the user id of the author initially using static values to test your view. If the UI of the view does not provide what you are looking for, you might need to write your own Views Access Plugin. Here is one I wrote for Message Private module: InboxPermission.php. You could do similar.


It is simple javascript... The returned value can easilly be sent through ajax (there are good tutorials on sending mails with ajax).

<button onClick="alert(document.getElementsByTagName('body').innerHTML())" value="serialize">

You might run into trouble though, at first email clients can have trouble accessing images from remote locations (eg. from your own url). So you might have to attach them to the mail.

Also most email clients are very picky when it comes to css. They refuse to load a remote sytlesheet. You will have to hardcode all css classes in the respective elements, the old fashioned way... By using the object style attribute.

<body style="background: red; font-size: 9pt;">

So as you see it is harder then just sending the HTML to an email receipient. In fact you might want to have a look at HTML2Canvas (or other alternatives) to make a 'screenshot' of a webpage and just send one image.


Does "drush dl" allow to download a module from a site that is not drupal.org?

It looks like the source url for project downloads is context-specific - so you can set, for example, cli.source to something other than the default Drupal server, and Drush will look there for new releases.

I can't see anything in the code that would suggest that this can be done per-project though, just globally/per context (it's in [drush]/commands/pm/downloads.pm.inc if you're interested).

It is possible per-module using core functionality, i.e. adding this to your module's install file:

project status url

which:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

But it looks like Drush is expecting the remote server to provide data in Drupal's update XML format regardless of the source, so I don't think you'll be able to integrate this with Github without implementing some middleware.


How can I track stale content and alert content owners to it?

It's been awhile since you asked and I'm assuming you found an answer. For those who come across this post, the Rules module should handle this requirement.

Create a rule to react when content is viewed, which should suffice as a trigger.
Add a condition to run a data comparison on node modification date or write custom PHP comparison code.
Set the rule to send an email to the node's author.


I think you are using the word "parent" incorrectly.

The terms of a vocabulary can be sorted in a tree. And the parents of a specific term are the ones higher in that hierachy. So, if you want all parents of a term, of course you need so say, which term and give its id as $tid.

However, if you just want all terms of a taxonomy, you can use loadTree($vid) instead. $vid is the id of your vocabulary.

If you want to load all taxonomy terms, ignoring which vocabulary they belong to, then this is the best solution:

$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple();

Then, to access the term data do

foreach ($terms as $term) {
    $tid = $term->id();
    $vid = $term->getVocabularyId();
    $name = $term->getName();
}

If all you need is the ids of all the terms, this is enough:

$tids = \Drupal::entityQuery('taxonomy_term')->execute();


How do I compile Mustache.php to use with the Template Field module?

Open command line.
cd to your basedir/sites/all/libraries
mkdir mustache && cd mustache
git clone https://github.com/bobthecow/mustache.php.git

You now have /sites/all/libraries/mustache/mustache.php .

Mustache.php is actually the name of the folder, not an individual php file.

To get an earlier version, such as 1.0, try

Open command line.
cd to your basedir/sites/all/libraries
mkdir mustache && cd mustache
wget https://github.com/bobthecow/mustache.php/archive/v1.0.0.tar.gz
tar -zxvf v1.0.0.tar.gz
mv mustache.php-1.0.0 mustache.php


How to use entityQuery to select if a multiple value entityReference field does not contain the id

gapple put me on the right track (at least a solution for my specific problem), and its a combination of his two ideas.

I needed to query for all the nodes that reference my user, then query for all the entities that match my main query. that gives me two arrays of node ids, and if I array_diff the first from the 2nd, I end up with the array of node ids i want.

so, a separate entityQuery is needed, but its not too computationally expensive in my case, I think.

$my_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_shared_with_user.target_id', $user->id())
  ->execute();
$public_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_public_directory', true)
  ->execute();
$public_not_in_my_contacts = array_diff($public_contacts, $my_contacts);


1) Views PHP Filter is good to go when you have 'not that many' query results in total. The thing is that it loads node's object and it's not the best choice if you opt for better performance, but still it's okay for quick views filters creation.

2) Create new Computed field and store any flag (1/0 is quite enough) as its value. The flag itself will indicate if the field X has any content and then it can be used by Views for filtering.


cURL ist the perfect library for this. It's available on most PHP servers. Check this for an example.


How to get Node IDs of nodes whose titles contain a certain string?

You need iterate over the node collection, you can use this code to do so:

$sql = 'SELECT title FROM {node} WHERE title LIKE :title';
$result = db_query($sql, array(':title' => '%' . $term->name . '%'));

foreach($result as $node) {
    //dpm($node);
    //$node is your object
    echo $node->title . '<br>';
}

Edit: If you want only specifics content types use this:

$sql = "SELECT title FROM {node} WHERE title LIKE :title AND type = 'your_content_type'";


How do I use a custom theme in a module?

It is very easy. You just need use '#theme' element in your render array.

For example:

Drupal 7 has both way:

// Render array.
$build['cars_list'] = array(
  '#title' => t('Cars List'),
  '#theme' => 'item_list',
  '#items' => array('Mercedes', 'BMB'),
);
// Ready HTML.
$build['cars_list'] = theme('item_list', array('items' => array('Mercedes', 'BMB')));

Drupal 8 has only one way:

// Use render array.
$build['cars_list'] = [
  '#title' => t('Cars List'),
  '#theme' => 'item_list',
  '#items' => ['Mercedes', 'BMB'],
];

Actuality you may create a custom theme via hook_theme() and use it.


User View List in Drupal filter by taxonomy

You can accomplish this using the views module. Its the Drupal GUI way to build queries so you will be able to crate a page that lists all users based on the field you need.

Here goes a really good reference that may help you with that:

http://nodeone.se/en/taming-the-beast-learn-views-with-nodeone

If you prefer to get your hands dirty you can use the Entity Field Query


module_load_include loads file but also prints path to the file

module_load_include returns the file path not the html. However the reason you are seeing the html is due to module_load_include also doing a require_once. An easy way to fix this would be something like the following

function mymodule_page_build(&$page) {
  module_load_include('inc', 'mymodule', 'inc/markup');

  if (!path_is_admin(current_path())) {
    $page['page_top']['mymodule'] = array(
      '#type' => 'markup',
      '#weight' => 25,
      '#markup' => get_my_html(),
    );
  }
}

So now your #markup is a function call. Just make sure your html is wrapped in the function name you want and then use your function name in the #markup key.

Also, you function that contains the markup will be something like this.

function get_my_html() {
  $output = '';

  $output .= '

Here is some of my HTML OR ALL of my HTML';

  return $output;
}

Hope this helps!


Sort criteria in views: how to add custom one

First, make sure you have Drupal's Statistics module enabled and collecting page view statistics.

In Drupal 6, you need to enable Count content views under admin/reports/settings. This will count total node views and give you total day count. Unfortunately, it does not give you a weekly view count by default.

This will give you a sort criteria for Node statistics: Total views and Node statistics: Views today.

Upon closer inspection of the day count for node views, this value is reset to 0 every 24 hours by statistics_cron. This value would prove more useful as a sort criteria if it was the most recent 24 hour's node views. So, the Node statistics: Total views would be your best bet.

NOTE: See Statistics Granularity module for week, month and year.


Is it possible to hide the title of a block in a region to render it separately from the content?

It might be easier to do this in the block.tpl.php file (using $block->region to determine the region) as you have the title printed out separately from content there.

In your test environment you can also use stuff like these to get a better overview of complex variables (will help you with issues like this):

drupal_set_message('
'.var_export($content, TRUE).'
');

function print_r_html ($data) {
  ?>
<?php print_r($data); ?>
<?php
}


Site Branding Block not appearing in regular page--html--twig template

You can probably override the suggestions using hook_theme_suggestions_page_alter in your THEMENAME.theme file

function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //the routes to use the specified template
  $use_template = [
    "user.register", // user/register
    "user.login", // user/login
    "user.pass", // user/password
    "entity.contact_form.canonical", // core contact form (website feedback)
    "entity.webform.canonical", // all webforms will have this route
  ];

  // what route are we on ?
  $route_name = \Drupal::routeMatch()->getRouteName();

  if (in_array($route_name, $use_template) ){
    $suggestions[] = 'full__width__page';
  }
}

You should clear the cache and your specific template should take control.

If you have twig debugging enabled and your browser has show html comments enabled you should see something similar to this the page source

<!-- FILE NAME SUGGESTIONS:
   X full--width--page.html.twig
   * page--user--register.html.twig
   * page--user.html.twig
   * page.html.twig
-->

With x indicating the twig template responsible for the particular output.  In this case full--width--page.html.twig is the twig template used.


Views Template for first Block being applied to all

Simply changing the machine name setting on the display allows me to make it what I want, so I gave it the machine name block_0 and now I can make a designated template for it.


Debugging help- rules are getting fired multiple times (recursively) when they should not be

The problem was with the components.  It turns out that the "Activate Friends" rule component only had a heartbeat "Log Activity" action, which was the source of the problem.


Create a new view of type content

Then add contextual filter "Content: Nid". Here you can add different settings depending on your needs.

Under "Relationships" you should be able to select the entity reference field. This brings in all information about the referenced properties.

As fields you can now add any field from the references properties - just add this relationship


Can PhpStorm autocomplete methods in Drupal::service?

The auto-complete suggestions are based on the type of return value documented in the \Drupal::service() doxygen comment. Since the method may return service of any kind the type of return value is mixed.

That means auto-complete is not possible unless you explicitly specify type of the service.

/** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
$config_factory = \Drupal::service('config.factory');

For some particular services you can use dedicated  methods like \Drupal::configFactory() or \Drupal::config() which have properly documented return value.

Notice that generally dependency injection is more preferable method for accessing services.


Plans for a D7 version of the Spam module, and possible alternatives?

I think you were looking for an antispam module, weren't you? Try Mollom.

It kills comment, contact form and registration form spam, has image and audio CAPTCHA service.

Try it, it is made by Drupal core developers.


How to resize  element within drupal block?

Is that everything that's in your block? I've tried to replicate this and it works fine for me.

Have you tried setting your CSS in the appropriate css file instead of adding it inline? Like:

#block-id-title img {
   height: 100px;
   width: 100px;
}

Or, try inspecting that img element in firebug or equivalent, and see how the css is being rendered. You might have a css styling set for all img tags which is unintentionally overriding your block image.


Programmatically check if a D8 version exists for all site modules

For non programmatical way.

Download and install the Upgrade Status Module


Limit total quantity of products across user's entire order history

Use hook_form_commerce_cart_add_to_cart_form_alter()

<?php
mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id)
{
  /*code*/
}
?>

Then, inside the hook, use entityFieldQuery to get list of orders for this user

For locating the "currently selected product," you can use the form_state variable:

<?php
$current_product = $form_state['default_product'];
?>

Finally, you'll want to iterate over each order and use entity meta data wrappers to wrap the orders so you can iterate over the line items, looking for matching products.

<?php
foreach ($orders as $order_id => $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
  }
}
?>

The final final round would include looking to see if the line item is attached to the product and then counting the number of products this person has purchased.

Unfortunately, while you might be able to construct an SQL statement that does most of the heavy lifting (instead of iterating over all the user's orders and line items), it would require much more intimate knowledge of your particular store architecture.


Why does my Rules Action about booking a time slot appear to not be executed?

I'm about sure that the answer to your question can be found here.
And to be 100%, I recommend you do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".

Update

Your (1st) comment confirms what I wrote in my answer even more. Have a look at the source code and let me know where I can find more details about any of those "Various events" that you try to use are actually coded. I trust they are somewhere (since your question says you use them), but with my limited knowledge of Rules (hm, hm) I cannot find them ... in the typical ".inc* file where the Rules module expect them to be located. But since "I" cannot find them, it may well be that that also explains why the Rules module cannot find them ...


You can set the alias by editing a content. See the screenshot below to edit url alias.


You can create a view to display a single node. You can determine which node to display by using a contextual filter. For instance, you can pass the node ID to the view, in order to get it displayed.

There are many tutorials explaining how to use contextual filters with views. A possible starting point might be the following: https://www.drupal.org/node/1578558


Images are not migrated and the body field is empty

The solution for the body-field:

it must be a translation problem. I changed the language of the Drupal 8.1 site to the same language as the Drupal 7 site and now the body field isn't empty anymore.

But the images are still missing. I noticed that no files were imported. Under /admin/content/files there is nothing! any help in this case?


How to properly alter response from Solr Search Module

The problem was this one:

function zen_search_api_solr_search_results_alter(array &$results, SearchApiQueryInterface $query, Apache_Solr_Response $response){
  ...
}

It should be this:

function zen_search_api_solr_search_results_alter(&$results, $query, $response){
  ...
}


Is it possible to show views exposed filters in the facet current search block?

This wouldn't add it into the Facet block, but you could just do the exposed filters in a block and put the exposed filters block near the Facet block (screenshot from the Advanced section of the View):


Access denied to login to original node id

Login Destination claims to do what you need:

  It is also possible to keep users on the currently visited page after logging in or out.


How to do multiple file uploads from a block's form?

I think the '#cardinality' it's not a form attribute, I couldn't find on the docs.

But I could find it on the field_multiple_value_form().

I suggest you to take another approach and use the AJAX framework, I found a couple of guides (guide_1 and guide_2) that might be helpful.


Hook_Form_Alter Edit Existing Field Type

hook_form_alter work only with module implementation. So you have to use it in any module not in template.php

Use the above statement in module like

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

  if($form_id == "views_exposed_form"){
    $form['data_2'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}


can't save search box configuration under themes>config

I had the same problem - answer: Search module is not enabled by default! So

go to admin/build/modules, scroll down to 'Search' and tick the checkbox.
Then go to admin/user/permissions, scroll down to 'Search module' and set permissions for Anonymous and authenticated user (and any other type of users you might have configured and want to give this permission to).
Finally, go over to admin/build/themes/settings/[your-theme-name] where you will find that the 'Search box' checkbox is now tickable.

You should now see the search box - if you don't , flush caches!


Setting up drush ini path in my site alias

Drush processes drush.ini in the drush bash script prior to calling drush.php.  Here is the relevant code it uses:

for conf_dir in $(dirname "$SELF_PATH") /etc/drush $HOME/.drush ; do
  if [ -f $conf_dir/php.ini ] ; then
    drush_php_ini=$conf_dir/php.ini
  fi
  if [ -f $conf_dir/drush.ini ] ; then
    drush_php_override=$conf_dir/drush.ini
  fi
done

You will need to make sure that your drush.ini file is in one of those location in order for it to be found and processed.  Note that the drush bash script never acts on command line parameters; those are parsed in php.  There are some environment variables that affect the drush bash script, but there are no environment variables that affect the selection of drush.ini, and there is no facility in site aliases to pass environment variable values to drush on the remote machine.

Sorry.

Edit: You could try setting %drush-script in your alias file to point to a script on the remote machine that called php /path/to/drush/drush.php.  Read the advice in the README.txt for Drush-4 on how to make an alias to drush.php if you do this; you will want to make sure that --php is passed to Drush correctly, etc.


Enable the "Token" view mode and select "Key" as field formatter for the "Series" field.


How do I validate form elements via onblur events?

Drupal doesn't have any client-side validation by default, but you can get that functionality with the Clientside Validation module:

  This module adds clientside validation (aka "Ajax form validation") for all forms and webforms using jquery.validate.

According to the docs it has a "Validate on blur" option, so it should be just what you're looking for.


How to redirect the checkout complete page?

In this payment structure with local payment gateway, I have to pass product item lists, return url and cancel url to local payment gateway through drupal commerce’s Local Payment Module. If detail information of this payment is returned, in that page I redirect to the this link http://localhost/checkoutComplete/completeCheckout .

Checkout_complete.admin.inc

function checkout_complete_loadAllrecord()
{
    //current orderId
    $paraorder = variable_get("order", "");
    $order = commerce_order_status_update($paraorder, 'checkout_complete');

    //assign order status to checkout_complete
    $order->status = "checkout_complete";

   //calling this method order status will be changed to "Checkout_complete", this method will fire commerce_checkout_rule()
   //In commerce_checkout_rule(), we can send email to client to notify checkout is complete.
    commerce_checkout_complete($order);

    //redirect to order completed page
    drupal_goto(commerce_checkout_order_uri($order));

}

Thanks


Is there a way to display some content fields in a separate block?

You could create a view which selects the field you want from a node. Use contextual filters to get the Node Id in your view.


Yes, you can install the ThemeKey module. One of its features is to provide:

  content, user, or role -specific themes

So you can upload a new theme and try it out for certain users roles, without affecting what how the site looks for regular users.


Core blog module only shows two blog entries?

Can you reproduce this behavior using your module set, but with fresh install and blog posts entered manually / generated with devel generate? If not, it's migration failure and your best bet is to export content from old site (you have backup, don't you) and import it to the new one, without Drupal's built in migration tool.

If this happen with fresh setup too, try changing theme to one of the supplied core themes. If it works, then, it means you have a bug in your templates. If it's not, I need to get more info to further expand my answer.


Redirect to external url adds external url to current url instead

You need whole URL like http(s)://www.example.com


Any instance of a Webform is a node so each anonymous user get his own submissionreference. So e.g the name of the form is harrypotter the user is getting harrypotter/1
Where 1 is the submission nr.

In rules you are able to get the submission id, get the content and redirect to the form again.

However you have to protect it again other users. Therefore you can use another Web form in front of it which ask for a pincode. You can redirect the user with the help of the pincode and rules to the correct submissionid


How To Set Node Path/Alias Programatically

The canonical URL for a node is http://example.com/node/<nid>; if you want to set a path alias, you need to set it with path_set_alias('node/' . $node->nid, $alias).


Telephone and Email are field which looks like textfield but actually are not of type textfield. Instead, they are of field type telephone and email respectively, which was introduced when Drupal 8 was released.

In order to show field title and field input in same line use below steps,

Edit the individual field.
Go to form display setting and open the title display dropdown.
Select Inline option.


Views provided by a module are defined using hook_views_default_views - and as almost anything, they can be modified using "alter" version of this hook, namely hook_views_default_views_alter:
Alter default views defined by other modules.

This hook is called right before all default views are cached to the database. It takes a keyed array of views by reference.
Example usage to add a field to a view:

$handler =& $view->display['DISPLAY_ID']->handler;
// Add the user name field to the view.
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;

Source code from API help page linked above.


Improve D8 performance to access a custom REST controller

Given I did not have many responses, I answer myself to share the bits of explanation and solution I found.

Below the performance loss sources I've identified :

The use of D8 full bootstrap, including modules loading, routes resolving, etc.
Reading and parsing a YAML config file each time the module handles a request

And the solutions I applied :

Custom D8 minimal bootstrap

Based on this post and the default D8 index.php, I created a custom Bootstrap in my proxy module :

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\my_module\Controller\ProxyController;

chdir( $_SERVER['DOCUMENT_ROOT'] );

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$response = ProxyController::create( $container )->index( $request );
$response->send();

$kernel->terminate($request, $response);

Like it was made in the D7 version, I redirected all request with the /service prefix to this file.

PHP config instead of YAML

I didn't find a way to load and parse the YAML config file once and cache the result.
(I'm still interested if someone know how to do that by the way)

So i converted the config file content myself into PHP, put it into a .php file and
use include instead of file_get_contents() and Yaml::decode().

Result

You can see here the response time obtained combining the 2 solutions above.

I assume the remaining perf loss is due to the use of OOP instead of procedural PHP. But if I want to stick to the D8 standards, I can't do much about it...


Drupal 7 - Entitiy Reference - Reference field to a conent as a link

On the Manage Display page (Structure->Content Types->Your content), first be sure the display format is set to Label. Then, click on the gear on the right. You will see a checkbox with "Link label to the referenced entity". Check that and click Update, then save our display. The label will now link to the entity.


Depending on the argument passed in url go to specific content type

Use hook_menu in custom module to achieve this using below code !
Change the links of Add Details to "goto/video" means full url will be localhost/drupal/goto/video

function yourmodule_menu() {
    $menus['goto/%'] = array(
        'title' => 'Just Redirect',
        'page callback' => 'drupal_redirect_to_content_type',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $menus;
}

function drupal_redirect_to_content_type($type) {
  drupal_goto("admin/structure/types/manage/" . $type);
}

Otherwise,

Instead of above what you can do it directly give Add Details link to admin/structure/types/manage/ . $type instead of drupal/$type


hook_ENTITY_TYPE_insert never gets called

You probably need to add a field to the user entity, which matches your form field key. Or, save the data in the session ..


Does turning on CSS aggregation make your CSS work in IE?

If so, you may be coming up against the 31 CSS file limit in Internet Explorer.

Someone has made a module that deals with this - IE Unlimited CSS Loader.


To answer my own question below is the correct js file that is working.

(attach:function ($) {Drupal.behaviors.my_module = {function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
            dataType:'json',
        });
        return false;
    });

}};})(jQuery);


How to link the title in a teaser to the main content?

If you are using a node title field, then the "Link this field to its entity" option should definitely work.

By default it will link to

localhost:8082/node/123

where 123 is the node ID of the node.

If you want a nicer URL, like

localhost:8082/title

where title is the title of the node (or something similar), try the pathauto module, which allows you to define settings that automatically create pretty urls for nodes (and users and taxonomy terms, etc.).
The pretty urls can use tokens, like [node:title], which will be replaced by the title of the node for example.


Detailed breakdown of what takes Drupal so long?

You need the xhprof extension and module.


How I do configure the BigBlueButton module?

I have resolved the problem following these steps.

Install the module
On the module settings page (admin/settings/bigbluebutton), put values for Server base URL and Security salt key, and save the settings
Create a new content type, for example Conference
On the content type setting panel (for the Big Blue Button module),
select Treat this node type as meeting and Display meeting status on node, and save the settings
Create a new Conference node and go to meeting


Auto Increment - Order/user numbers not changing

The users table does not work with AUTO INCREMENT in Drupal 7.
Instead, the ids are generated in PHP.

See What could cause uids to not be numbered consecutively?


How To resolve Broken/Missing Handler with Independent views query backend flag links patch?

Try disabling views cache. I believe it should remove broken/missing handler.


User profiles are fieldable in Drupal 7, you can add a taxonomy field already, with nothing but core. You don't need Entity Reference or any other modules, you can simply  add field_taxonomy to your user. Sure, it is a bit opposite to "add users to terms" you described, but later, if you need it for Views etc, it doesn't matter which way it was created - there is a connection between user and term, and you can use it.


use taxonomy terms as values for radio buttons by code

#options

values must be in array: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options

example:

'#options' => array(
            0 => t('None'),
            1 => t('Team'),
            2 => t('Business'),
            3 => t('Talent'),
        ),


How can I output aliases in a print function, so I can render links using aliases instead of nid?

You should use the l() function:

  Formats an internal or external URL link as an HTML anchor tag.

  This function correctly handles aliased paths and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.

So:

<?php print l('Link text',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')))); ?>

You have to supply classes and any other attributes to the l() function.

Note that the first l() parameter (the 'Link text') can be HTML. For this you have to pass in the options array an element HTML set to TRUE. The above example can be:

<?php print l('Some text',
              'node/' . $row->nid,
               array(
                 'attributes' => array(
                   'class' => array(
                     'w-inline-block',
                     'portfolio-photo',
                     'portfolio-1')
                   )
                 'html' => TRUE,
                 )
             ); ?>

Also, as noted by the documentation fragmento above, the l() functions handles the aliases. This is because internally drupal_get_path_alias() function is used.


With help from "Ambidex" on Drupal Slack, I post here the complete plugin-file.

I could not find an example for this use case, and I believe it might benefit others:

file: [drupalroot]/modules/custom/ourcustomername_tweaks/src/Plugin/Block
/ContactBlock.php

.

<?php

namespace Drupal\ourcustomername_tweaks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

/**
 * Provides a 'Contact' Block.
 *
 * @Block(
 *   id = "contact_block",
 *   admin_label = @Translation("Image Contact block"),
 * )
 */
class ContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [

        'image' => [
          'value' => ''
        ],

        'label_display' => FALSE,
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];

    if (  isset($this->configuration['image']) && !empty( $this->configuration['image'] )  ) {

      $image_field = $this->configuration['image'];
      $image_uri = File::load($image_field[0]);

      $build['image'] = [
        '#theme' => 'image_style',
        '#style_name' => 'ourcustomername',
        '#uri' => $image_uri->uri->value
      ];
    } else {
      $build['image']['#markup'] = '['.t('Picture').']';
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form['image'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/',
      '#title' => $this->t('Image'),
      '#description' => t("Image to show on the contact form"),
      '#default_value' => $this->configuration['image'],
      '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_size' => array(25600000),
      ),
      '#states'        => array(
        'visible'      => array(
          ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
        )
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}


Display a flag link in views based on whether the node has an associated taxonomy term

You could achieve this easily using views without using views php field. More specifically you can create a view of content with an EVA (entity views attach) field display where you will add the flag link field and attach it to the nodes of that content type. Just make sure to:

Add a contextual filter of Content:Nid
Add a relationship of "Content:Taxonomy terms on node"
Also add a "Flags: Node flag" relationship (uncheck the include flagged content only checkbox)
Add a filter "Content type:...your content type which nodes will have the flag link
Add a filter "Taxonomy term: Term ID" that will equal to the tid of the "fruit" term.

After that you can easily choose how to display this eva field on your nodes using Display suite.


Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess

I finally found out that my question had an answer in this thread.

So I went back to Boost version 1.0, generated the htaccess code, pasted it in my .htaccess file and then updated to version 1.1 again (without changing the .htaccess file). Now everything seem to work fine.


How to assign roles in my own registration form

function company_form()
    {
         $form['company_username'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-username',
          '#default_value' => '',
              '#required'=>'true'
      );
          $form['company_email'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-email',
              '#required'=>'true',
          '#default_value' => '',
          '#element_validate' => array('generate_special_form_validate'),
      );
           $form['company_password'] =  array(
          '#type' => 'textfield',
          '#title' => 'company-password',
               '#required'=>'true',
          '#default_value' => ''
      );

      $form['submit'] =  array(
          '#type' => 'submit',
          '#title' => '',
          '#value' => 'Submit',
          '#default_value' => ''
      );
      return $form;
    }
    function company_form__validate(&$form_state,$form) {

         if (!valid_email_address($form['input']['email'])) {
         form_set_error($form['input']['email'],'Please enter a valid email address.');
       }
    }
    function company_form_submit($form, &$form_state)
    {

     global $user;
        $company_username = $form_state['input']['company_username'];
        $company_email = $form_state['input']['company_email'];
        $company_password = $form_state['input']['company_password'];
         $fields = array(
              'name' => $company_username,
              'pass' =>$company_password,
              'mail' => $company_email,
              'init' => $company_email,
              'status' => 1,
              'access' => REQUEST_TIME,
              'roles' => array(
               4 => 'company',
                ),

        );
        $account=user_save('', $fields);

    if($account->uid)
    {
     drupal_set_message('User Created SuccessFully');
    }

}

Firstly you have to create roles from backend.
and then You can Assign as many roles by passing role id and role name in array.

'roles' => array(
               4 => 'company',
                ),

Hope this code helps you.


Commerce Shipping - arbitrary calculations

I found a module that does exactly what I want: Commerce Shipping Weight Tariff.
I set up three services, one for each destination, and used rules based on the shipping address to work out which service to use. Then I added the weight tariffs for each service.


This problem is probably related to the text format used when the page containing the image is rendered.

If the text format used is "Filtered HTML", you should try to change the format for the node to "Full HTML".  If this change makes the missing images re-appear, the problem is the text format.

If only trusted users are allowed to insert images in nodes, you can fix the problem by changing the default text format from "Filtered HTML" to "Full HTML".  However, it is not recommended to allow untrusted users use this text format, as it allows XSS attacks.

For a secure configuration where untrusted users can insert images, you need to use a better filter module that the default "Filtered HTML".  You can do this by installing the WYSIWYG Filter module as is decribed here.


Form incorrectly displays differently depending on logged in user's role

Your code isn't manipulating the select field's options ($form['field_topic']['#options']), so the difference in options is something outside your code (you can confirm this by commenting out your form manipulation code).

If this is the case, you'll have to investigate why non-admin auth users are seeing empty options; it seems like it would have something to do with user permissions on your taxonomy, field, or something else that would prevent auth users from querying the valid terms for your taxonomy field.


After reading question again I was way off. I am not sure if there is an easy cut and dry way to do this but I did find a workaround with hook_preprocess_webform_element. The code is pretty rough but should point the way to suit your needs.

Example:

function MY_MODULE_preprocess_webform_element(&$variables) {
 $icons = array(
  'fa-adn' => '&#xf170;',
  'fa-align-right' => '&#xf209;',
 );
 if (isset($variables['element']['#attributes']['placeholder']) && array_search($variables['element']['#attributes']['placeholder'], array_keys($icons)) !== FALSE) {
  $icon = $variables['element']['#attributes']['placeholder'];
  $search_string = implode('|', array_keys($icons));
  $variables['element']['#children'] = preg_replace('/^(<input .*placeholder=")(' . $search_string . ')(".*\/>)$/', '$1' . $icons[$icon] . '$3', $variables['element']['#children']);
 }
}

This will allow the editor to put the fa icon name in the placeholder text field on the edit form.

You can find the codes for the fa icons here.

EDIT: I forgot to add that you would have to change the font-family for the element and then remove it when the placeholder disappears if you are not using FA for your sites font.

Edit2: Per comment you can add a wrapper class to the textfield when editing the component then use CSS to have an icon permanently in front of the textfield.

.textfield-wrapper::before {
  position: relative;
  font-family: FontAwesome;
  margin-left: 5px;
  content: '\f061';
 }

Note: If you want the icon 'inside' the text field you can add the appropriate top, left positioning and z-index to this CSS.


Register a new namespace for autodiscovery

The autoload is still done using Composer. To add an extra namespace you'll have to run a composer command to rebuild the autoload file.

See https://stackoverflow.com/a/31505011/113057 for how to add a namespace to composer.

The key is in composer dump-autoload


If you really want to prevent the URLs from existing at all, you could probably unset the paths using a hook_menu_alter. I would be careful with that though, as it might have unforseen consequences. The creating module may in some way depend on the paths existance.

I don't know where the category paths comes from but I guess the answer will be the same as for the taxonomy ones.

My solution would be to take over the URL with Page manager, and simply pass the user a redirect to the front page. (Or a 404, if you prefer).
Note that I'm talking about "Page manager" in Ctools, not Panels. The two modules are often confused and their names interchanged.


Your current configuration is doing the SUM of all numbers in that field but per views row, so you'd see numbers added up within each node if you had a multivalue field.

To make it sum up across all results/nodes you need to remove the Sort criteria, that can throw aggregation off.

I don't think your second question is making sense, you want to make a reference to a value calculated within views?

Entityreference creates a list of entities, and the summed up value is not an entity, you can't reference it like that. You can create a Views block and show the summed up value on some content pages and wherever you need it. Is that what you're after?


if you don't want to change the structure of your url.

you can use Explode function

I have made a helper function try it out:

function getParamsOfUrlWithSameKey(){
  $current_uri = \Drupal::request()->getRequestUri();
  $items = explode('?', $current_uri);
  $res_param = [];
  if (isset($items[1])) {
    $params = explode('&', $items[1]);
    foreach ($params as $param) {
      $param_value = explode('=', $param);
      $key = $param_value[0];
      $value = $param_value[1];
      $res_param[$key][] = $value;
    }
  }
  return $res_param;
}

The return of this function will be something like:

array:1 [▼
   "filter-value" => array:2 [▼
     0 => "67"
     1 => "80"
   ]
 ]


How to sort a view so that, say, all the nodes with stock=0 come last, and not sort by stock?

You could do this if you use something like the Views php module, because that will allow you to use php code to sort by.  I know that module is currently looking for additional maintainers, I just can't think of an alternative.

Once you've enabled it, and added a php field to sort by, I'd have it return something like:

min([commerce_stock], 1);  // replace [commerce_stock] with whatever your available stock variable is.

What that code will do is return 1 (the minimum) if you have any stock more than 1, but it will return 0 if the product is all out.

So it will only return 1 (there are items) or 0 (there are none), which is exactly what you want.  Next, you can add a sort by name or whatever you want to sort these two groups further.

Let us know if it works.  I was having a bit of problems getting this rolling, since my stock variable is just returning my product ID, and I'm not sure if I'm just running slightly out-of-date modules or what.  So let us know if a similar approach works when you try it!!


How to properly add anchor to form element

Take a look at the form apis prefix and suffix attributes these will allow you to wrap html around your form element.


I can see the image slideshows in full width for 1 sec but then images
  go back to original sizes.

sounds like there is another css that is loaded after that is causing them to shrink. (perhaps it's in the views slide show css file). To prevent anything that is loaded after from overriding your css try adding the !important tag

so try this:

.views-slideshow-cycle-main-frame-row-item .field-content img {
    min-height: 500px !important;
    width: 100% !important;
}


Breadcrumb trail not displaying correctly in custom module

After making a completely unrelated change to my hook_menu, the breadcrumb fixed itself.  I don't know why though.


How to know when to use $config or $settings overrides in settings.php?

From settings.php, regarding $settings:

Settings:
$settings contains environment-specific configuration, such as the files
directory and reverse proxy address, and temporary configuration, such as
security overrides.
@see \Drupal\Core\Site\Settings::get()

From settings.php regarding $config:

Configuration overrides.
To globally override specific configuration values for this site,
set them here. You usually don't need to use this feature. This is
useful in a configuration file for a vhost or directory, rather than
the default settings.php.
Note that any values you provide in these variable overrides will not be
viewable from the Drupal administration interface. The administration
interface displays the values stored in configuration so that you can stage
changes to other environments that don't have the overrides.
There are particular configuration values that are risky to override. For
example, overriding the list of installed modules in 'core.extension' is not
supported as module install or uninstall has not occurred. Other examples
include field storage configuration, because it has effects on database
structure, and 'core.menu.static_menu_link_overrides' since this is cached in
a way that is not config override aware. Also, note that changing
configuration values in settings.php will not fire any of the configuration
change events.


how to display related node titles to taxonomy terms

The solution will be to use a taxonomy view using the views module and in the view add a relationship the content type where the terms are use. To finish you can display the results as an HTML list grouping by the parent term.


howto set a category for a webform/entityform question ...?

You can do this with the Webform Entity module. It uses Webform to create the forms but the content that is created is a full-fledged entity instead of just a serialized array in the database. That means full Views support etc.

For a category you can use a field list in the webform which can become a taxonomy field or field list in the entity that can be used as an exposed filter in Views.

To set this up just go to "admin/config/content/webform/entities/webform/" and click "Create" to create an entity webform

Then add fields to the entity:

Now, when you create a webform, the fields from the webform entity will appear on your node:

Finally, in Views, create a new view with the webform subsmissions as a base table:

and the fields attached to webforms can be used as exposed filters, fields and all other things views:


How to order multiple values in a field collection

You can order the Items when you are creating it using the widget that is next to the field. I mean this (It is a field collection that contains multiple fields)

and if you need to sort the items after adding the content, you can use  Field Collection views module. This module creates a view of type field collection and by some configurations you can get what you want.


How to load block on link click with AJAX framework?

Looks like your missing the ajax_deliver command

$commands[] = ajax_command_html('.region-content', some_func());
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);


Why do I get the "Maximum function nesting level of 100 reached" error?

It is probably caused by xdebug. Increase nesting level in php.ini

xdebug.max_nesting_level = 200


You can use drupal_mail() together with hook_mail() to send email.

See also the Examples for Developers.


How to find the user avatar filename in Drupal 7

Check the table "users", column "picture". Join that on the fid from the file_managed table.


On the user edit page, how can I show the "Help text" for my fields after the "Label" and before the selection widget?

Install the theme developer module and point to your widget. It will tell you which hooks and templates are rendering it and what functions/templates you can use to override this functionality.

Often I find myself first copying the default code to the custom function/template and then twicking it to my needs.


How do I change html structure of menu (primary links for example) to my own?

I am assuming you are working with drupal6 and you have basic understanding of variables and arrays. Default html structure of the primary links is formed at different places in drupal. First if you start with the wrapping div id, in your theme's page.tpl.php file where you print $primary_links change it as the following example:

 <?php print theme('links', $primary_links, array('class' => 'links primary-links dk_two')) ?>

In order to change what is in $primary_links use the following code in template.php file of your theme.

    function yourThemeName_links($links, $attributes = array('class' => 'links')) {
  $output = '';

  if (count($links) > 0) {
    $output = '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = $key;

      // Automatically add a class to each link and also to each LI
      if (isset($link['attributes']) && isset($link['attributes']['class'])) {
        $link['attributes']['class'] .= 'dk_three ' . $key;
      }
      else {
        $link['attributes']['class'] = $key;
      }

      // Add first and last classes to the list of links to help out themers.
      $extra_class = '';
      if ($i == 1) {
        $extra_class .= 'first dk_four ';
      }
      if ($i == $num_links) {
        $extra_class .= 'last dk_five ';
      }
      $output .= '
 $extra_class . $class)) . '>';

      // Is the title HTML?
      $html = isset($link['html']) && $link['html'];

      // Initialize fragment and query variables.
      $link['query'] = isset($link['query']) ? $link['query'] : NULL;
      $link['fragment'] = isset($link['fragment']) ? $link['fragment'] : NULL;

      if (isset($link['href'])) {
        $output .= l($link['title'], $link['href'], $link['attributes'], $link['query'], $link['fragment'], FALSE, $html);
      }
      else if ($link['title']) {
        //Some links are actually not links, but we wrap these in  for adding title and class attributes
        if (!$html) {
          $link['title'] = check_plain($link['title']);
        }
        $output .= '' . $link['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Clear your cache and you will see dk_one dk_two dk_four dk_five  div ids and classes in your html structure of your primary menu. Please let me know if it works for you.


How can I create a View to give me a list of nodes that share a nodereference with the User's profile?

did something similar using panels and view panes. Without panels I'm not sure how I would approach it. You can create a view that lists all the content nodes. then create a display of that view that is a "content pane" (requires panels). Go into advanced, and create a "contextual filter" based on the criteria you want (in your case it would be your node reference to the company). Then click "argument input" under pane settings. you should now be able to add this pane to a panel and pass it the correct argument. I know it's a little confusing written out .... but with this setup you could for instance make a panel that shows the user, the users company, and a list of the content nodes owned by that company.

I've posted this a couple times here, only because it really helped me understand contextual filters and how you can build some pretty awesome things just using them with views and panels

http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics


I usually define my modules functions in a separate .inc file, and when i need them somewhere (usually sub-modules) i first include them with module_load_include( file-extension, module-name, file-path)

You can add the module_load_include() call at top of your snippet, or, if you need those function in many other places in your module hook_init() and make it avaible to every page.


form error Fatal error: Cannot use string offset as an array

The problem is here:

if(isset($zinfo['values'])){
    $form['page_output'] = array(
    'markup' => 'Submitted value:'. $zinfo['values']['state']);
}

Any element of a render-array that doesn't start with a # symbol is itself considered a child render-array by the drupal_render() function.

As drupal_render() expects an array when your array key is markup (without the #), it tries to treat the variable as an array. Since it's a string, PHP complains that it can't use the provided variable as an array...because it isn't one :)

This should work:

if(isset($zinfo['values'])){
    $form['page_output'] = array(
    '#markup' => 'Submitted value:'. $zinfo['values']['state']);
}

Have a look at Render Arrays in Drupal 7 and the FAPI #markup property for more information.

EDIT

There's a slightly bigger problem: in zillow_api_info() you're accepting the $zinfo parameter by reference, and then overwriting it with this call: $zinfo = simplexml_load_string($xml);.

That code overwrites the $zinfo variable in memory, so when you use it again in your submission function it will cause errors. It's also what's causing the last two lines not to work, and $zinfo['values'] to not exist when your form is rebuilt.

The easiest solution is to change zillow_api_info() to look like this:

function zillow_api_info($form, &$form_state){
  set_time_limit(3600);
  $state = $form_state['values']['state'];
  $zillow_id = 'XXXXX';
  $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&state='.$state.'');
  $zinfo2 = simplexml_load_string($xml);

  foreach($zinfo2->response as $rates){
    $zinfo2 .= $rates->today->rate[0];
    $zinfo2 .= $rates->today->rate[1];
    $zinfo2 .= $rates->today->rate[2];
    $zinfo2 .= $rates->lastWeek->rate[0];
    $zinfo2 .= $rates->lastWeek->rate[1];
    $zinfo2 .= $rates->lastWeek->rate[2];
  }

  return $zinfo2;
}

As an extra note, you do need $zinfo['rebuild'] = TRUE in your submit function too.

I'd really advise using the $form_state variable name throughout your code when it refers to the form state array, it'll make problems like this vanish instantly :)


Trying to use variable to pass a view argument/parameter

the first you install module Twig Tweak

In file yourtheme.theme

/**
 * Implements hook_preprocess_HOOK()
 */
function yourtheme_preprocess_node(&$variables) {
  $terms=[];
  foreach($variables['node']->field_tags->getValue() as $term){
    $terms[] = $term['target_id'];
  }
  $variables['node_terms'] = implode(',',$terms);
}

In file node.html.twig

{{ drupal_view('custom_view','article_block',node_terms) }}

Config Views CONTEXTUAL FILTERS in your views


View block with contextual filter on taxonomy term name in URL doesn't work

Your contextual filter will be expecting the term ID rather than the term name. You'll need remove that contextual filter and then add a relationship to the taxonomy which will then allow you to add a contextual filter for the taxonomy term name rather than the term ID


Content Moderation: Editorial workflow not installed and broken/missing handler on the moderated content view

The guys over at Drupal's Slack channel pointed me in the right direction. I added detailed troubleshooting infos to the Content Moderation Guide.

If you enable Content Moderation (drush en content_moderation) on a site, that was not installed using Drupal's Standard Profile as a base, you will run into some problems which require a few manual steps before you can use Content Moderation, as detailed in the guide.

Fix missing Editorial workflow

If the Editorial workflow was not created when enabling Content Moderation, you can either manually create a new workflow and assign a content type, that's used with your new workflow or import the Editorial workflow manually.

The template for the Editorial Workflow is:

langcode: en
status: true
dependencies:
  module:
    - content_moderation
id: editorial
label: Editorial
type: content_moderation
type_settings:
  states:
    archived:
      label: Archived
      weight: 5
      published: false
      default_revision: true
    draft:
      label: Draft
      published: false
      default_revision: false
      weight: -5
    published:
      label: Published
      published: true
      default_revision: true
      weight: 0
  transitions:
    archive:
      label: Archive
      from:
        - published
      to: archived
      weight: 2
    archived_draft:
      label: 'Restore to Draft'
      from:
        - archived
      to: draft
      weight: 3
    archived_published:
      label: Restore
      from:
        - archived
      to: published
      weight: 4
    create_new_draft:
      label: 'Create New Draft'
      to: draft
      weight: 0
      from:
        - draft
        - published
    publish:
      label: Publish
      to: published
      weight: 1
      from:
        - draft
        - published
  entity_types:
    node: null
  default_moderation_state: draft

Copy the template to some yml file and import it using drush config:import --partial.

Fix Broken/missing handler on the Moderated Content view

This error occurs, if there exists no moderation workflow that is assigned to a content type. Wether you just imported the Editorial workflow as described above or created a custom moderation workflow, you'll have to make sure it has at least one content-type assigned to it. Just edit your moderation workflow, scroll to the bottom of the page and select at least one content type that is used with this workflow. After you save your changes, the "Broken/missing handler" on the Moderated Content will be gone and the view at /admin/content/moderated will work as expected.


Template suggestions for file_entity.tpl.php

There's a documentation about template suggestions at Displaying Media under the heading Further Theming.

  The theme suggestions provided by the File Entity module are:

file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}


Using jQuery to communicate to Drupal 7 via AJAX

I am assuming you'd like to display some data when you're moving the slider around.

The way I do it is without using the '#ajax' attribute.

Implement the AJAX call, send the slider value as POST variable to '/foo/ajax':

    jQuery('#slider').slider({
            // Define your slider (min, max etc)
            ...
            // Add event handler
            change: function(event, ui) {
                jQuery.ajax({
                    type: 'POST',
                    url: '/foo/ajax',
                    dataType: 'json',
                    success: ajaxCompleted,
                    // Might want to use 'ui' instead of jQuery('#slider').
                    data: 'slider_value=' + jQuery('#slider').slider('values', 0);
                });
            }
    });

Make a menu item that's called when the slider moves around:

function foo_menu() {
  ...
  $items['foo/ajax'] = array(
    'title' => t('foo AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'foo_ajax',
    'access arguments' => array('access content'),
  );
  ...
  return $items;
}

Implement the foo_ajax page callback:

function foo_ajax () {
  // Retrieve the slider value
  $slider_value = (int)$_POST['slider_value'];

  // Get some id's from the foo table
  $result = db_query('SELECT id FROM {foo} WHERE value = :value', array(':value' => $slider_value));
  $data = array();
  foreach ($result as $row) {
    // Do something with data
    // Parse to json

    $data[] = $row->id;
  }

  // Return json
  drupal_json_output($data)
}

Implement ajaxCompleted (within your javascript):

function ajaxCompleted () {
    // Parse Json
    // Add some stuff to your DOM.
}


How to add programmatically region's class when region had block in D8?

Check Block Class module for this

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


Must an admin theme be enabled to be used?

No, it's not needed to enable theme to use it as an admin theme. You only need to enable it if you want to alter it's settings, both the ones in "appearance" section, and blocks. Just go to http://example.org/admin/structure/block/list/seven and http://example.org/admin/structure/block/list/your-seven-subtheme and set up the blocks the way you want them, that's all.


Block visible only to the user who created it

You can use block visibility settings PHP code to check for specific users.

Please find the sample php code below.

<?php
global $user;
$allowed = array('moderator','administrator'); // Allowed Roles
$allowed_uids = array(1, 5, 10); // 1, 5, 10 are user id's which you want to allow
$valid=FALSE;
foreach($user->roles as $role){
  if(in_array($role, $allowed) && in_array($user->uid, $allowed_uids)) {
    $valid=TRUE;
  }
}
return $valid;
?>

See the screen show below where you need to write above code.


How do I invalidate cache for a block for anonymous users on a schedule?

At the top of the issue queue of Office Hours is this issue:
Fix javascript in D8-version of office_hours module
The problem is, you need this issue resolved, because for anonymous users javascript has to work.
If you want to build your own module, follow @oknate advice and use a lazy builder in a custom block plugin and install BigPipe to get the javascript part for anonymous logged-in users.
Updated question:
For anonymous users you can instead of disabling the Internal Page Cache set an expires header to the response as suggested by @Berdir's comment. See https://drupal.stackexchange.com/a/196557/47547


How to get Signatures for Forums using SQL query?

Please try the following.

if ($account->id() && isset($form_state['values']['user_signature'])) {
    if (!$account->get('user_signature')->isEmpty()) {
      db_merge('user_signature')
        ->key(array('uid' => $account->id()))
        ->fields(array(
          'signature__value' => $account->get('user_signature')->value,
          'signature__format' => $account->get('user_signature')->format,
        ))
        ->execute();
    }
    else {
      db_delete('user_signature')
        ->condition('uid', $account->id())
        ->execute();
    }
  }


Providing a default value for an Entity Reference Field using Views Bulk Operations

I figured this out.

Views > Create New View > Content type 'Schools'

Format > Table

Add Fields > Title

Add Fields > Bulk Operations (Content) > Bulk Operations > Modify Entity Values > 'Your Entity Reference Field' > Skip Confirmation Step > Show Token Values

done - navigate the views bulk operations URL, select all of your nodes and apply the changes ... You might need to adjust the pager options in the view to see all of your nodes, and also disable the feeds importer while you adjust the nodes associated with it...


Problem was WSL1, in PowerShell with admin rights wsl -v -l

  NAME            STATE           VERSION
* Ubuntu-18.04    Running         1

Convert your WSL1 installation to WSL2 wsl --set-version Ubuntu-18.04 2

Takes about 10 minutes to finish and needs more than 10GB of free space on the drive for the process.

More at https://scotch.io/bar-talk/trying-the-new-wsl-2-its-fast-windows-subsystem-for-linux


Here's my Core Drupal search based solution for the same. The code below would be responsible for indexing the node author in a custom module badly named My custom module ('my_module.module'). Most of the code is heavily inspired by the core search module's search.api.php.

Once the module is in place ensure that its name (again My custom module) is checked in Active search modules.

/**
 * Implements hook_search_info().
 * This ensures that the Search Content by author tab is present in your Search result
 * and available in the path site/byauthor/<searchterm>
 */
function my_module_search_info() {
  return array(
    'title' => 'Search Content by author',
    'path' => 'byauthor',
    'conditions callback' => 'callback_search_conditions',
  );
}

Following this click and confirm re-index content and run cron for the actual indexing
The hook_update_index is written such that for each node the author name is retrieved and stored in the search index as a type 'nodebyauthor'.

/**
 * Implements hook_update_index().
 *
 * To actually index the nodes based on the uid
 * "Inspired" by search.api.php from drupal core search
 */
function my_module_update_index() {
  watchdog('my_module', 'entered my module update index');
  $limit = (int)variable_get('search_cron_limit', 100);
  $result = db_query_range("SELECT n.nid FROM {node} n
            LEFT JOIN {search_dataset} d ON d.type = 'nodebyauthor'
            AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0
            ORDER BY d.reindex ASC, n.nid ASC", 0, $limit);
  foreach ($result as $node) {
    // simple query seemed a better option than loading the node and author object
    $author = db_query("SELECT `uid` FROM {node} WHERE `nid` = :nid",
              array(':nid' => $node->nid))->fetchField();
    watchdog("my_moduleupdateidx", "Node is {$node->nid} and uid is {$author}");
    if ($author !== FALSE) {
      $author_name = db_query("SELECT `name` FROM {users}
                     WHERE `uid` = :uid",
                     array(':uid' => $author))->fetchField();
      search_index($node->nid, 'nodebyauthor', $author_name);
    }
  }
}

A helper hook hook_search_reset to mark content for reindexing when re-index option is triggered

/**
 * Implements hook_search_reset().
 *
 * Reset the indexed item timestamp for being reindexed on subsequent cron runs.
 */
function my_module_search_reset() {
  db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', 'nodebyauthor')
    ->execute();
}

The hook_search_execute is where the actual newly indexed content (after enabling our custom module and running cron) will provide results based on the user when a search is triggered:

/**
 * Implements hook_search_execute().
 *
 * To provide matching node results based on the node author when searched, again blatantly copied from search.api.php
 */
function my_module_search_execute($keys = NULL, $conditions = NULL) {
  $query = db_select('search_index', 'i',
           array('target' => 'slave'))
           ->extend('SearchQuery')
           ->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'nodebyauthor');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);
  /*drupal_set_message((string) $query);
  drupal_set_message(var_dump($query->arguments()));
  drupal_set_message((string)$query->countQuery());*/
  // Load results.
  $find = $query
    ->limit(10)
    ->execute();
  $results = array();

  foreach ($find as $item) {
    // Build the node body.
    $node = node_load($item->sid);
    node_build_content($node, 'search_result');
    $node->body = drupal_render($node->content);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
    // Fetch terms for snippet.
    $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

    $results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );
  }
  return $results;
}

Despite being huge even with some additional search hooks missing I believe anything is better an option than hacking core. Hope this helps.


How can I update the values of an exposed view filter when another filter changes value?

This module might help: Views Dependent Filters

If you really want a custom solution take a peek at the code there and see if it helps, or help the D8 version get released :)


Specifying Taxonomy Term Filter in View from Page Editor

There are two parts to this question - one is to have creators of nodes to choose a Taxonomy term, the other is to have a Views Display show up on Node View based on the Taxonomy term set inside the node.

Taxonomy term reference

As you've already worked out, the easiest way to allow for users to influence what content list to display on their nodes is to allow them to choose a Taxonomy term.

You can do that by creating an Entity reference field referencing Taxonomy terms. The way you worded your question suggests you will only allow one term to be selected (limit number of values to 1).

When the node is saved, the information about the chosen Taxonomy term will be displayed when viewing the node. If you don't want this to be visible, if you only want this field to serve as a way to influence Views in the following steps, you can hide the field from showing up on node view by changing Manage Display settings. The info from the field will still be available for Views to read "on the sly".

Views Block listing content sensitive to the Taxonomy of the page they're on

Creating Views that display related content is probably the most common request in Views. With such a Views Block you don't have to have any additional interface for node creators to choose what to display on their nodes. Simply having a Taxonomy term reference is enough (already covered above).

First you create a Views Block listing your desired Content (set up all the regular Filters and Fields).

Then add a Contextual Filter of type Content: Has taxonomy term ID, and configure it to Load filter from node page (NOT taxonomy term page). Take a look at screenshots from this answer: display lists of related content that share the same Taxonomy term.

In the end place the Block in a region, and configure the block settings (to display only on node page where you want).

When your content creators save a new node, that Block will automagically show only Teasers of content tagged with the term they chose when creating the node.

If the content type of the created node is the same as the content type of teasers in the Block, the newly created node will also be displayed on the Teaser list. If you don't want the node you're currently viewing to be listed there you can exclude it with an additional Contextual Filter Content: ID (Provide default value: Content Id from URL, More (at the bottom): Exclude).


Adding referencing entities using hook_entity_property_info_alter

It looks like you are trying to add a multi-valued entity reference property to a standard node entity. If that's the case, I think you first need to declare the property as multi-valued in hook_entity_info_alter() via the 'type' entry:

$info['node']['properties']['referencing_matching'] = array(
  'label' => t('Referencing matching'),
  'type' => 'list<matching>',
  'description' => t("Matchings referecing a job"),
  'getter callback' => 'get_referencing_matching'
);

See the hook_entity_property_info() notes for more on that.

Then, in the getter callback I believe you need to return a list of entity ids, something like:

if ($node->type == "job"){
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'matching')
        ->fieldCondition('field_job_id', 'target_id', $node->nid, '=');
  $result = $query->execute();
  if (!empty($result['matching'])) {
    return array_keys($result['matching']);
  }
}

I have not tested that specific code, but this was the pattern that I used in a similar example of my own.


How to set Disqus Share link to window.location.pathname + window.location.search?

So the solution was to add my own Javascript file and just clear the drupal settings for disqus like this:

Added Javascript file to modules/custom/MYMODULE/MYMODULE.libraries.yml

disqus-overrides:
  version: VERSION
  js:
    js/disqus_overrides.js: {}
  dependencies:
    - core/drupalSettings

Created a new file in modules/custom/MYMODULE/js/disqus_overrides.js

drupalSettings['disqus']['identifier'] = '';
    drupalSettings['disqus']['title'] = '';
    drupalSettings['disqus']['url'] = '';

Then force this file to be loaded on every page load in modules/custom/MYMODULE/MYMODULE.module (this could be optimized to only load on those pages with the Disqus comment field, but I don't know how yet):

function MYMODULE_page_attachments(array &$attachments) {
        $attachments['#attached']['library'][] = 'MYMODULE/disqus-overrides';
    }


Yeah, that's an odd approach with === isset() basically checking if drupal_get_title == TRUE; whereas drupal_get_title returns a string title.

Something like this should work, in template.php or module (clear cache).

It will set the $title variable for page.tpl.php

/**
 * Implements hook_preprocess_page
 */
function MODULE_preprocess_page(&$variables){
  // Set title on user account pages.
  if ($account = menu_get_object('user')) {
    $variables['title'] = t('My Sharecab');
  }
}


How to add a payment gateway with two different accounts?

Use multiple payment method rules for the same payment gateway and add conditions to them that check for the existence of particular products in the order's line items. How you do that is up to you and what your product catalog is like.


How to display custom block anywhere in a div?

Install the twig tweak module
Insert the following code in your page--front.html.twig

{{ drupal_entity('block_content', 1) }}

Where "1" is the block id. You can see the block ID when you edit the custom block, it's in the URL - E.g. my-drupal-site.com/block/1


How can I see the clean query of a view?

I gather that this piece is not correct

It’s absolutely correct - Views is just using the query results to pass through some meta data about the operation.

In this case your view joins three different fields, and the types of entity that the fields are related to are nodes. Views is just keeping track of the that fact for each field, so it can use a generic processor for the results.

If you don’t need to use those fields from the query, you can safely ignore them.


Use administration theme for verified users when adding or editing content

Enable View the administration theme permission for verified/authenticated users.


What is difference between a custom block and a Bean block?

Custom block

If you'd created/configure a block using the typical Admin UI, located at admin/structure/block, you enter configuration options like visibility, block title, etc. That's what I would consider as "an" example of a custom block.

And when some module that you enable causes some block to become available (related to that module), it could be considered as a similar block, though "custom" does not apply to it (maybe call it a module delivered block?).

Bean block

Bean blocks are (also) blocks, but what is special about them is that you use the Bean module to create such blocks. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting Bean permissions, it gives you a lot of flexibility about how exactly you want to use this (great) module.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A rising star ...

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has about 32K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...


I think I've had a similar issue in the past with a different payment gateway.

Inspect each variable (print_r or var_dump) one after another comparing the values between your stand alone php file and the drupal module.

When you find the point at which there is a difference you know what line it's going wrong.

Maybe shout at it a bit at this point, give it a prod, read some more API documentation and then you should almost be there ;)


Locations geocoding to province, not country

The problem is not actually with that snippet of code in _google_geocode_flatten(), but is just a result of google's geocoding algorithms.

For example, your search for BB finds 2 results, Brandenburg Germany & Barbados, however google puts the former as the first result, possibly due to popularity of searches or something.

See http://maps.googleapis.com/maps/api/geocode/json?address=bb&region=bb&sensor=false

The solution I can see is to also pass in the component param when requesting from google geocoder, which allows you to specify specific parts of the address in addition to the full address string.

See https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering

I have posted a patch back to your issue on drupal.org


How to control a taxonomy view's output?

It sounds like you're trying to do a couple complex things: 1) use contextual filters to choose which term to show and 2) then you're trying to theme certain taxonomy term pages. Once you've got stuff set up in a way that uses these concepts, you should be able to accomplish your end goal (But the views need to be dynamic, so that if a new type/application is used, it is added to the list to the left and the styles applied as desired.) relatively easily.

This is a good basic introduction into Views Contextual Filters: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

As for theming taxonomy term pages, I think everyone has different ideas on how to best to do that, but if you've already got these three views set up, it might be easiest to use Panels (https://drupal.org/project/panels) and drop those existing views into a panel that is context-based. Of course, Panels comes with its own learning curve, so it might not actually be that easy (though here is a basic introduction for something like what you're trying to do: https://drupal.org/node/1582906). And maybe I'm over-complicating this by assuming you want to theme your pages; maybe contextual filters were all you needed?

Just in case, here are some other ways of theming taxonomy pages:

override taxonomy-term.tpl.php (the basics of overrides: https://drupal.org/node/173880)
Display Suite: https://drupal.org/project/ds

I'm sure there are a bunch of other ways too, but that's all I've got off the top of my head for now. And I'm sure someone else will chime in with more options soon.

Also, here are some other links that you might find useful:

How to theme each nodes in a taxonomy term page seperately in drupal 7
Theme a taxonomy terms page
Overriding the default taxonomy page with a view in Drupal 7


jQuery not Loading for "Anonymous" Users

Drupal does not load jQuery if there are no dependency on it.

When drupal_add_js() is used once any where, Drupal includes jQuery automatically.

In case of user session, admin menu and overlay are dependent on jQuery so it is added automatically. So i advise you to try your drupal_add_js() code in hook_init just for try. I am not confirmed if it does not have any effect if it is called in hook_preprocess.

Please also check if you hook_node_preprocess is working at all?


hook_nodeapi() is split into multiple hooks in Drupal 7, so you should use hook_node_load()


Actually, bit of searching and here you go: Context Condition Theme

  This module will add a conditional check within context for themes. Ever had the need to load a context based on which theme is being rendered?


Views random list with different css for result 1

You can get random results in Views by using the random sort filter.
Then there's quite a few ways to target CSS on the first result.  If your using a list style, the first list item will have a views-row-first class.

However, if you want the image to be larger you really want to use a different image style.  This means the field will be different from the rest, and the best way to do that would be to move it to an attachment display.  In there, override the fields and edit the image style.  Override the pager and limit it to 1.

The next problem would be how to exclude the random image from the attachment in the main view (so that you don't get duplicate results).

You can get a view to exclude a result by adding it is an contextual filter. And in the 'more' options, select 'exclude'.

However, I don't know of a way to pass the result from the attachment into the other display as an argument.  They will both inherit the same arguments.

You could generate a random id somehow, and pass this in to your view.

But the tricky bit is how you would generate this random id, it could even be done with another view!  And then also how do you pass this into the view.
I can't quite think of an elegant solution. If you're in a hurry, here's some quick and dirty php code you could put into a custom modules hook_menu callback.

$random_id = views_embed_view('your_view_name', 'display_that_outputs_random_id');
print views_embed_view('your_view_name', 'main_display_name', $random_id);

There's definitley a better way, if I can think of something I'll let you know.

Thanks
Leon


How can I move the modules that are dependencies for a module of mine in another directory?

Drupal 7 doesn't look for modules on /modules. The list of directories looked for modules by drupal_system_listing() is the following one.

profiles/$profile/modules and its sub-directories, where $profile is the short name of the profile currently installed
sites/all/modules  and its sub-directories
$config/modules and its sub-directories, where $config is the directory containing the settings.php file used for the site

All those directories are relative to the directory containing Drupal, so a directory like /modules will never be checked for any module.

Actually, there isn't any need for a module to look for a specific directory for its dependencies. If the dependencies are modules that comes as sub-modules of the main module, they are normally put in the modules directory of the directory containing the main module, but the main module doesn't normally force Drupal to look in a specific directory for its own sub-modules.

Instead of /modules/contrib, you can use sites/all/modules/contrib, or sites/$site_directory/modules/contrib. Those are directory where Drupal looks for modules.

There isn't any way to move a module from browser, and it is normally not necessary. You put the files with FTP or SSH, and you put the modules in the correct directory before installing the module using them.
If you already have your module installed, you disable it, disable its dependencies, move its dependencies in the correct directory (one that Drupal checks), enable them, and enable the module using them. If disabling/enabling doesn't work, you simply uninstall/install the modules.


Expose only a specific content type to Views

You want to add a filter to your view that is a content type filter, and then select "only show" and check off "Region" in the checkbox list.

So, edit your view, and on the left under "Filter criteria" click add.  Then, scroll through the list of available fields to filter on and find "Content: Type", check that off, click "Apply".  Then, on the left, select "Is one of" and on the right in the checkbox list select "Region", click "Apply".

After you've done that you can save your view.  The changes should be applied and should be showing only nodes in the view that are of type Region.


First off, this isn't really a question that has a single correct answer.

It is really up to the site builder as to how they want it to work and it depends greatly on the use cases of the site and any business rules related to the content.

As such, it isn't the best question for a site like this, however I will say a couple of things:

Having thousands of taxonomy terms is ok if your content requires it. You might have a thousands of taxonomy terms and tens or hundreds of thousands of nodes. That's fine.
The second option you mention doesn't sound like a good idea. Mainly the use of fields as blogs etc. doesn't sound right conceptually. Plus handling revisions, permissions, comments for blog posts etc. is going to be a hassle to say the least.
The first option mentioned doesn't necessarily have to have the term page as the topic homepage. It could be done other ways, like having the backgrounder node as the topic homepage or using a views page with arguments to be the homepage.
Another possible solution is to have the backgrounder node be the home page and link everything to that via an entity reference field, removing the need for taxonomy at all.
As for laying out the home pages, consider using the panels or context modules combined with views.

These are not nearly all the possibilities, there are a bunch of other ways things could be done, so you can see you will not be able to get someone to give you a definitive answer.


How can I delete nodes when an arbitrary date has past?

You can use the hook_cron to solve your problem

function mymodule_cron(){
  _mymodule_delete_nodes();
}

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

See hook_cron for further information


Yes, with the caveat it still contains the JSONAPI document payload around your requested field. This is mandated by the spec so you can't just have an arbitrary JSON structure that contains only the field data you want.

This is called a sparse fields query. When you add a ?fields[$RESOURCE_ENTITY]=field1,field2... to a:

index endpoint (/jsonapi/node/article)
resource endpoint (/jsonapi/node/article/$UUID) endpoint

It will trim down the list of fields to the comma-delimited list you've specified.

To use your example, http://localhost:8080/jsonapi/node/article?fields[node--article]=body will return a JSONAPI document with all article nodes with only the body property in the attributes object.

See the JSONAPI docs about fetching resources for more info.


How to link taxonomy term with current loaded NID?

$nid = arg(1);
$node = node_load($nid);
//field_taxonomy is the taxonomy field used in the node
$tid = $node->field_taxonomy['und'][0]['tid'];
$term=taxonomy_term_load($tid)
print $term;


Change the cardinallity ratio of a an already existing field from 1 to unlimited

It is possible to change an element with a singular cardinality via the YAML source without any data loss. You would definitely lose data going from multiple cardinality to singular.
In the YAML source, add the '#multiple': true property to the element.
name:
  '#type': textfield
  '#title': 'Name'
  '#multiple': true


Sending email to hidden field using webform after calling hook_form_alter?

The problem is probably caused by the hidden field having the #value property set which overrides #default_value (even if the former is NULL or a empty string).

To get the desired result you have 2 options:

1) Override #value instead of adding a #default_value:

$form['submitted']['lt_email']['#value'] = $_SESSION['Some']['Email'];

2) Unset #value then add #default_value:

unset($form['submitted']['lt_email']['#value']);
$form['submitted']['lt_email']['#default_value'] = $_SESSION['Some']['Email'];

If you are wondering which option is the right one for you then #default_value means that Drupal will accept client-side changes to the field value (via javascript for example). If you don't need/want that possibility then #value should be used (Drupal will ignore any client-side changes in that case). It's mentioned in the documentation as well.