Prevent items from being indexed so it won't come out on search

You can use the Search API module in Drupal 7 to give you this granular control over your search indexing and results.

You will need at least one other module to use the Search API,
namely one that defines a service class (e.g. search_api_db ("Database search"),
provided with this module).

Creating a server
(Configuration > Search API > Add server)

The most basic thing you have to create is a search server for indexing content.
Go to Configuration > Search API in the administration pages and select
"Add server". Name and description are usually only shown to administrators and
can be used to differentiate between several servers, or to explain a server's
use to other administrators (for larger sites). Disabling a server makes it
unusable for indexing and searching and can e.g. be used if the underlying
search engine is temporarily unavailable.
The "service class" is the most important option here, since it lets you select
which backend the search server will use. This cannot be changed after the
server is created.
Depending on the selected service class, further, service-specific settings will
be available. For details on those settings, consult the respective service's
documentation.

Creating an index
(Configuration > Search API > Add index)

For adding a search index, choose "Add index" on the Search API administration
page. Name, description and "enabled" status serve the exact same purpose as
for servers.
The most important option in this form is the indexed entity type. Every index
contains data on only a single type of entities, e.g. nodes, users or taxonomy
terms. This is therefore the only option that cannot be changed afterwards.
The server on which the index lies determines where the data will actually be
indexed. It doesn't affect any other settings of the index and can later be
changed with the only drawback being that the index' content will have to be
indexed again. You can also select a server that is at the moment disabled, or
choose to let the index lie on no server at all, for the time being. Note,
however, that you can only create enabled indexes on an enabled server. Also,
disabling a server will disable all indexes that lie on it.
The "Index items immediately" option specifies that you want items to be
directly re-indexed after being changed, instead of waiting for the next cron
run. Use this if it is important that users see no stale data in searches, and
only when your setup enables relatively fast indexing.
Lastly, the "Cron batch size" option allows you to set whether items will be
indexed when cron runs (as long as the index is enabled), and how many items
will be indexed in a single batch. The best value for this setting depends on
how time-consuming indexing is for your setup, which in turn depends mostly on
the server used and the enabled data alterations. You should set it to a number
of items which can easily be indexed in 10 seconds' time. Items can also be
indexed manually, or directly when they are changed, so even if this is set to
0, the index can still be used.

Indexed fields
(Configuration > Search API > [Index name] > Fields)

Here you can select which of the entities' fields will be indexed, and how.
Fields added by (enabled) data alterations will be available here, too.
Without selecting fields to index, the index will be useless and also won't be
available for searches. Select the "Fulltext" data type for fields which you
want search for keywords, and other data types when you want to use the field
for filtering (e.g., as facets). The "Item language" field will always be
indexed as it contains important information for processors and hooks.
You can also add fields of related entities here, via the "Add related fields"
form at the bottom of the page. For instance, you might want to index the
author's username to the indexed data of a node, and you need to add the "Body"
entity to the node when you want to index the actual text it contains.

Index workflow
(Configuration > Search API > [Index name] > Workflow)

This page lets you customize how the created index works, and what metadata will
be available, by selecting data alterations and processors (see the glossary for
further explanations).
Data alterations usually only add one or more fields to the entity and their
order is mostly irrelevant.
The order of processors, however, often is important. Read the processors'
descriptions or consult their documentation for determining how to use them most
effectively.


Execute Drupal function in background, maybe with cron, for the duration of a user session

Preface
While doing web development, if user is browsing can only be measured with two methods: 1. User last access time is less than A_PRE_DEFINED_AMOUNT (say 5 minutes) or (more accurately in some cases, as the user might be just reading the same page without refreshing) user's last heartbeat time is less than A_PRE_DEFINED_AMOUNT or or the most accurate, combination of both (js might be disabled on some browsers).
And while doing Drupal development, running a task periodically, means a cron task. but sometimes these tasks are better handled outside of Drupal.
The problem originates from the fact that Drupal does not have an always running server. Usually NodeJS is used in combination for such tasks, and it performs better (usually when resources on the server is limited). When the NodeJS has the data ready, it uploads it to drupal by calling a URL which you have previously defined in a custom module, say http://example.com/my/module/upload/data. It will use HTTP POST to authenticate and send data.
But anyway, here is the pure Drupal solution:
The custom module part:

Create a custom module.
Define a new entity type in your module (recommended) using a project like entityspice, model or plain entity api.
OR just use hook_schema() and define a table for your module in database (though entity is recommended).
Define a custom rule action in your module, when called it should write the current user id (uid) in the table you just defined. If you have created a new entity type you can use the already existing rule create a new entity.
Or just use nodes or a field in user profile but be careful about access checks. It's your call.
Create another rule action, triggered on cron (using rules_scheduler), in this action: fetch user's last access time, if it's more than 5 minutes, fetch the entity we talked about just above and remove it (more explanation on this later).
OR instead of rule action, define a cron task in your module. it should: check user's last access time, if it is more than 5 minutes, remove his/her uid from your custom table.
Or instead of checking user last access time, create a custom JS loaded on every page for logged in users which sends a heartbeat. It is simply done by defining a custom path in your module such as example.com/my/heartbeat/path and fetching that URL using HTTP GET (using ajax) on the server in your custom path's handler function, you should check current user's UID who is sending the heartbeat and update the last access time of the user. (or perhaps create your own entity/table/field for storing last heartbeat time).

Congrats! first part done. now you know if you should process data or stop processing data for user. You know you should while their UID is in your custom table.
The processing of data:
Still this part of question is unclear: who will fetch data? is there a large amount of data, or does it take long for data to become ready? if the former, you might face PHP execution time outs, if the later, you might be fine. Any way, to do it in Drupal, you should create a custom cron task which is again, possible in rules. in this cron task, check every uid which is in the custom entity/table we talked about above and fetch data for, and upload it to local database.
Your cron task should check two conditions: 1. is user uid still in table? 2. is data ready? if 1 is false, cancel fetching data. If 2 is false, just pass for now.
If there is a large amount of data being fetched and user has left the site, you probably won't be able to cancel it as there is no true multi-threading in PHP. how ever there is a register_tick_function which might do the job: if the uid of current task is removed, call die(). I don't know if die() in registered tick function works, however if data is being fetched for other users too, they will be canceled!!
final note:
DO Install Elysia Cron (optional but highly recommended). If you are planning to run cron on short periods it will take the load off of your server drastically.


Masonry effect not loaded in D7 Masonry Views

It's just because you are just updating a Jquery version in front end theme but not updating in admin theme. Because views opens in admin theme so you should also update Jquery version in it. For getting this work just goto admin/config/development/jquery_update  and click on configure link in front of admin theme, then select the same version of Jquery as you selected in front theme. Now you can edit the masonry views as per your needs and check the result.


Is it possible to return a form element AND an ajax response from the same ajax callback function?

If you want to do more than simply return new markup, then your response should be an instance of Drupal\Core\Ajax\AjaxResponse, to which you can append one or more AJAX commands via the addCommand() method.
A simplified version of this would be:
use Drupal\Core\Ajax\AjaxResponse;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper-id', $form['fid']));
return $response;

I recommend checking out a tutorial, such as one of those below, for more information on using AJAX with FAPI:

https://www.sitepoint.com/using-ajax-forms-drupal-8/
https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands


Overriding contributed module functionality

A patch doesn't necessarily apply to a new version of a module: It is enough the patched function is moved to a different line, or the code for that function is changed, and the patch doesn't apply anymore. For the function to be moved to a different line, it is enough another function is re-written to take more lines (or less lines).

A better way to alter the behavior of a module is, for Drupal 7:

If the module uses code for a page callback that you want to change, change the page callback with hook_menu_alter().
If the module implements a theme function you want to alter, change the function associated with hook_theme_registry_alter(). In alternative, if it is sufficient to change the variables the theme function gets, then you can implement the preprocess function for that theme function (e.g. hook_preprocess_rdf_metadata() for theme_rdf_metadata(), and change the variables that theme function will get.
If the module executes an SQL query using db_select(), and assigns a tag to the query, change the executed query with hook_query_alter().
If the module implements a hook you don't want it is executed, you can implement hook_module_implements_alter() to avoid it is executed.
If the module implements an alter hook (e.g. hook_page_alter()), and you want to change what that hook altered, implement the same alter hook, being sure it is executed after the one implemented from that module.

In the case the function you want to alter is not a hook, then:

Check that function is using hooks implemented from other module. For example, node_save() invokes hook_node_presave(); if I would want to change the "changed" property of the node, I don't hack node_save(), but I rather implement hook_node_presave() to alter it.
Check that function is referenced/used from a hook; in that case, you can do something for that hook, as I previously described.

If anything I said until now doesn't apply, then it is better to create a custom module, and use the code of the other module to create it. I would also try asking a feature request for the existing module, hoping the feature is implemented.
Hacking a third-party module is never a good idea, especially because automatic updates of the module (via the Update Manager, or Drush) would not anymore possible for that module.


You want to use userpoints_userpointsapi(), not the service wrapper.

The system is designed to only ever allow new transactions in order to change the total amount of points a user has. So yes, if you want to set it to a fixed value, you need to calculate the difference from the actual amount of points a user has and grant him the difference.


If you mean how to add the data- attribute to the <form> tag it would be as easy as this:

$form['#attributes']['data-foo'] = 'bar';

The same goes for any element within the form:

$form['foo']['#attributes']['data-bar'] = 'baz';

For more info have a look at the documentation for #attributes.


Custom SQL: nodereference joins and latest VID

LEFT JOIN {node} refevent
    ON event.vid = refevent.nid

LEFT JOIN {content_type_person} person1
    ON refevent.vid = person1.nid

LEFT JOIN {content_type_person} person2
    ON refevent.vid = person2.nid

This looks wrong. Instead, you probably want to use event.field_event_person1_nid and 2 instead of refevent.vid. The additional join of node shouldn't be necessary, you already have node as the main table.

The query still returns something because you are using LEFT JOIN. Since I assume that these fields are required and/or you only want those which are filled, you should just use JOIN. LEFT JOIN means that the main table is returned even if there is no matching row in the joined table.

The same is true for the content_type_event table. No need for a LEFT JOIN. That is just what views does by default unless you specify that the relationship is required.


Media Feeds should allow you to create media objects that you can use in your gallery.

  This module is the Drupal 7 solution for Media Feeds Integration. It
  provides mappers for the Feeds module. The target can be a Media
  asset, image or file field on an entity (such as a node).


You can achieve your all requirements by installing Recruiter Drupal distribution.

  Recruiter is a Drupal distribution for building Drupal based
  e-recruitment platforms. Users can register either as recruiter and
  post job classifieds or they can register as applicants and fill out
  their resume. A faceted search helps users to find jobs and possible
  job candidates.


How to provide default value with PHP code for a field in Views 3

You can pass currently viewing nodes id in contextual filter without using any custom code.

In contextual filter settings, under When the filter value is NOT in the URL select Provide default value option. Then there is a dropdown will show. Then select Content ID from URL. See the image:


You should remove the first slash from src in your theme to

<img src="sites/all/themes/microsite/images/image.jpg" />

That first slash is indicating that it is relative to your web root rather than your Drupal root.


You may implement this: hook_privatemsg_message_presave_alter in you custom module and change the message's subject as you like.

Here is a code sample:

/**
 * Implements hook_privatemsg_message_presave_alter().
 */
function your_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $message->subject = "$message->subject"; // use single or double quotes
}

Tip: strip quotes from a string


$form['#action'] works the same, Drupal 7 or Drupal 8. It needs a string, which is what url() returns in Drupal 7. The reason why url() is normally used is because the code has a relative path for a routing item, such as in url('comment/reply/'. $edit['nid']).

In Drupal 8, for example, the Comment module uses the following code.

$form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));

UrlGeneratorTrait::url(), the method called in that code, still returns a string, not an object. Also in this case, UrlGeneratorTrait::url() is used because the code has a route name (comment.reply) and it wants to get the URL for that route.

The following code works for Drupal 7 and Drupal 8.

$form['#action'] = 'http://example.com';


Extending forms (or views, or something else?!)

You could implement hook_form_alter for adding a checkbox field to your form.

The most simple thing to do after that is to handle the display of the form elements with JS/CSS (checked or not). You have to handle the validation of the different submissions of the form (with or without the delivery address part).

Here you can find a tutorial for adding custom validation to a form.

For the JS/CSS part, you can put your code in the main files of your theme, or add specific files for this form. Check this answer for the second solution.


So it turns out the regexp is not for avoiding apostrophes but to allow them, you can track down the origin to this issue to 6 years ago: https://drupal.org/node/266488

  I've added apostrophe support(+test) and a small change in check_plain() as proposed in http://drupal.org/node/165226 in the new version of the patch.

So it would be not due a security flaw but to have names with apostrophes correctly handled as you can see in the issue above:

  One of my friends is fortunate, or unfortunate, enough to have an apostrophe in his last name. Many first and last names have this, for example: O’Reilly.

  The crazy thing is: Drupal completely ignores this, and O'Reilly becomes OReily

The reason why this is crashing your site is hard to foresee, I stand that you might be fixing the symptoms here and not the cause by changing the regexp. Check the username databse you've got for strange chars.

If you want to have a way to modify this validation pattern, you can check this module Custom username validation.


Customizing the way the form is displayed to admin user

You can make use of system_settings_form to make admin form and theme_table to make a table output.


How do i give other users permissions for modules?

To adminster the permissions for a module navigate to  Administration » People » Permissions.  There you will find a panel where you can assign permissions for the various modules.  The section for the FAQ (Frequently Asked Questions) module is shown below:

As you can see, this module have three separate permissions:

Administer FAQ module
Administer FAQ order
View FAQ pages

To grant as specific role a permission, you tick the mark to the right of the permission and below the role.

In the screen shot above, all roles are granted the right to "View FAQ pages", but only the administrator is granted the other two permissions.


In Drupal 8 module creation, why don't I have to put the directories "modules" and "src" in the namespace of my yaml file?

"Why", in a general sense, is for convenience. Drupal 8 uses PSR-4 autoloading and maps the respective module namespaces to each module's src/ directory. See drupal_classloader_register():

function drupal_classloader_register($name, $path) {
  $loader = \Drupal::service('class_loader');
  $loader->addPsr4('Drupal\\' . $name . '\\', \Drupal::root() . '/' . $path . '/src');
}


Set mod-rewrite to forward everything accept for one subdomain

Something like this should do it:

RewriteCond %{HTTP_HOST} !^(www|m)\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


You could accomplish this with a custom node.tpl.php for the content types - whereby it checks if the author of the node is the currently logged in user, and if not, it doesn't display the comments links (or the comments all together).


How set background image for doc files when exporting nodes to Word in Drupal 7?

The functionality you are looking for does not (as right now) exist in the version of the module you have linked to.

Therefore you will not be able to set the background image of the Word document without making modifications to the module.

This would be non-trivial as your modified module would have to do the following:

parse the CSS of the page to determine what image should be displayed
load the image and embed it in a format that Microsoft Word can understand
set the necessary tags in the Word document to use the embed image


Blog posts are being listed under content

The fact that blog-post-title appears suggests that the module PathAuto is somehow involved.  Try to disable that module (If you're on Drupal 7, navigate to Home » Administration » Modules, locate PathAuto and remove its tickmark, then press "Save configuration" and clear all caches.)

If the blog posts now appear under /blog, you know why.

After you've etablished that PathAuto is indeed resposible, you can re-enable the module (all its settings will be left intact), and you can then proceed to change its settings to put blog posts in the place you want them.


How does one see the specific structure of some variable?

You can use kint in a template. Enable the devel and kint modules and you can call it right from your template: {{ kint(node) }}


Add new block then yo have to specify whether the block should be visible in all pages or specific pages in the Show block on specific pages save it.
also while assigning the block to any particular region you need to save the block by clicking on save blocks button at the bottom of the blocks page.


Is it possible to dynamically set Views' pager settings?

The views hook that you would want to use is hook_views_pre_build which is called before the query is built. Now this is assuming you have some basic module development experience and that you are familiar with the views api.

You should be able to do :

/*
 * Implementation of hook_views_pre_build().
 */
function hook_views_pre_build(&$view) {

  // Make sure this is only for the specific view you want to modified
  if ($view->name == "foo_bar") {

    // Get the x-y value from where you're storing it (in your example the node object).
    $pager_count = get_count_for_this_node();

    // Lets also make sure that this is a number so we won't destroy our view.
    if (is_numeric($pager_count)) {

      // Now lets set the pager item to what ever out count is.
      $view->pager['items_per_page'] = $pager_count;
    }
  }
}

Above we're using a views hook that's called before the view query is built that way the pager and everything else will reflect the change.

Word of caution: views hooks should only be used if you understand whats going on. The above code is written for views-2.x.

Hope this helps.


Use node title as page title in views full node page display

I finally managed to pull this off by writing a small module using following code:

function MYMODULE_preprocess_views_view(&$vars) {
  // Get my view
  if ($vars['view']->name == 'MY_VIEW_NAME') {
    //get the title of the node shown in the view
    $nid = $vars['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $vars['view']->build_info['title'] = $my_title;
  }
}

This module changes te views page title and uses the nodes title as page title instead.

Now you can remove the linked nodetitle in the node--YOURTYPE.tpl.php


Setup a view to show most recent post or a post promoted to front page

You are on the right track but, you don't have to create another view block. You can easily add more sort criteria on your existing view block and rearrange the sorting criteria. Also, just a suggestion it is better to use Sticky at top of lists than Promoted to front page.  For more, you can refer to Frontpage views.


What tools do I need to automate my Drupal workflow?

The quickstart project will handle almost all of these tasks.  It is basically a preconfigured drupal development environment that you run in a virtual machine.

If you wanted to install the tools locally, you can do almost everything in your lists with drush & make.


After spending good 20hours with investigating the issue I was able to fix it by repairing an entity error in the database via un and installing the file_entity module.


How can I implement a custom display widget for an existing field?

The Examples project on drupal.org has a field example, showing how to implement a widget.

Basically you need to implement hook_field_widget_info(), and for 'field types' include the field type your widget is for.


How to send formatted html email using swiftmailer?

Swiftmailer only sends mails, it doesn't let you create HTML / plaintext content for emails.

I think that you want to use a module like mimemail to do this.

I came across this article that describes how to style mails send out using mimemail.

Theming HTML Mail sent through Mime Mail

This guide is made for Drupal 7, but the module has been made for Drupal 8 as well, so I think you might just create a mimemail-message.html.twig


Add extra field on check out page of Drupal 7

I think you can add a new field for your orders in "Store > Configuration > Order Settings > Manage Fields."

Next, using the Commerce FieldGroup Panes module, you can add the new field as a pane in your checkout.


No calendar showing on Rooms bookable unit - when clicking manage availability

Rooms and BAT are separate modules, you should fully un-install BAT and then follow the Rooms installation instructions. Rooms depends on the fullcalendar library, but not the full calendar module.

  Within the Rooms module there is a rooms.make file which will download the library if using Drush or you can visit https://github.com/arshaw/fullcalendar/releases/download/v2.6.1/fullcalendar-2.6.1.zip to download it. The FullCalendar library should be placed in sites/all/libraries so that you end up with the file located here: sites/all/libraries/fullcalendar/fullcalendar.js

(quoted from http://docs.roomify.us/rooms/installation.html)


The type of entity you are dealing with defines the hook you need to implement; in this case it is NOT block but rather block_content, as provided by the "Custom Block" core module.

N.B.: It is generally good practice to use more specific hooks when possible, as it will have a general effect on your code's performance, i.e. your hook implementation will be called less times if it is more specific. In your case, instead of going through all blocks available on any page during page loading, you are going through only custom blocks (block_content entities).

In order to get your hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter() implementation to work, you need to replace ENTITY_TYPE with block_content. That should give you the following code (which I tested and works):

use Drupal\block_content\Entity\BlockContent;
...
function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

And the visual result:

Good luck!


Which hook or tpl file controls the output of a view (to manipulate the results)?

Views Template Suggestion

All views templates can be overridden with a variety of names, using the view, the display ID of the view, the display type of the view, or some combination thereof.

Below are different template suggestions you can use for overriding the defaults.

Let consider a example View, named foobar. Style: unformatted. Row style: Fields. Display: Page.

Display output: This controls the structure of the overall view, including the position of and code around the view administrative links, header, exposed filters, pager, "more" link, footer and feed icon. This template also controls the position of and code around the primary view content, empty content, and attached views.

views-view--foobar--page.tpl.php
views-view--page.tpl.php
views-view--foobar.tpl.php
views-view.tpl.php

Style output: This controls the structure of this particular view display's style, e.g. HTML List, Table, Unformatted, etc. This includes the view title and the code surrounding each row (item in your view) of the given style.

views-view-unformatted--foobar--page.tpl.php
views-view-unformatted--page.tpl.php
views-view-unformatted--foobar.tpl.php
views-view-unformatted.tpl.php

Row style output: This controls the internal structure of each row (item in your view), including the label and the content for each field.

views-view-fields--foobar--page.tpl.php
views-view-fields--page.tpl.php
views-view-fields--foobar.tpl.php
views-view-fields.tpl.php

Fields: There will be one entry for each field in your display, allowing you to control the structure and code for each. If your row style is set to "Node," there won't be any field entries, and the view will use the node's template file instead.

Lets take you have added Title field in the field list, then below are the suggestion to theme title field

views-view-field.tpl.php
views-view-field--title.tpl.php
views-view-field--foobar.tpl.php
views-view-field--foobar--title.tpl.php
views-view-field--page.tpl.php
views-view-field--page--title.tpl.phpfoobar
views-view-field--foobar--page.tpl.php
views-view-field--foobar--page--title.tpl.php
views-view-field--page-1.tpl.php
views-view-field--page-1--title.tpl.php
views-view-field--foobar--page-1.tpl.php
views-view-field--foobar--page-1--title.tpl.php

Views Preprocessors suggestion
If you want to alter the display of any view with preprocess functions, then you can use the below suggestions to modify the display of any view.

Altering Views result
To alter the result of the view itself(i.e modifying the results before its being rendered) you can use any of the following hook,

hook_views_pre_render
hook_views_post_execute

For using these hooks, you can refer the answer by jimajamma.

References

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7
http://www.ostraining.com/blog/drupal/views-templates/
http://webpartners.es/en/drupal-7-views-templates-and-preprocess
https://api.drupal.org/api/views/theme!theme.inc/7
https://drupal.org/node/352970
Why doesn't adding results in hook_views_pre_render work?


There is a very simple way to that using the Rules module.


Trying to use drupal_http_request to get an admin page

The Overlay module in the core is built to do exactly this, to open admin pages in an overlay popup.  You can enable it directly from /admin/modules.


PHP isn't Java...there's no concept of 'instance variables' in this context, and no automatic persistence of such vars across page requests.

Drupal Commerce persists information about the order, order lines, products, etc to the database during the checkout process, and then re-loads the relevant entity when it needs it (which is the standard workflow).

In hook_commerce_checkout_complete() you already have access to the $order entity, so there's no need to load it yourself. I'd advise using an entity_metadata_wrapper() to access the order; to get the order lines, for example, you'd use something like:

function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    // Do something with $line_item_wrapper.
    $field_val = $line_item_wrapper->field_something->value();
  }
}


Using an aggregated entity query to find duplicate taxonomy terms

You can use the Database abstraction layer:

$connection = Drupal::database();
$query = $connection->select('node__field_industries', 'i');
$query->fields('i', ['entity_id', 'field_term_target_id']);
$query->addExpression('COUNT(*)', 'count');
$query->groupBy('i.entity_id');
$query->groupBy('i.field_term_target_id');
$query->having('COUNT(*) > 1');

$results = $query->execute()->fetchAll();

Hope this helps


Is there a hook after user confirmation?

Although this approach uses modules, I add nodes after users confirm their e-mails using Logintoboggan and Rules.  The Logintoboggan rules integration adds a new event, When the user account is validated, which will allow you to perform actions upon e-mail confirmation.


The easiest way would be to edit the .htaccess file of your hostmaster platform and add something like

RewriteRule ^(.*\.com) http://$1 [L,R=301]

Note that you have to reload apache as Aegir integrates the htaccess file into the vhost config.


Unfortunately I couldn't get the perfect solution to this so I had to use Views PHP. Remember to add a hidden field for the nid of the node

<?php
$link = flag_create_link('MyFlagMachineName', $row->nid);
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result);
if (!empty($result)) {
  echo $result[2][0];
}
?>


How to define multiple cronjobs within single module?

As commented in that that issue and various others before, custom cron jobs are defined using config entities, in the same way that ultimate cron defines the default cron jobs.

Just export what you have by default, copy one and adjust the callback/cron configuration, then import it again or define them in your config/install folder for a new module.


I recently faced a similar problem and I solved it using the hook_form_FORM_ID_alter hook so that I can have an overview of the changes before actually applying them. My idea was to set the weight of each entity reference field to the number that can be found in the referenced entity's title. In your case however, the "numbers" in your title are not actual numbers with decimal parts but 2 different numbers that happen to be connected with a period (the first number has higher priority in the ordering than the second).

In your case you should do something like this:

function YOUR_MODULE_NAME_form_YOUR_CONTENT_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  if($form['nid']['#value'] == "22312") {  // The node id instead of 22312
    $keys = array_keys($form['field_FROM_ENTITY_REFERENCE']['und']);
    foreach ($keys as $value) {
      if (is_numeric($value)) {
        $weight = preg_match_all("/\d+\.\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        if (empty($matches[0])) {
          $weight = preg_match_all("/\d+/", $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['target_id']['#default_value'], $matches);
        }
        if (!empty($matches[0])) {
          $tempweight = explode(".", $matches[0][0]);
          $lengthtopad = (isset($tempweight[1])) ? 5 - strlen($tempweight[1]) : 5;
          $tempweight[0] = str_pad($tempweight[0], $lengthtopad, "0");
          $finalweight = implode("", $tempweight);
          $form['field_FROM_ENTITY_REFERENCE']['und'][$value]['_weight']['#default_value'] = $finalweight;
        }
      }
    }
  }
}

This solution is based on the idea that if from the 2 different-priority numbers that you have, you create numbers with the same amount of digits by padding the number with the highest priority with zeros, your final numbers will be properly ordered.

I assumed that the first number is single digit and that the second number can only go up to 3 digits. You can however adjust this to support more digits in the "decimal" part of the number.

Just to give you a couple of quick examples of how the numbers will look like after the transformation described above:

1 -> 10000
1.1 -> 10001
1.2 -> 10002
1.10 -> 10010
2.45 -> 20045
2.456 -> 20456

Of course, you can apply the same method to change the weights implicitly by using node_load, altering the weights and then using node_save to apply the new weights. It would work just fine, but with the solution described above, you edit the node-in-question and you can inspect the referenced entities and their ordering before deciding whether to save the node or not.


Which table does the Phone module store data in?

If this module defines a field, then the table is named after that field. So if your field is called field_phone, the table is called "field_data_field_phone". However, getting the value direct from the database is not the right "Drupal way" to do it.

You say you want to display the phone number in a block, but I assume this is within a specific context, such as on a page for a node or user. One way to do this would be to use the Views module to define a block with whatever fields you wish to display, using a contextual filter to get the node or user ID from the page arguments.

But more information is needed in order to say whether this is the right answer or not.


How to restrict node view to users by registration date?

You need use this hook https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7

So in your module you need code smth like this

function YUORMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($op == 'view') {
    global $user; // get current user
    // check user register date
    if ($user->created < $node->created) {
      return NODE_ACCESS_DENY;
    }
  }

// Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}


Can I program a check on a save on an admin page?

Yes, use hook_form_FORM_ID_alter()

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_some_validate_function';
  $form['#submit'][] = 'MYMODULE_some_submit_function';
}

function MYMODULE_some_validate_function($form, &$form_state) {
  if ($form_state['values']['foo'] !== 'bar']) {
    form_set_error('foo', t('Foo must be bar'));
  }
}

function MYMODULE_some_submit_function($form, &$form_state) {
  // Do something.
}

It's not possible to be any more specific than that as 'admin' pages vary in their structure. Most are created using a system_settings_form(), though, so there's a reasonable amount of consistency.

It's also worth noting that a form created with system_settings_form() saves its data in the variables table, so you can accomplish the same thing in a lot of cases with variable_set():

variable_set('site_name', 'New name');


Pitfalls when updating a site without entering maintenance mode?

As you said there:

  but they have brochureware sites with not a lot of traffic and not a lot of logged-in user sessions (which we do have)

If accessibility is very important to your website I would suggest you do NOT take the risk to directly overwrite files for upgrading while the website is still up and serving. It may lead to corrupt data or broken response.

One approach could be take one web server out of the load-balance group, upgrade it while your website is still up and serving. After upgrade and test, put it back then upgrade another one, until all are done. In this way you can seamlessly upgrade without shutting down the service. It may sound complicated and boring, but it could be highly automated by writing some scripts I think.


IE Stylesheets being ignored - only on production server though

IE chokes if you have more than 31 stylesheets, which most Drupal sites do if you create a zen subtheme. Turn on CSS aggregation in your performance settings to fix that.

There are potential (temporary or easily fixable) problems associated with migrating a Drupal site from http://example.com/dev/ to http://example2.com/ that you can avoid completely if you develop on a subdomain, ie. moving http://dev.example.com to http://example.com

check your database and theme files for paths starting with "dev/" and give your .htaccess files the once-over.


Why table creation on module install doesn't work?

In Drupal 7, it is not necessary to call drupal_install_schema(), or drupal_uninstall_schema(); that is automatically done from Drupal. It is enough to implement hook_schema(), and the database table is created. There are many modules for Drupal 7 implementing that hook, and their database tables are created.

I can think of two possible causes for the database table not being created:

The short name of the module is not bip_content_migration
You added the hook_schema() implementation on an already installed module

If you installed the module, disabled it, changed the code, and re-enabled it, the database table would not be created. Disabling a module is different from uninstalling it. Uninstalling is done when a module is disabled, and then uninstalled from the "Uninstall" tab in admin/modules.

I didn't considered the following two cases, as Drupal should have given you some errors:

The schema is not correct
Drupal is not able to connect to the database, while installing the module.

If there are more databases, be sure you are looking at the right database.


How to disable input field but show tekst with hook_form_alter?

use #disabled like below:

$form['field_pe_punten']['#disabled'] = 'disabled';


I tracked this down to the fact that current_path(), which returns path/to/content in the browser, instead returns batch when called from within Simpletest.

Since drupal_lookup_path() uses the output of current_path() to generate the $cache[map] variable that it uses to find and store the path alias, this prevents drupal_lookup_path() from working in tests.

I have filed this as an issue on d.o.


How to disable page redirect on node edit?

I am not sure what the ajax is doing in your specific case, but if all you want to do is redirect back to the node/###/edit page instead of node/###, you are wanting to swap out the submit handler with one that doesn't do the redirect.

The core one, assuming your hook-nodeapi tag implies Drupal 6 anyway, looks like this....

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

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    $form_state['redirect'] = 'node/'. $node->nid;
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

So, if you created almost a duplicate of it in a custom module...

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

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    // $form_state['redirect'] = 'node/'. $node->nid; // just remove or comment out this line
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

with the only change being the removal or commenting out of the redirect, you are halfway there.  Now you need to have this one called when you are editing nodes, which is done with a form_alter, something along these lines...

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

  if ($form_id=='TYPE_node_form') { // TYPE is the machine name of the content type you are dealing with here

    if (arg(2)=='edit') {

      foreach ($form['buttons']['submit']['#submit'] as $h => $handler) {
        if ($handler=='node_form_submit') {
          $form['buttons']['submit']['#submit'][$h]='YOURMODULE_node_form_edit_submit';
        }
      }

    }

  }

}

and now, assuming no copy/paste typos, you should be able to edit that node type and if you hit submit, it does not redirect to the node page but rather redirects back to the node/#/edit page.

Now, if somehow your ajax stuff is doing something similar like swapping out the various handlers, then you will have to do something different yet similar, and the above should be able to guide you a bit.  (The point I am trying to make here is that hitting submit causes drupal to go to/load another page unless that button itself has been ajaxed or otherwise modified)

UPDATE:

I changed the name of the handler from YOURMODULE_node_form_submit to YOURMODULE_node_form_edit_submit because, as I just found out, if you happen to have a module and content type of the same name, drupal goes all recursive on you upon trying to submit the edits of those node types due to hooking into TYPE_node_form_submit automatically.


You need to install Entity reference module

Then in your blogs content type, add a new field

Name: [what ever you like] I named mine aaaa
Type: entity reference
Widget: auto complete.
Then on the settings page for Target Bundle select poll.

Then edit your block, and in entity reference field (aaaa), type your poll name and save changes.

In Views, create a block view of poll.

Under Advanced, RELATIONSHIPS add Entity Reference: Referecing entity NOT referenced.

Checkmark require this relationship.

Then add a CONTEXTUAL FILTER of Content: Nid

For Relationship, select your referecing

Provide default value, Content ID from URL.

Note: your view preview will be blank, but it will show up when you view the blog.

Lastly, in blocks, assign your view block to a region.

Now this will automatically show the poll that you reference in your blog.


Simple button to send users info to an email address

Hope this will help you.

In Drupal 7 you can use ctools for your requirement.

Just create a ctools link after 100% of profile completeness

Steps

Create link on 100% of profile completeness in the profile page

global $user;
ctools_include('ajax'); // Include the CTools tools that we need.
$entity_type = 'user';
$bundle = 'user';
if (module_exists('pcp')) {//check for 100% completeness
  $check_percentage = pcp_get_complete_percentage_data($entity_type, $bundle, $user);
  if (is_array($check_percentage)) {
    if ($check_percentage['current_percent'] == 100) {//100% of profile completed
      $mail_link = '';
      $mail_link = ctools_ajax_text_button(t("Send Mail"), "send_mail/nojs/$user->uid", t("Send Mail"));
      $link = "
uid . "'>"; //must have unique ID for replacement
      $link .= $mail_link;
      $link .= "";
    }
  }
  return $link;
}

Create menu for callback

$items['send_mail/%ctools_js/%'] = array(
  'title' => '',
  'page callback' => 'send_mail_link',
  'page arguments' => array(1,2),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);....
 return $items;

Send mail callback

function send_mail_link($js, $uid) {
  // Include the CTools tools that we need.
  ctools_include('ajax');
  $output = '';
  if(isset($uid)){
     $output .= 'Mail Sent';//without link
    //Code for sending an email to the administrator
    if(/* mail sent */){
       drupal_set_message('mail sent');
    }
  }
  if ($js) {
    $commands = array();
    $commands[] = ajax_command_html("#send-mail-$uid", $output);
    print ajax_render($commands);
    exit;
  }
  else {
    return $output;
  }
}


Verify that there are not extra characters at the beginning of the file, right before the <?php part; this would cause the error you have seen.
Sometimes the editors add the BOM (Byte Order Mark) when saving an Unicode file; verify Unicode is not the text encoding used to save the file, or that the editor is not set to add the BOM to the files it saves as Unicode.
The BOM characters are not normally visible in a text editor; if the editor has the option to show characters that have a specific code, or "invisible characters," that can help to notice them.

Alternatively, the file got corrupted when transferred.


Render picture module image in a custom module

Here is my solution to build the render array of the drupal 7 picture module v2

//Load picture renderable array

$picture_name = 'mapping_name'
$fallback_image_style = 'large';

$image = $node->field_image[LANGUAGE_NONE][0];

$picture_mappings = picture_mapping_load($picture_name);

$breakpoint_styles = picture_get_mapping_breakpoints($picture_mappings, $fallback_image_style);

$picture = array(
        '#theme' => 'picture',
        '#width' => isset($image['width']) ? $image['width'] : NULL,
        '#height' => isset($image['height']) ? $image['height'] : NULL,
        '#style_name' => $fallback_image_style,
        '#breakpoints' => $breakpoint_styles,
        '#uri' => $image['uri'],
        '#alt' => isset($image['alt']) ? $image['alt'] : '',
        '#attributes' => isset($image['attributes']) ? $image['attributes'] : NULL,
        '#timestamp' => $image['timestamp'],
      );

print render($picture);


VBO: "Change owner" Vs "Change the author of content"

Change owner is an action implemented by the Views Bulk Operations module, while Change the author of content is an action implemented by the Node module. (See views_bulk_operations_change_owner_action_info() and node_action_info().)

The VBO module implements that action for any entity for which that action makes sense. (In other words, if the entity doesn't have an owner, the action is not implemented for that entity.) Apart that, the underline code doesn't change much.

// This is the function for the VBO action.
function views_bulk_operations_change_owner_action($entity, $context) {
  $entity->uid = $context['owner_uid'];
}

// This is the function for the Node module action.
function node_assign_owner_action($node, $context) {
  $node->uid = $context['owner_uid'];
  $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(
    ':uid' => $context['owner_uid'],
  ))
    ->fetchField();
  watchdog('action', 'Changed owner of @type %title to uid %name.', array(
    '@type' => node_type_get_name($node),
    '%title' => $node->title,
    '%name' => $owner_name,
  ));
}

The obvious difference is that the VBO action implementation doesn't log for which node the owner has been changed. When changing the owner for many nodes, its implementation could be faster than the Node module one.


How do I use print to generate a PDF of all entities referencing a specific node?

Seeing the url for print layout works fine, my first suggestion would be, that you can actually do it simply by activating the pdf module and changing the path to trigger the 'pdf-generator':

print-path:
http://fanbards.net/print/stories/13008

printpdf-path: http://fanbards.net/printpdf/stories/13008

…you may find further useful info about this on the documentation page for Print.


in Rules, after your Action Create a new entity (of type taxonomy term), when you set a new one, Set a data value, find the entity you just created -> Description .


Remove default tab from login page ( Simple Fb Connect)

Create a hook_menu_alter function like this in a module:

function my_module_menu_alter(&$items) {
  unset($items['user/simple-fb-connect']);
}


Just execute core/rebuild.php.
As the documentation says, it rebuilds the cache even when Drupal doesn't work; it require a token you can generate with scripts/rebuild_token_calculator.sh, so you call it as http://example.com/core/rebuild.php?token=TOKEN_YOU_GET_FROM_THE_SCRIPT.


Check the size of the files, maybe they are to big. Check the max. file sizes on your server and in Drupal!.

PHP configuration check:

check the following parameters:

post_max_size

upload_max_filesize

If these values are to small, you have to change them on your server in your PHP configuration (for example php.ini)


Using the Big Pipe approach for listing pages that are driven by Solr Index

What exactly do you want to achieve?

That you can scroll endlessly through your nodes and don't have to click on pager links?

That's not related to the big pipe stuff.

Instead, you'll need a views pager plugin for that, e.g. https://www.drupal.org/project/views_infinite_scroll. There is a Drupal 8 version but I haven't used it yet, so I don't know if it's stable.


Technical advantages of either Configuration or Features over the other?

Watch Configuration for the future, because it more closely follows the model of Drupal 8. But I wouldn't suggest using it for now, because it is in alpha state, which means you need to be prepared to hack on it to keep it working, and you need to constantly update it, because it will not get formal Security Advisories if security issues are discovered.

Features is at 1.0, so it's a more stable choice for projects going to production soon, as you can trust that minor version updates will not break your existing features.


Drupal add fieldset inside form and wrap all form elements under that fieldset

It should be something like this.

function change_password_form($form, &$form_state) {
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  $form['#account'] = $GLOBALS['user'];

  // To make the fieldset define #type as fieldset
  $form['fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Password Info'),
    '#collapsible' => TRUE, // Added
    '#collapsed' => FALSE,  // Added
  );

  $form['fieldset']['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE,
  );

  return $form;
}


How to limit edit permission to individual values on a multi value field?

I think your goal is to create a gallery which different people can upload their own images into it and then modify those images. Reaching this goal you can create a gallery content type with multiple images and a taxonomy or a referenced field so you can relate two galleries owned by two different people and in this case any user can modify, create or delete his/her own gallery. At the end you can create a global view for all images using Views module so all images posted by all users are listed inside and can be categorized using the reference field you have added.

If you want all images being uploaded to same content then you must use another approach which needs the ability of drupal module development, first of all you must create a new field type using drupal Field API. This field type must contain a image subfield and a user reference so you can have both image and its uploader in a same place. Then you can use hook_field_access to restrict access to field values in different operations.


Repeat view entry for each value of multivalue field

Ok I finally figured out how to do this.

I order for the line item to repeat itself I unchecked the single line representation for multivalue field.

And in order to repeat the whole invoice I call a view from within another view.


Field collection item table names in mysql

In Drupal 8 the field tables are created as [ENTITY_TYPE]__[FIELD_NAME] and [ENTITY_TYPE]_revision__[FIELD_NAME] in database. The [ENTITY_TYPE]__[FIELD_NAME] is a main field table where latest revision data of entity field is stored. Where as [ENTITY_TYPE]_revision__[FIELD_NAME] is field revision table where all revision data is stored for a field.

In your case I think your Drupal/Database has some issue, because of which the table name has random character (10 characters) hexadecimal in it. I'm not sure of exact reason of this, but I too have notice this sometime in my Drupal Site (only twice one in D7 and one in D8) not every time.

In such case, where you're unsure of which table is used for which field, you can use name and value column in key_value table to get field table mapping. The name column contains, the entity and field name and value column contains serialized array of field schema stored in blob type. The name column format is as below:

[ENTITY_TYPE].field_schema_data.[FIELD_NAME]

So if I've field named as field_test in field_collection_item entity, then the mapping will be stored as field_collection_item.field_schema_data.field_test in key_value table. Check the screenshot below:

Screenshot 1: key_value table showing record of field_test field.

Screenshot 2: value column data from key_value table for field_test field.

I know this is not a better solution but, if table name doesn't has field name in it you can use data in value column in key_value table, you can find which table is used for which field.

Hope this helps.


It's a bit strange that node_view is not returning a fully formatted node. The node module calls node_view inside it's own hook_menu to handle node/%nid requests.

Is there any chance that your CSS is selecting on something specific to node/%nid pages or your templates are setup in a non-standard way.

Can you show us the exact HTML string that is being returned by that function and the HTML string you are expecting?


Views to show nodes filtered by referenced user

What you want to do is often called displaying sibling items. In your case the connection is the ER user connection (not Taxonomy) but you can find examples with details about how to do it, search answers for it.
In short:

Create Views of type Book, you'll probably want Block Display, it doesn't have to be Entity reference Display type (that is for influencing choices in nodes in ER fields).
Add the Relationship for the User ER field. It should be the forwards Relationship. You can require it if you want to exclude all Books from your list that don't have the User ER filled in.
Add the second Relationship for that field, but the reverse one this time (it will be called different). Make it use the first Relationship. You can require it.
Add Contextual filter for Node ID, make it use the second Relationship (because this way you get the ID of sibling nodes) and configure it the usual way (default value ID from URL, validate Book node type) etc.
The current Book node will also be listed. To exclude it add another Contextual filter for node ID, don't make it use any Relationships, set to default value ID from URL and under "More" choose "Exclude".
Under Structure > Blocks set the Block to display in a theme region, and configure it to use Contextual options. Don't forget the Visibility settings too.

You should now see the block on Book nodes showing their siblings per shared user ER.
You can test Contextual filter when editing Views by entering values into the Preview field. If you have two Contextual filters you have to enter two values separated by "/" In your case enter a book node twice e.g. "12/12". "all/all" usually bypasses the Contextual filter results.
You still have to check that it works by placing the Block in a region at the end, to check your Contextual configuration is correct.


Is there a way to add clauses like accept = 'image/*' to input items via forms API?

You can override theme_file to achieve above if you would like to alter file input element in template.php ..

function YOURTHEMENAME_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}

below code works for me

function seven_file($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'file';
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-file'));

  return '<input' . drupal_attributes($element['#attributes']) . ' accept="image/*" />';
}


Make Flippy links available in page.html.twig

I didn't realize the module provides a "Flippy" block.

Remove "Pager" from Structure>Content types>MyContentType>Manage display
Add block in Structure>Block layout. Go to the region you want the links to appear, click Place block, search for Flippy Bock and you are done.

ps: the answer came from stackoverflow, but I reposted it here just in case it's useful for others too.


Displaying the parent term first in Views

The Views Tree module might be what you're after.


How to rename a field with hook_ds_fields_info()

I managed to implement this, thanks to @aspilicious.

See
- https://drupal.org/node/2190599
- http://drupalcode.org/project/views_content_ds.git/blob/refs/heads/7.x-2.x:/views_content_ds.install

The solution is to edit this directly in the database, with db_update() called from hook_update_N().

The tables are ds_field_settings and ds_layout_settings. Columns you need (same for both tables):

'id' is the primary key. Typical value: taxonomy_term|categories|full
'settings' holds the settings (field settings or layout settings), serialized.

Use drush sqlc + describe (table) to look at the table structure.

It also helps to implement the upgrade as a drush command, ideally with a downgrade option. This allows to quickly test this a lot of times, which is not that easy with hook_update_N().


Exract all node field values to json including reference entities with value

If you really really want to do this which you probably wont with JSON API Views and
serialisation
https://www.drupal.org/docs/8/api/serialization-api/serialization-api-overview
eg:
dump(Drupal::service('serializer')->serializer->serialize($entity, 'json'));

But if you really want to ...
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = [];
foreach ($node->getFields() as $name => $field) {
   // Get Type.
   $field_type = $node->get($name)->getFieldDefinition()->getType();
   //see https://drupal.stackexchange.com/questions/180373/how-to-get-the-list-of-field-types

   switch($field_type) {
      case 'text_with_summary':
      case 'text':
      case 'text_long:
        $data[$name]  = $field->getString();
        break;
      case 'entity_reference':
      case 'entity_reference':
        $value = [];
        $items = $field->referencedEntities();
        if (!empty($items)) {
            foreach ($items as $item) {
                // here is the crappy part
                $val_1 = $item->get('field_something')->value;
                $value[$item->id()] =  $val_1,
            }
        }
        $data[$name] = $value;
      break;
      // continue for other data types
      // and set a default !
   }
}


Nginx vs Apache - Are there any actual usage comparisons and statistcs out there?

Strictly speaking, this doesn't answer the question you are asking. I'm hoping it's helpful anyway.

Apache/Nginx/Lighttpd/other web server. Does it matter which one I choose? In short, No.

The much much longer answer:

If, and only if, you have a very large percentage of your users being logged in, should you care at all about the performance of your web server. If your users are anonymous, any difference that you can theoretically derive from optimizing at that layers absolute pales compared to making your resources better cacheable. If your css files have proper cache headers on them, the UA won't even ask for them the second time. That matters. If you can cache your pages in Varnish or a similar software solution, then serving that page is a matter of making a hash-lookup, and then returning a large chunk of data directly from RAM. That matters. In both of these scenarios, the HTTP daemon is never even involved, PHP does not get invoked. Drupal does not bootstrap. No large set of modules must be loaded into RAM, no time consuming database queries are executed.

When you perform a full page load, from a cold cache, for a logged in user, on a complex page; a lot of things are going on. Yes, the web server is involved in dealing with the incoming request, setting some headers and passing the response back. But the time that takes, is not even relevant in the context of Drupal running a full bootstrap and outputting its response. There could be hundreds of database queries being executed. Highly complex logic in PHP is evaluated by the parser. Lots of modules are being loaded into RAM. Improving the performance of any of those things, are much more likely to make a serious contribution to performance.

For the sake of argument: Let's say you have spent a lot of time performance optimizing everything else.

You run APC (Or Optimizer+) and the latest and fastest version of PHP.
DB-queries are few.
PHP logic has been reduced.
You cache what you can in Varnish.
You have re-structured your entire site so that you can cache a lot client side, and do lots of heavy lifting in ECMAScript.

If you have a lot of logged in users, and you've dealt with all of the above, then you can probably make a difference but performance tuning, or replacing your web server. However, guess what. Your site is so complex, and the usage patterns of your particular users, is unique. There is no generic answer. You will need to setup all different web servers behind a load balancer, and see how they behave, under your scenario.

The above was an attempt at logically reaching the conclusion that spending time performance optimizing the web server is likely a bad use of time. I would love to have someone pick holes in the above though, I would probably learn something new from it. :)

Some other notes:

During the DrupalCon Copenhagen keynote, PHP creator Rasmus Lerdorf, using Nginx himself, speaking on the topic of Drupal performance, said "People always ask me about web servers ... it really doesn't matter, the web server is pretty much irrelevant". (Roughly at 26:30 in the video)
Facebook has spent countless hours on writing Hiphop, a code base significantly larger than Drupal itself, for accelerating PHP-code by a "measly" 100%. I examined Hiphop with $ wc -l $(find . -type f | grep -v "^\.git" | grep -v "^\.hphp/third_party") | sort -nr | head -n1 and found it to consist of 1.512.481 lines of code. That's an absolutely insane amount of work put in to improving the speed of PHP. I'm guessing that's because the speed of PHP matters greatly to them.
Did I mention that good caching is going to have a much greater effect that tuning the web server?
With the release of Apache 2.4, Jim Jagielski basically claims that Apache 2.4 is faster than event based servers.
I attented Drupal Performance and Scalability with The Dream Team, where just this question came up. All the answers about which to choose, was unrelated to performance. Things like "Which one do you already know how to configure", and "Which one will allow you to build the simplest technology stack", were among the reasons mentioned to pick on over the other. Performance did not enter the picture.


'Could not find the alias' error after installing drush alias for Pantheon

If you already have terminus installed, you can use terminus drush instead of your local drush.

The advantage of terminus drush is that it already has everything you need to work with Pantheon.

The disadvantage is that you will have to do some work to set it up with your local dev environment; for that, I would just use your local drush.

So, the workflow looks like this:

Do I need to call a drush command on Pantheon? terminus drush
Do I need to call a drush command on my local dev server? drush


How do I go about telling Captcha that my form exists?

This was embarrassingly easy.  See that box at the bottom of the table?  Put your form ID in there.  "myform_form"


How should i get corresponding field value for taxonomy filed attached?

You can see the relationship by viewing or editing the node.

If you mean where is this data stored in the DB then if you created a field called file_type then the tid of the associated taxonomy term would be found in the field_data_field_file_type table.

The names of the taxonomy terms are stored in the taxonomy_term_data table.


You can display anything using Views: Nodes, users, comments, fields. Drawback is - Views object does not particularly care about the type of data. As long as handlers can process it, it works. But that means it cannot really expose methods related to the kind of data displayed. It might be possible to hack around it, but it's not the way it was designed to work.


How do I override the default page.tpl.php?

Depending for what exact content you want to make a special template there are diffrent solutions for that. Look at Drupal 7 Template Suggestions. Example for a single node: page--node--1.tpl.php.

In case the core template suggestions do not offer the flexibility you need, you can add more suggestions based on your own criteria. This is done in a preprocess function in your theme's template.php. For more information, see Working with template suggestions.


PDF Preview module not working in ubuntu for Drupal 8.5 version

I found the solution by running the below command in Docker file and run the docker build.

Install ImageMagick

RUN apt-get update && apt-get install -y \
    libmagickwand-dev --no-install-recommends \
    && pecl install ImageMagick* \
    && docker-php-ext-enable ImageMagick

Install GhostScript

RUN apt-get update && apt-get -y install ghostscript && apt-get clean


How to access rules condition values in the rule event?

I'm not sure if it'll be the only thing you need to do to get this to work, but I think you may get closer (= simplify your challenge) by ALSO using the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):


impossible to save source code in wysiwyg blocks if  does not contains some strings

If this only happens when a Text format is associated with a WYSIWYG profile, regardless of the format's Text filters or the Editor assigned to it, then try using a non-breaking space (&nbsp;) as the anchor text:

&nbsp;


How to get the URL of a file located in the theme folder?

You can use drupal_get_path() to get the path to your theme folder:

$path = drupal_get_path('theme', 'name_of_theme');

From there you can specify a particular file like this:

$image_path = $path . '/images/image.jpg';

You could also use path_to_theme(), but be wary as the return from this can change depending on the context it's called in:

  It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.


Get blank value if field value is not available

You can change $query->join to $query->leftjoin.

This will cause the query to return a row, even if there's no entry in the joined table.

Hope this helps.


What are common methods of intrusion into a Drupal website?

The first question is how they are uploading and extracting the file. That is likely only possible via a vulnerable contributed module (probably an out of date one) or because they have credentials to your server (either at the drupal layer or the server - ie ssh or sftp layer).

The second question is why your tmp directory is in a publicly accessible location (is it?). If it's not then it seems more likely the problem is arbitrary code execution or credentials compromised.

Solutions: basically you have to "start over."

Audit every single account and permission
Audit every single file of code - download fresh copies from drupal.org and ensure the versions on your site match them exactly.
Install the security review and paranoia modules and read their documentation to ensure they are working properly. They will help audit your permissions and content.


Omega Theme: how to change the stacking order of each region for each layout?

The browser, not the server, knows the width of the layout. So you cannot change the stacking order on the server side and move the regions or zones up and down without having the browser talk back to the server, which Omega doesn't do.

You could use Javascript to move things around, which is painful. You could also duplicate the content you want to be in the different places, and then hide it or display it with display: none and display: block. But then you are outputting multiple copies of the content and lengthening page load time.

Here's a similar discussion about (not) changing stacking order in Omega: http://drupal.org/node/1343798.


How to get Product name instead of sku in email to admin in authorize.net?

You might want to modify uc-order--admin.tpl.php under sites\all\modules\ubercart\uc_order\templateslook for: $product->model (SKU) and comment it out or replace it directly with $product->title , modify the template to your liking but always keep a copy of the original template.


In order to the help link appear on the module page (admin/modules), you should have both the core Help module and your module enabled.


How to build my own view for apache solr module

This is a duplicate of the question https://stackoverflow.com/questions/12496764/how-to-build-my-own-view-for-apache-solr-module so the answer is the same as well. Let me quote:

The .tpl.php files are theme template files, and you can override them by using identically named files in your own theme. Some deeper reading at Drupal docs.
Or you could use the search features provided by Google, as I did, and find an already existing answer on a related site.


Theming paragraph fields from entity reference in view

I had a situation where i had to theme entity reference fields that were used in a view. Have you tried any of these?

Setup a view mode for the Paragraph type, set view Format to Show Content where the view mode was set to the one you needed, and then i themed the view mode
Use a hook_preprocess_hook to get all the results from a View and then store them in the $variables['fields'] and then you modify the twig template for the view

This relies on Views Template Files and Debugging Twig templates


Before I could run the CCK migration I needed to run the mywebsite.com/update.php script before I could use the Migrate Fields.

That solved my issue.


How can I let users create their own playlists of a particular content type?

Flag module

Use the Flag module to create 1 flag for each of the lists you want to use it for (do NOT make it a 'global' flag though). The flags are to be created by an admin, but each user (authorized to use a flag) will then be able to build their own "lists" using such flag.

Then create a view (with the views module) for each such playlist you want, whereas you create a "views relationship" with one of those flags.

This approach requires the types of flags to be pre-defined (via admin), such as playlist-flags named like Bookmarked, Revisit Later, Add to my queue, Played, etc. Though it is ony like a 5 min admin update to add any other relevant flag later on (eg if a user requests another variation).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
Flag Lists, to allow users to create custom lists.
Flag Weights, to add weights to Flags (to be used for sorting).
DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
Flag Files, to flag media files.
Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details.

Entity Reference module

Create a content type like "Playlist" for which each user should be able to create/edit "their" nodes for (with 1 node for each Playlist they want). And add a field in it using the Entity reference module for it (with multiple values allowed). Combine this with the Node Access module to ensure that each user can only "edit" their own Playlist nodes.

Other usecases

Refer to my answer to How to motivate visitors to comment (technically)? for other usages of the Flag module as illustrations of other great things you can do with the Flag module, and some other great modules that play well with it (i.e. the Rules module).


How to add a custom marker icon on gmap using the gmap module?

You do not really need to write your own module (unless it does something out of the box) in order to use custom markers.

Here is an guide how you can do that (I assume we use gmap module and views module to display google map.

Upload you custom markers to Drupal website, f.x. to your theme folder (i.e. /sites/all/themes/yourtheme/images/markers or another location that suit you more.
In that folder you need to create an INI file and declare your custom markers (give them name etc). See example with 1 custom marker below.

Go to gmap settings /admin/config/services/gmap and specify folder where you saved your marker image and ini file (see image below).

Now make sure you saved everything and cleared cache.
Go to your view and in the settings you must get your custom marker available (at the bottom).


To get the list of the messages set with drupal_set_message(), you should call drupal_get_messages().

Drupal doesn't use any global $messages to store those messages. They are stored in $_SESSION['messages'], but you should really use drupal_get_messages().

drupal_get_messages() returns an array; this means you cannot simply use the following code.

$messages = drupal_get_messages();
print $messages;


You are editing the component rule for the flat rate. Instead, you'll want to create a shipping pricing rule.

http://youtu.be/trLydGpimD4?t=10m7s

In that video, I show you how to set up a shipping pricing rule that only runs on a particular flat rate service ... I've linked for you to jump to the part of the video that walks you through that.

The two conditions you're looking to add:

Entity has field (it should have the shipping service field)
Data Comparison (the shipping service field should equal whatever flat rate you want to tweak)

Josh


The standard date Views filters in Drupal 8 have two options:

A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.
An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

The first is an absolute date.  The second is a relative date string (I don't know why this is called an offset date).

So, add a filter, choose 'offset' as an option, and then enter your relative date.  These work for simple comparisons, and between/not between.

At runtime, the value you entered will be parsed by strtotime(); any date-like string that it will accept can be used.   This means that it will be dynamic and always be relative to when the view is executed and not when the view was created.  php|architect’s Guide to Date and Time Programming has a nice appendix in it about what are parsable values (and some of the quirks).

Keep in mind that you may need to adjust the cache rules for the view to prevent stale data from being displayed.  Also, there is a bug1 regarding time zone handling that has not been committed to core yet, which may result in some weirdness.

1 Barring unforeseen problems, this will be fixed in Drupal 8.5.0.


Can the Views Module assign a value to the

I found a place in the Contextual Filter that lets me set the page title based on the Node ID's URL parameter.

I set options that met my needs in "Context Filters > Content: Nid." Within the Nid options, there are several options for providing a filter value and for overriding the title.


How to install drush on a restricted shell access account? Media Temple shared environment

Place drush into your home (~) folder under something like ~/drush/
Create or edit ~/.bash_profile and add the following: alias drush='~/drush/drush'; this creates an alias called 'drush' that will execute drush's main file.
If you need to specify which version of PHP to use, add export DRUSH_PHP=/path/to/php.
Run source ~/.bash_profile to reload the .bash_profile file.

At this point you should be able to use the drush command.

In unrelated news: if you can, move your client off MediaTemple. Their database servers are in a physically different location from their web servers, which is an absolute nightmare for applications with a ton of database queries (read: Drupal).


How to change position of a block in a region?

If it's showing up below the page content (and you want it above), you'll need to add a new region. It's recommended to copy Garland and rename it as your own custom theme in sites/all/themes.

In the .info file, add a new region. e.g.:

regions[content_upper] = "content upper"

In the page template file, place that region just above $content.

<?php print $content_upper; ?>
<?php print $content; ?>

Then place the block in "content upper"


Views with filter on "main" and "additional" taxonomy terms

You should use the Representative Node pattern. That is that your View on the taxonomy refers to another View that collects a Node based on a particular filter (a checkbox in your example but just as easily a flag like "Sticky" or "Promoted").
There are two representative node patterns in Drupal 7. The first, which is builtin to Views, is a little less flexible (you can only sort on one parameter and you can only get one result). The second is the contrib module Views Field View which has fewer limitations but is a little harder to set up (you have to pass the contextual filter yourself).
Views 3

Firstly create a View on Content (filtering on Articles) with a contextual filter on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
Next create a View on your Taxonomy and have it list out the terms.
Add a Relationship (Advanced > Relationship) using Taxonomy term: Representative node
Sort on your specifier (your checkbox field or sticky/promoted)
Select your first View on Articles and apply.
Add a field Title and use the Representative node relationship. Continue adding fields using the relationship.

Views Field View

Firstly create a View on Content (filtering on Articles) with a contextual filter on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
Then limit the number of results. Possibly 1 in your case. Turn off paging.
Lastly filter on how you want to select your Representative node. The checkbox, or stick/promoted.
Next create a View on your Taxonomy and have it list out the terms.
Add a hidden tid (term ID) field
Optionally add Title and other fields.
Then add a field of type Global:View
Select your View previously created. Pass in the term ID.


How can I use tab_parent/tab_root in hook_menu to have one router item appear as a local task for another router item with a different path?

If I'm not mistaken the tab_root and tab_parent properties need to point to a path prefix of the router item in question - at least if there are wildcards on the path. The code responsible for this restriction is somewhat convoluted, but what you find when stepping through it is the following:

When generating the tab-links, the _menu_translate function is responsible for replacing the %-wildcards with actual values (node-id, etc). However the replacement values are not computed from the actual object-ids but are derived from the current URL. For example when accessing widget/5, the object-id is on position 1 and therefore when generating tab-links, the value 5 is only injected into paths having the %-wildcard at position 1.

This also leads to another consequence. When navigating to admin/acme/widget/5/edit, you will find that there are no tabs on this page - even if widget number 5 actually exists. This is because when generating the URLs for the other tabs, they will start with widget/acme instead of widget/5 because the value acme is at position 1 in the current path.

If you like to provide tabs on your widget page as well as have it in the backend, then simply duplicate the router item. E.g:

function acme_menu() {

  // View a widget.
  $items['widget/%'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'acme_widget_view',
    'page arguments' => array(1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'view'),
    'file' => 'includes/widget.view.inc',
  );

  $items['widget/%/view'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'View'
  );

  // Edit a widget - frontend
  $items['widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 1),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(1, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  // Edit a widget - backend
  $items['admin/acme/widget/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Edit Widget',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('acme_widget_edit', 3),
    'access callback' => 'acme_widget_access',
    'access arguments' => array(3, 'edit'),
    'file' => 'includes/widget.edit.inc',
  );

  return $items;
}

If you like to move around stuff from a third-party module, you still can implement additional router-items on behalf of it in a custom module - or even move them using hook_menu_alter.


how to print view title in views-view-unformatted.html.twig?

As per @Clive's comment

{{ view.getTitle() }}


Creating a sortable table in the backend?

If by view you mean that you want to create a custom module page for administrators, check out Examples modules, especially tabledrag_example and tablesort_example.

However, if you want to use Views, check out DraggableViews module.


The function is invoked with code similar to:

$success = array();
$url = 'mysqli://username:password@localhost/databasename';

require_once './includes/install.mysqli.inc';
$err = drupal_test_mysqli($url, $success);

Replace username, password, localhost, and databasename with the values correct for your site.
The variable $success will contain an array with a value for each SQL instruction that has been executed with success.


How do I render the page to add products into my custom module?

You need to create an empty product and use entity.form_builder service to generate the form.
Try the following.

<?php

namespace Drupal\mymodule\Controller;

use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {
   $product = Product::create([
     'type' => 'default',
   ]);
  return  \Drupal::service('entity.form_builder')->getForm($product);
  }
}


How to pass current selection to entity browser select view

The Entity Browser doesn't current pass current default value items field in persistent data, but it's easy to add it.

1) Add persistent data using field_widget_form_alter()

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface &$form_state, $context) {
  if (!empty($element['entity_browser'])) {
    $default_value =  $element['entity_browser']['#default_value'];
    $ids = [];
    foreach ($default_value as $entity) {
      $ids[] = $entity->id();
    }
    $element['entity_browser']['#widget_context']['current_ids'] = implode('+', $ids);
  }
}

2) Update your selection so that if blank it shows all:

  /**
   * {@inheritdoc}
   */
  public function getArgument() {
    $argument = NULL;
    $current_request = $this->view->getRequest();

    // Check if the widget context is available.
    if ($current_request->query->has('uuid')) {
      $uuid = $current_request->query->get('uuid');
      if ($storage = $this->selectionStorage->get($uuid)) {
        if (!empty($storage['widget_context']['current_ids'])) {
          $argument = $storage['widget_context']['current_ids'];
        }
        else {
          $argument = 'all';
        }
      }
    }
    return $argument;
  }

3) Make sure you have "exclude" and "allow multiple" checked on your selection.

By the way, if you update to the latest dev release of entity_browser, you don't need your custom plugin.  There is a new entity_browser_widget_context default value views plugin that is configurable.

I also added an issue to the entity_browser queue to add this information when in the widget_context.


Best way to use image styles with Media and WYSIWYG?

It completely depends on your requirement. If you are looking to apply particular styles through wysiwyg then view styles is definitely the right option.

If you need image style (height and width) to be chosen during wysiwyg then go for this option

a) Media + Wysiwyg -: https://drupal.org/comment/8009717#comment-8009717

b) Wysiwyg + Ckeditor -: https://drupal.org/node/1956778 (patch 37)


Theme specific drupal commerce product form

It's the same form ID for every type, but you can find context in the form state, e.g.

function MYMODULE_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['commerce_product'];
  $product_type = commerce_product_type_load($product->type);

  if ($product_type->name == 'foo') {
    // ...
  }
}


Panels Everywhere and missing Page Title

I think page title is a pane you can add to your PE master.

In the region you want to put it:

Add content -> Page elements -> Page title


Base fields

You can add base fields to the user entity in a hook:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['field1'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New field 1'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

Bundle fields

But most times you probably want to use bundle fields, which can be added and modified in UI and can be easily deployed through configuration. In D8 the user entity is fieldable like nodes.

See this tutorial:

Programming custom fields into your content type

You can apply the same procedure to users. Replace node with user, also the content type with user, because the user entity has no bundles and then you use the entity name as replacement.

In a standard install user_picture is the only user field configured out-of-the-box, which you can use as an example:

field.field.user.user.user_picture.yml

You can see that user is twice in the config name, for the entity type and the bundle name.

How to add the fields

The easiest way to implement this in a custom module is to add the fields in UI

/admin/config/people/accounts/fields

and then export the configured fields:

/admin/config/development/configuration

If you export the complete configuration before and after you've added the fields you can make a diff to catch all new yaml files.

Put the new configuration files in /config/install of your module. Remove the uuid line from the exported yaml files.


The issue was with the non-English characters in the CSV file like ö, ä etc

So the solution was to use utf8_encode() for the values:

$node->title = utf8_encode($param[0]);
$node->body[$node->language][]['value'] = utf8_encode($param[3]);

Hope it helps somebody.


Unable to access Views fields in block Twig template

In block--views-block--page-fields-block-1.html.twig

You can access the view fields like this:

{% for row in content['#view'].result %}

  {{ content['#view'].field['field_name'].value(row) }}
  // change field_name to the actual field machine name.

{% endfor %}

Personally, I rather use views-view-fields--[view-name]--[machine-name].html.twig

In your case should be views-view-fields--page-fields--block-1.html.twig

Here you do not need to do a for loop and you can access the fields easily with:

{{ fields.field_name.content }}
// change field_name to the actual field machine name.


Which Rules Event should I use to trigger a Rules Action when accessing a particular Views page?

You need to download Rules module ,Rule_link module Token module

Enable Rule and Rule link and Token module
Go to /admin/config/workflow/rules_links
Add a new rule_link, Give the rule label and all other required field
Click on Configure rules tab and in access conditions you can add your conditions


Create an alias that looks something like one of the examples below:

Drush 9 Example: ~/.drush/sites/my-site.yml

live:
  uri: example.com
  host: isp.net
  user: www-admin
  paths:
    drush-script: /path/to/drush
  ssh:
    options: '-p 2222 -o "AddressFamily inet"'
    tty: false

Drush 8 Example ~/.drush/aliases.drushrc.php

$aliases["my-site.live"] = array (
  'uri' => 'example.com',
  'remote-host' => 'isp.net',
  'remote-user' => 'www-admin',
  'ssh-options' => '-p 2234 -o "AddressFamily inet"',
  'path-aliases' =>
    array (
      '%drush-script' => '/path/to/drush',
    ),
);

Adjust 'ssh-options' as necessary for your configuration.

You may omit 'path-aliases' entirely if Drush is in your $PATH on the remote machine. Defining the Drush path is safer, though; the rules Bash follows for sourcing resource files for login shells vs. non-login shells et. al. is somewhat confusing.


OK, the information is stored in the node associated with the user, and not the user itself.

You essentially need to query the database to find the node for the user, load it, edit the fields, and then save out the node.

It would roughly look  like

$sql = "
  SELECT nid FROM {node}
  WHERE type = '%s' AND uid = %d AND status = %d
";

$nid = (int) db_result(db_query($sql, "profile", $user->uid, 1));

$node = node_load($nid);

$node->field_foo[0]["value"] = "foo";

node_save($node);

This is a copy/edit/paste from a project of mine, so error checking and other steps have been omitted, and the code may not run as-is.


Per this line in admin_menu.info:

dependencies[] = system (>7.10)

The module requires a core version of Drupal greater than 7.10. Currently yours must be less than that.

Drupal core is currently at 7.26; you'd be wise to update ASAP, there have been a number of security updates in recent memory.


Getting the value of a checkbox in form api

I found the answer.  I added '#tree' => TRUE, to the fieldset and suddenly things are working correctly.  I think because of the eventKeys were repeated so overwriting others. By adding the tree attribute, all the checkboxes were seperated into their respective fieldsets in the $form_state['values'] array.


Best way to migrate content and various other changes from development to production

The most user friendly way to do the content migration you are talking about is by using the Backup and Migrate module.

You'll want to upload and enable the module on both development and production instances. The project page links to this tutorial series for a more detailed explanation. I also saw a helper module that backs up your files directory too.

Features does in fact allow you to quickly import a "feature" to a website that you may have developed on your development environment and want to move to production.

Ideally though, you'd want to use features to develop locally and then push to dev/staging server. The final push you'd want to just replicate the database from dev/staging to lessen the chance of configuration errors.

You could also use Drush if you want to do more advanced operations. You can write your own Drush commands and with aliases you can have this down to one command in a terminal if you'de want to. You can rsync files, sqlsync the databases, and use features commands to sync configuration options. Drupalize.me has a nice series on some of this stuff.

I highly recommend Drush, if you are getting more into Drupal, and also recommend checking out Drupal 8's CMI initiative for what lies ahead: https://groups.drupal.org/build-systems-change-management/cmi

P.S. I would have posted more links but don't have the reputation yet to do so. So, just Google the missing pieces.


redirect based on content type using rules

That's happening because you're reacting on the content is viewed event, which means everytime a content of the type you're describing in the conditions is displayed. You need to extend more those conditions to add the search context.

You can either compare with the site path with a "Data comparison" condition on  site:current-page:path to node/[node:nid]

A better solution would be to filter out the view mode, I'm guessing you're looking for reacting on the "Full" view mode of the node, so just add a "Data comparison" condition on view-mode and set it to Full content

Something very similar has been answered before in: How to set Rules event for "Content is viewed" from excluding Teaser view?

In any case, if you want a node type to not have a final page, I recommend the Rabbit hole module.