If your index.php file is different from the default one, then it has been changed from somebody.
Updates to modules don't alter the content of that file. If there is a module that tries to alter the content of index.php, that is not the correct behavior for that module.

I would check that the permissions of the system user used to run the server, and PHP, don't allow it to alter any file contained in the Drupal root directory, and in its sub-directories.

In Drupal 6, the content of index.php is the following one. It is 39-line long, it includes an empty line after drupal_page_footer();, and it doesn't have any closing tag (?>).

<?php

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * The routines here dispatch control to the appropriate handler, which then
 * prints the appropriate page.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt.
 */

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();


Your problem is node_unpublish will be saving the node, triggering the second rule on node_update--article thereby actioning mimemail_to_users_of_role

Looks like you'll need to add a condition to make sure the email should be sent. For example, you could check the updated node is not being set to "unpublished"

"IF" : [ { "data_is" : { "data" : [ "node:status" ], "value" : "1" } } ],


So I had a couple of people asking about this here and on drupal.org - so I figured it would be easier to just tell you what I did.

in commerce_sagepay/inc/commerce_sagepay_server.inc around line 120 there is a piece of code that reads:

  '#markup' => '<iframe style="width: 600px; height:500px" scrolling="no" frameborder="0" name="iframe_sagepay" id="iframe_sagepay" src="' . url('commerce_sagepay/sagepay_waiting_page') . '" />',

I changed this line to

  '#markup' => '<iframe style="width: 600px; height:500px" scrolling="no" frameborder="0" name="iframe_sagepay" id="iframe_sagepay" src="' . url('commerce_sagepay/sagepay_waiting_page') . '"></iframe>',

in other words - explicit close the iframe tag.  It solved the problem for me.

Hope this helps someone.


Since you are using Panels, you could create two variants. One of them would have a selection rule that says only select this variant if "accept" is flagged, and in it your display only the complete flag. The other variant wouldn't need selection rules (but would need to be placed under the first one in the variants order) and it would display only the complete flag.


How to set a conditional webform to copy the value of a field to another?

webform sameas

  this module makes a "Same As" component available for use on your
  webforms. This component allows you to add a "Same as" checkbox to a
  form allowing you to indicates that one set of fields should have the
  same value as another set of fields. For example, if you had fields
  for both a Billing and Shipping address on your webform, you could add
  the Same As component to allow users to only fill out their billing
  address if their shipping address is the same.


go to phpmyadmin database ->

go to table -> ' simplenews_newsletter '

Sent newsletter will have status 2, pending will have 1 and not sent will be 0.

edit and change the status of that newsletter to 0

Hurrey!!!! send it again :)


How can I display nodes in a view both by title and by a short title

The only way to do this is going to be to create either a custom entity or at least a custom table with Views integration.  Views is designed to list one record per entity (or "row" of data).

Custom code solution:

Create a table that actually has multiple rows per node.  It would need at least 2 fields: nid and title, and you'd have to maintain the data in that table by implementing hook_node_update, hook_node_insert, and hook_node_delete.  Then you'd need to expose that data to views either by defining a custom entity type based on that table, or by writing the Views integration directly.

Field Collection Approach:

You could store your titles on another entity in the system.  A Field Collection is probably the best due to the fact that it won't clutter up any other parts of the interface.

The general idea would be to add a Field Collection field (field_alternate_titles?) to your disease entity.  The Field Collection itself really only needs a single field (field_alternate_titles_title?) with cardinality equal to 1.  You're not using Field Collection because of its ability to let you group fields together, but rather because it creates separate entities for each of your values that you can use Views to query against.  You can set the cardinality for the Field Collection field (field_alternate_titles) to 2 or, if you want to allow an arbitrary number of alternate titles, unlimited.

You could stop now and keep things really simple.  Your users would have to enter all of the titles that they'd possibly want for the disease in this field.  This would require them to re-enter the node title as an additional entry in the Field Collection field, but it would save you from writing any code.

If you want a slicker user experience then you would probably want to do the following:

Hide the Field Collection field on the disease node edit form by
using the available widget type of "hidden" (rather than
"embedded").  You don't want your users seeing or touching the field
in the edit form as you'll be maintaining the values for them.
Maintain the values in that field by implementing hook_node_presave
and creating and relating your node to Field Collection entities
according to the values entered for the node title and short title.

Whether you write the code to auto-populate the Field Collection values or not, you'll now need to build your view based on Field Collection as the base table rather than the Content (node) table.  You can add a relationship to the host node entity so that you can grab whatever info you need from the node.

Search Index Approach:

Another possible approach would be to use something like Search API which maintains a separate index of your content which you can muck about with when content is sent to the index.  So you could create separate index entries for every title you want to be able to search/list by.  You may find it helpful to use this module as a starting point as it does denormalization, which is what you're after: https://www.drupal.org/project/search_api_grouping


How to login when you have a default page setup with panels?

If you have access to drush, you can generate a one time login link use drush >    uli. Other than that, I'm not sure other than manually restoring to a back-up - lukedekker

Awesome!  That worked.  I was trying something else the other day with drush that wasn't producing results.


How to only define hook_menu path to certain URL

Per the hook_menu() docs:

  When path 'abc/def' is requested, no further path components are in
  the request, and no additional arguments are passed to the callback
  function (so $ghi and $jkl would take the default values as defined in
  the function signature). When 'abc/def/123/foo' is requested, $ghi
  will be '123' and $jkl will be 'foo'. Note that this automatic passing
  of optional path arguments applies only to page and theme callback
  functions.

In other words, it's a feature of the Drupal menu routing system to accept additional path components.

If you're looking to try to circumvent this, you can use an access callback function to enforce your sole path:

/**
 * implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_callback',
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

/**
 * Access callback for /hello. 403 on addition path components.
 */
function helloworld_callback() {
  return (request_path() == 'hello');
}


Theme the login page for Maintenance mode

If you want the login page to look different when you are in maintenance mode you theme it by checking the maintenance mode variable like this:

if (variable_get('maintenance_mode', 0)) {
  // Do something because it is maintenance mode.
}

For example, in your page template you could do this:

/**
 * Preprocess variables for the page template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  if (variable_get('maintenance_mode', 0)) {
    // Add a template suggestion for pages that are not the maintenance
    // page, while the site is in maintenance mode.
    $variables['theme_hook_suggestion'][] = 'page__inmaintenancemode';
  }
}

Then you could make a page--inmaintenancemode.tpl.php file, that could be used to theme any pages that are visible while in maintenance mode.
Be aware though that this will then affect all pages you see when you are logged in during maintenance mode, so you might want to change the line that check for maintenance mode to:

if (variable_get('maintenance_mode', 0) && user_is_logged_in()) {

You can do the same check in hook_form_alter() or in other template preprocessors, or anywhere else you are modifying content.


Drupal 7 Views Organic Groups Complex Relationship

This worked for me....

Create two relationship:

OG membership from node
Group node from OG membership (Relate to
Above)

Filter by Content Type and use relationship Group node from OG membership.


You return a RedirectResponse() with the path. If you're in a controller, you can use the redirect() method from ControllerBase.


How to hide specific fields and the according label in a view, based on field permissions?

On the Name field's edit config popup, remove the text from the Label field and disable the label checkbox; expand the Rewriting section, and paste in the label followed by the name field's  substitution pattern.... it will look something like this Name: [field_name].  Finally,  ensure the option to disable rewriting when field is empty checkbox is checked.


Have it working now :)
made 2views 1taxonomy view and 1profile view and renamed the taxonomypath to something else.
and rewrite the taxonomy-name url in the taxonomy view


There is a bug in your URL snippet (syntax error), so I'm writing the code.

<?php
$adopt_me_link_male = l(
  t('Adopt @name',
    array('@name' => $node->field_pet_name['und'][0]['safe_value']), //t() function replacements array
    array('context' => 'Male pet name') //t() function options array. Not necessary in this case though.
    ),
  'node/163', // l() function - URL
  array(
    'query' => array(
      'edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]' => $node->field_pet_name['und'][0]['safe_value'],
    ),
    'attributes' => array(
      'class' => array('btn', 'btn-primary', 'btn-xs'),
    ),
  )
);

?>

In this example, I changed !name to @name for the security (Read t() function documentation). Also, if you want to use HTML inside the anchor (say, an image), you have to pass 'html' => TRUE the last parameter array in the l() function (add it along with the attributes and query array keys).


Gettting errors after install drupal-8.2.6.nl.po

(copying from my comment)

Sounds like your public file system is not writable, which is necessary to generate translation files for JS. When you get an error like this, always check the status report page.


Benefit of config entities over regular config entries?

A config entity is useful when there need to be multiple variations of the configuration, think views, image styles, or node bundles. If there is no need to create variations, as in system.site which stores the site's basic information or core.extensions which stores the list of enabled modules, a basic config entry is appropriate.


How can I update user data whenever a user account is saved in PHP?

The problem there is you're creating an endless loop.

user_save calls hook_user_update, your hook_user_update calls user_save.... you get the picture.

A better approach would be to use

hook_user_presave

to add the field, then you don't need to worry about saving the account, as the user module will do that for you after the field is added.

The downside is, the uid isn't available in presave (for new accounts), though for a zodiac sign, I assume that's not required.


I don't have much experience in Drupal 8. Please refer my suggestion bellow.

Please add wrapper item for the ajax call
eg:

$form['flat_per_floor'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Flat Per Floor'),
    '#default_value' => $flatPerFloor,
    '#ajax' => array(
        'callback' => 'Drupal\bms_flat\Form\FlatForm::flatGenerate',
        'effect' => 'fade',
        'event' => 'change',
        'method' => 'replace',
        'progress' => array(
            'type' => 'throbber',
            'message' => "Generating..",
        ),
        'wrapper' => 'flat-per-floor-wrapper',
    ),
);

Add the wrapper container under the flat_per_floor field

$form['flat_per_floor_wrapper'] =  array(
  '#type' => 'container',
  '#attributes' => ['id' => 'flat-per-floor-wrapper']
);

For more details please refer the example module for drupal 8 and check the ajax form
https://www.drupal.org/project/examples


Where should I begin in creating a page to allow authenticated users to submit a short story that will become it's own independent page?

Hope this gets you off the ground. Of course you need some more reading/googling.

Give users the right to register an account on your site.
Create a content type with all the fields you need. You can do this with the built in fields features.
Create a role that has the right to create/edit/delete a this content type. This is a drupal core feature as well.
Assign a role to this users up on register (auto assign role module).
Make sure nice descritptive URLs are created automatically from the node titles (and maybe some fields) (path auto module)
Done.


How to call fields individually like this in Twig template?

In my node twig template file I have this which works for me:

{{ content.field_name|field_label }}
{{ content.field_name|field_value }}

This works if the twig_field_value module is enabled.


Another example:
As with all referenced entities you can load them quickly using the referencedEntities() method.

Also, if you are not using the Devel module and Devel Kint submodule, you should check it out. You can then use ksm() to explore variables and see available methods.

function hook_preprocess_node(&$variables) {

  //make sure you have Devel module installed, then you can use ksm() to explore variables
  //ksm($variables['node']);

  if ($variables['node']->hasField('field_permit_city')) {
    //this will give you the referenced terms on the node as objects
    $term_objects = $variables['node']->get('field_permit_city')->referencedEntities();
    $term_labels = [];
    foreach ($term_objects as $term_object) {
      print $term_object->id(); //the id of the term
      print $term_object->label(); //the term title
      $term_labels[] = $term_object->label(); //build an array of term labels
    }
    //send an array of term titles over to the node twig template
    $variables['my_custom_template_variable'] = $term_labels;
  }
}

Then in your node.html.twig template you can iterate through the labels and do the stuff.

{% for term in my_custom_template_variable %}
    <p>{{ term }}</p>
{% endfor %}


You need to make sure the number of MySQL connections (max_connections in my.cnf) is greater than the number of PHP processes (pm.max_children if you use php-fpm, or MaxClients if you're using Apache mod_php).

The default for Apache is often 300, and the MySQL default is only 100, so you can run out of connections pretty quickly if these values aren't tuned.


How to specify multiple submit handlers for multiple forms

You can specify a submit handler for each of your forms. Examples:

Override default handler with custom handler (new array):

$form['#submit'] = array('data_retrieval_form_submit');

Run custom handler after default (append to array):

$form['#submit'][] = 'data_retrieval_form_submit';

Run custom handler before default (prepend array):

array_unshift($form['#submit'], 'data_retrieval_form_submit');

You can add it to the $form array in a custom form builder function, or alter an existing form via hook_form_alter.


Unable to debug drush command using xdebug with batch api

You're debugging your script using IDE which require valid xdebug.idekey to be present in the session which probably isn't passed correctly to the forked process.

It's probably the bug of XDebug (see: #938) which doesn't debug well the forked processes.

I assume you've xdebug.remote_port working correctly and there is no any communication issue. Remote debugging generates log file (defined by xdebug.remote_log), so you should check further debugger communications details there.

As for workaround, you should debug your script manually by calling the functions: xdebug_start_trace() and xdebug_stop_trace().

In case debugging on demand won't work with forked processes, enable xdebug.auto_trace, restart Apache, so all forked processes can be debugged properly which will generate huge trace file which you can analyze (defined by xdebug.trace_output_dir/xdebug.trace_output_name).

Check my xdebug.ini for suggestions, especially these settings are useful to see all the details:

; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=200        ; int: Controls the protection mechanism for infinite recursion protection.

If XDebug still won't work, then consider using phpdbg instead.

For suggestions how to debug Batch API process, see: How to debug Batch API more efficiently?


How can I make my ubercart catalog content available to users?

Since you mention that authenticated users can't access your Product nodes, it's most likely that your nodes aren't published, or that there is a module interfering with the access check.

First, check if your nodes are actually published, on the Create or Edit form:

Second, go to /admin/people/permissions and check if anonymous users have the View published content permission.

Third, are you using any modules like Node Access that might alter the access permissions?


Here is how you can get the list field key and value

function themename_preprocess_field(&$variables, $hook) {

    if ($variables['field_name'] == 'field_test') {

        foreach ($variables['items'] as $key => $item) {
            $list_field_value = $item['content']['#markup'];
            $list_field_key = $variables['element']['#items'][$key]->getString();
        }

    }

}

Note: replace field_test with the actual field machine name, do not replace field_name.


Is there a way I can display one image field if another one does not exist using visibility rules in node template?

I would suggest using views to create a block based on the filter criteria where the first image field is empty.


This solved my problem.

chmod 775 /var/lib/mysql


Multisite, shared users, own databases, own files, how to deal with profile picture?

You need a single sign on approach.
You could implement your own approach just like this one https://drupal.org/node/1043724 or try to find some contribute module to handle it.
Hope this help.
Regards


Best approach to wrap rendered file field in a link?

I would create a custom field formatter for rendering the cck field itself. Look for hook_field_formatter_info, hook_field_formatter_view and implement your own custom module

There is also this module https://drupal.org/project/custom_formatters you might want to check out.


Try something like the following:

$form['my_captcha_element'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

More info here :https://www.drupal.org/node/743056


By default the command drush archive-restore creates a unique temporary folder under /tmp (*/tmp/drush_tmp_1394487346_531e303223...*) where it will extract the archived tarball content, and later will move the $doc_root into the $destination - with the option overwrite.

I guess your /tmp folder resides on a separate partition, ~4GB in size; restoring a 3GB archive worked well, but it fails for 5BG. It looks like drush archive-restore works only when the system's temp folder is large enough to accommodate the extracted tarball.

PS. drush archive-restore is defined in archive.drush.inc :

function "drush_archive_restore" (drush_tarball_extract($file, $tmp)), where $tmp = drush_tempdir();

Funtion drush_tempdir() is defined in filesystem.inc - creates a unique temporary directory  and returns its path. drush_tempdir() uses drush_find_tmp() which more likely returns /tmp


Drush doesn't support field commands for Drupal 8 yet. The error message is caused by the fact that Drupal 8 no longer has a function field_info_field() - see Drupal change record at https://www.drupal.org/node/2260037

Drush issue at https://github.com/drush-ops/drush/issues/230


Attach webform on each node of specified content type

I had the same question and found answer in drupal community, that was using of Webform Default Fields module.

Here are a brief description about this module :

  Description

  With this module you can easily create a lot of nodes with same webform fields. It can be applicable in case of job vacancies with reply form, kind of quality feedback control or whatever your mind suggests you.

  Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.


You can use Display Suite module to create custom view mode for search results.


Allow another role to edit only parts of any node

The Field Permissions module will allow you to do exactly this.

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


Moving the fields and data from one content type to another content type

you can definitely accomplish this with the migrate module (https://www.drupal.org/project/migrate). Your source DB and your destination DB will be the same, but that is acceptable. You're essentially migrating ContentA nodes into ContentB nodes and since they both have the same fields the mapping should be very simple.


How can I create multiple dashboards with Open Atrium?

Users with sufficient permissions should see an "Add custom" link on the Dashboard.  This link lets you create additional Dashboards for a single group, each with its own content and layout.


Ajax replaced elements not available in form submit callback

I received some help on Drupal.org about this... Jaypan's helpful reply is at https://www.drupal.org/node/2563045. I've posted a comment there to show how I got this working eventually.


How to change textformat of many nodes at once?

In previous instances where this has happened to me, I've just updated the *_format column in the field_revision_* & field_data_* tables, flushed the Drupal cache, and things worked without issue.

For example, if you're looking to change the nodes' body format for all imported nodes of type my_type from my_format to plain_text, you could execute this query:

UPDATE field_data_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';
UPDATE field_revision_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';

NOTE: There's probably a better, programmatic way, than touching the database directly, but I've never seen any adverse effects from this method.


You'll have to follow the trail in the DPM structure. The url field is under the #element element. The #element element is under the 0 element. This means you can access the value of url with:

$items[0]['#element']['url'];

You can reach the title element in a similar way.

The value of #theme is directly under the 0 element, that is why you could access it with:

$items[0]['#theme']


This seems to be solved by drupal community:
https://drupal.org/node/2112281#comment-7971057


Migrating paragraph items to their host nodes from Drupal 7 to Drupal 9?

I was thinking about this in the wrong way. The source plugin returns a list of results to migrate one at a time - the SQL query I was using would cause you to get for example, 5 rows for one node, each with a paragraph id. That is why only one paragraph was showing up on nodes at the end of a migration.
That isn't what you want - what you want instead is one row with the node id and 5 paragraph IDs.
I was able to do that by adjusting my source plugin query to the following:
  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('node', 'n');
    $query->join('D7_FIELD_NAME', 'fc', 'fc.entity_id = n.nid');
    $query->fields('n', [
      'nid',
      'title'
    ]);
    $query->condition('n.status', 1);
    $query->addExpression('GROUP_CONCAT(fc.D7_FIELD_NAME_VALUE)', 'paragraph_ids');
    $query->groupBy('n.nid');
    $query->groupBy('n.title');
    $query->orderBy('fc.delta');
    return $query;
  }

This produces a result set of
nid | paragraph_ids
-------------------
1     2, 4, 6, 8
2     13, 18, 12, 9
...........

Once you have that part, then you can fill in your Migration definition:
  D9_DESTINATION_FIELD_NAME:
    - plugin: explode
      delimiter: ','
      source: paragraph_ids
    - plugin: to_array
    - plugin: sub_process
      process:
        target_id:
          - plugin: migration_lookup
            migration:
              - accordion_items_paragraph
              - editor_items
              - highlight_files
            source: value
          - plugin: extract
            index:
              - 0
        target_revision_id:
          - plugin: migration_lookup
            migration:
              - accordion_items_paragraph
              - editor_items
              - highlight_files
            source: value
          - plugin: extract
            index:
              - 1

explode changes the comma delimited list into an array, and to_array is a small plugin I made to make it an array of arrays, each with an index of "value" and the id.
sub_process iterates over that and does a lookup against my other 3 paragraph migrations to drop the new destination id into target_id and target_revision_id.
The nid mapping from the original question still works, and passing multiple node migrations provides the full lookup capability. So for any nodes the result set returns, they are updated accordingly.
Now all migrated Paragraphs show up on their respective nodes in the correct order. I was able to apply this pattern to 3 different entity_reference_revision fields in Drupal 9 that held Paragraphs.


Unable to set a default value for a CCK field

Simply try by creating a new (text)field & choosing widget as select list.
then put in allowed values
0|a
1|b
2|c
(putting 0|a in one line,1|b in other so on..)
& number of values to unlimited & save
by editing, select default values from drop down & save.
hope it helps..


In the end I got it working by changing the code to:

  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));
  drupal_add_js('misc/jquery.once.js', array(
    'group' => JS_LIBRARY,
    'weight' => -19,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));

This then meet the rules on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

First by scope, with 'header' first, 'footer' last, and any other scopes provided by a cust om theme coming in between, as determined by the theme.
Then by group.
Then by the 'every_page' flag, with TRUE coming before FALSE.
Then by weight.
Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.


How can I programatically log another user out in D7?

drupal_session_destroy_uid() sounds like a safe bet:

  Ends a specific user's session(s).

The core implementation clears the database, as you'd expect, but any module that overrides session.inc, and doesn't provide a working implementation of that function, would surely be considered broken (as user_delete_multiple() and other functions need it).

So in theory you should be able to use that function regardless of the storage.


For the latest version of Ultimate Cron, you also need the latest versions of Background Process and Progress. The versions might not match, or the database schema may not have been updated properly. Try completely uninstalling Ultimate Cron, Background Process and Progress, and then re-install them.


i finally worked this one out, I strppied the form right back and removed all the states and got the ajax call working first. This was a bit of a hack as I had to access the $_GET variable directly and using the following line I was able to check whether or not the page had already been searched.

if(isset($_GET['line_2'])) {
  $line_2_selected = $_GET['line_2'];
}
else{
$line_2_selected = isset($form_state['values']['line_2']) ? $form_state['values']['line_2'] : key($doc_line2_options);
}

After this the problem was either having the ajax selectively removed ot depending on the values in the parent checkboxes. What I actually did was add the same list twice and then disable one or the other depending on the value in the first checkbox. Doing this greatly reduced the complexity of the states array.

$form['line'] = array(
  '#type' => 'radios',
  '#options' => $doc_line_options,
  '#default_value' => $line_selected,
  '#title' => '',
  '#prefix' => '
',
  '#suffix' => '
',
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 31)
    ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 31)
      ),
  ),
);

$form['line_2'] = array(
  '#type' => 'radios',
  '#options' => $doc_line2_options,
  '#default_value' => $line_2_selected,
  '#title' => '',
  '#prefix' => '
',
  '#suffix' => '
',
  '#ajax' => array(
    'callback' => 'uk_general_forms_documents_products',
    'wrapper' => 'products-dropdown-replace',
    ),
  '#states' => array(
    'enabled' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    'visible' => array(
      ':input[name="type"]' => array('value' => 29)
      ),
    )
  );

The previous ajax functions all worked as expected.


Would a cached page be considered, solely by definition, RESTful?

If a page is cached or not is in my opinion completely irrelevant. Page caching is transparent to the user and the content, he doesn't know if it is and once the cache expires, he might get something different on the same page. A page could for example be a view that randomly displays a node. Enabling page caching (and the node only switches e.g. every 5 minutes) doesn't change anything.

RESTful is about having a 1-1 mapping between an URL and a resource (or maybe better: a representation of that resource, e.g. a different format). IMHO, it doesn't matter if..

authorization is necessary to have access to that resource (anon vs. authorized users)
Only a part of that resource is visible (e.g. someone with additional permissions might see more information)
If the displayed information changes, as long as it's the same resource on the same URL (e.g., a node could have an access counter that increases every time you view it.)
If there is some sort of caching involved, either page or partial caching.


Relation and Entity Share a Field / Reference Each Other

If you are talking about the Relation module, then you can use Rules to trigger entity updates whenever a relationship (which is also an entity) changes.

The workflow would be like this :

Trigger on entity update.
Check that entity is a relation.
Update linked entity.

Check the video documentation on Relation, there are two (1, 2) of them talking about Rules.


Getting the workflow associated to a node type

Workflows are configuration entities so you can load them using their id:

$workflow = $this->entityTypeManager->getStorage('workflow')->load('workflow_machine_name');

Or "query" them using the Entity Query (check the Drupal 8 example shown here):

$query = $this->entityTypeManager->getStorage('workflow')->getQuery();
$query->condition('type_settings.entity_types.node', 'article', 'IN');
$workflows = $query->execute();

The condition is a proof-of-concept drawn from another config entity query but is the right path you need to test it agains the workflow entity schema.


You can do this within a tpl file specific to your content type. In this case it sounds like it'd be node--page.tpl.php

All the drupal 7 template naming suggestions are available at - https://drupal.org/node/1089656

Just make sure you have a regular node.tpl.php file in your theme before creating the new one.

From there this thread tells you how to go about printing your field elsewhere (specific to drupal 7)- https://drupal.org/node/1059636

Specific to your question:

<?php
hide($content['field_my_image_field']);
print render($content);
?>

then wherever you want your image to appear at use

<?php
print render($content['field_my_image_field']);
?>


Views: how to achieve automatic pagination?

Try Views infinite scroll module.

  Views Infinite Scroll provides a #586668: Pluggable pagers that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.


Change field settings for text field from plain to formatted while data exists

Attention for Drupal 8:

You need to update at least 3 or 4 yml files

field.field.node.page.field_description.yml

(same change)

field.storage.node.field_description.yml

--- a/config/default/field.storage.node.field_description.yml
+++ b/config/default/field.storage.node.field_description.yml
@@ -4,13 +4,13 @@
 dependencies:
   module:
     - node
+    - text
 id: node.field_description
 field_name: field_description
 entity_type: node
-type: string_long
-settings:
-  case_sensitive: false
-module: core
+type: text_long
+settings: {  }
+module: text
 locked: false
 cardinality: 1
 translatable: true

core.entity_form_display.node.page.default.yml

-type: string_textarea
+type: text_textarea

core.entity_view_display.node.page.default.yml

-type: basic_string
+type: text_default

Maybe the last 2 ones you can deal with those changes on UI(go to each teaser and save). But I did in config folder.


Moving SQLite-D7 Installation to other Server throws Uncaught exception in shutdown function

It seems that the PDO SQLite driver requires that if you are going to do a write operation (INSERT,UPDATE,DELETE,DROP, etc), then the folder the database resides in must have write permissions, as well as the actual database file.

The above information is taken from another answer: https://stackoverflow.com/a/3330616/2171489

I don't use SQLite, but given the error from the PDO driver and the fact that you moved to a different server, it does seem like it could be a file permission problem.


Drupal Commerce add to cart is no longer working for anonymous users

Commerce Kickstart added these lines to the /profiles/commerce-kickstart/.gitignore which prevented new files from being added to git and thus not getting pushed to production.

libraries
modules/contrib
themes/contrib

https://www.drupal.org/project/commerce_kickstart/issues/2937535


Tabular data in Drupal: create a field with multiple attributes

You should look at the Field Collection module, which allows you to make groups of fields and reuse them in a content type like a single field. So in your case, each collection might contain the fields "stage," "completed" (checkbox), "reference," and "notes," and then you could use that field collection multiple times throughout your content type.


Cookie not being created (not a schoolboy error, I hope)

The world has not turned upside-down.

It turned out that Zeus was indeed eating cookies of anonymous accesses, I had to go through every Zeus rule (we have a lot) until I found it.

Testing with Zeus bypassed demonstrated the cookies were created correctly.

Bloody Greek Gods, wandering in uninvited and eating all the cookies...


Drush decides whether a site is local or remote via the function drush_is_local_host.  Make up a domain name for your system, such as foo.local, and make an entry for it in /etc/hosts (123.456.78.90 foo.local).  Next, make sure that /etc/hostname also contains foo.local, and confirm this by running hostname -f.  If you do all of this correctly, then you can set 'remote-host' => 'foo.local', and Drush will still treat it like localhost for commands such as sql-sync.


How to make the title field of a node/add form hidden or locked

I'd probably just hide it with CSS to be honest.
Either that, or I'd use Automatic Nodetitles to populate the title with tokens (path token in your case) as it has the option to hide the title field AND auto-generate it with minimal effort.

"auto_nodetitle" is a small and efficient module that allows hiding of
the content title field in the form. To prevent empty content title
fields one can configure it to generate the title by a given pattern.
When the token module is installed it's possible to use various node
data for the auto generated title - e.g. use the text of a CCK field
(since 5.x).

Another option would be to use hook_form_alter() and set #disabled to TRUE to disable user input.


More than one modules implementing the hook_module_implements_alter

You need to change the weight of the modules in system table to modify their execution order.

One module that can help you in that is the Modules Weight, which provides an admin interface and avoids changing the SQL record directly.


Where are the field labels and descriptions stored?

You can try something like this :-

$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$field_label = $node->field_file->getFieldDefinition()->getLabel();
$field_desc = $node->field_file->getFieldDefinition()->getDescription();
$field_settings = $node->field_file->getFieldDefinition()->getSettings();
}


Adding a views block to a menu? Or adding a menu to a views block?

To make views show up inside a menu you can use Menu Views. If you only require the functionality your described it's the simplest and easiest way to do it.


How to add classes to a specific bean w/ display suite template

A friend helped me solve this one. All I needed was the following PHP as a container class.

<?php print $zebra; ?>

I can now style the .odd containers!

Thanks all


how to do addition of two field values in drupal 7during node_presave?

function my_module_node_presave($node){  // implementation of hook_node_presave
  if($node->type == 'add_stock') {
    $product = $node->field_stock_value['und'][0]['value']; //get data value of field
    drupal_set_message('product :'.$product); // print data value for checking
    $nid = $node->field_reference['und'][0]['nid']; //get nid of reference field
    drupal_set_message('nid :'.$nid); // print nid
    $p_node = node_load($nid); // implemenet node_load and get in $p_node
    $stock = $p_node->field_product_stock['und'][0]['value']; //get data value of field
    drupal_set_message('stock :'.$stock); // print value

    $stock = $product + $stock; // addition of both value
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock; // updating the product field with updated value
    node_save($p_node); // implement node_save
  }
}


How to increase the performance of my website in Drupal 7

You can guess all you want and experiment, but the only way to actually achieve meaningful results is to profile the system to figure out where the bottlenecks are.   There are many ways to accomlish this.

You can use the Performance module to identify slow pages.

You can use xhprof and the Devel module to identify memory problems, and show slow functions and queries.

Are you running APC?  If not, you should.  Stick the apc.php file somewhere safe and check the statistics to make sure you don't have cache churn.

Install DB Tuner and see what the mysqltuner results and recommendations are, particularly with regards to buffer sizes and query cache size.

You can also read up on profiling and optimizing Apache

You could also experiment with Zend Server CE as it includes a PHP optimizer in addition to opcode caching.


Drupals render arrays are a great invention which make it possible to alter the output of content by others (modules, themes etc.).

If you would hard-code your output in variables to print, no one other can alter it. But if you use render arrays, then other modules can implement hooks to alter the rendering of your output if they need to do so.

For this flexibility it is best practice to use render arrays until the very last moment and let the twig template build the html from it.


Core updates and module updates: Does order matter?

Order does matter.

Sadly, it's hard to tell exactly how it will matter in your situation. If you can, make a dev copy of this site and experiment on it. I would either go with core-first or with all at once. But that's my intuition, and actual tests on a copy of actual site matters much more.

Usually it's OK to jump all versions in-between the one you have and most recent one. For modules, sometimes, rarely, it's good to use most-recent minor version and don't install next major version at all (if both are maintained), or install most-recent minor and then update major. Sadly, it's different for each module, so fastest thing would be to update everything straight to the recent version, and see if / what broke. Of course, this is only feasible on a dev copy, not production.


When saving an updated node, does the update operation clear all caches?

There is only one line about clearing cache in node_save():

// Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

It only resets entity-related cache. Caches related to another nodes, caches like boost and so on are left untouched, unless specifically cleared by other module's actions in node or entity saving hooks.


Implementing a callback after user registration

A way is add a submit function to user_register_form submits in form alter.

yourmodule_form_alter(&$from,$form_state,$form_id) {
  if ($form_id == 'user_register_form ) {
       $form['#submit'][] = 'sugar_crm_user_register_submit';
       }
 }

but I think the better way is setup your custom function in hook_user_insert.this hook triggered when a user registered . you can implement it in your custom module.

  function yourmodule_user_insert(&$edit, $account, $category) {
   // some code to run a database query in SugarCRM
  ddl("User registration form submitted to CRM");
  }


what's are these "@name" and "@site-name" token-things in email_example.module and how do they work?

Please refer to the official D8 Sanitizing Output Documentation.

From the documentation page

There are three available placeholders in Drupal 8:

@variable: When the placeholder replacement value is a string or a MarkupInterface object
%variable: When the placeholder replacement value is to be wrapped in em tags.
:variable: When the placeholder replacement value is a URL to be used in the "href" attribute

You can learn more about these placeholders in the FormattableMarkup::placeholderFormat() documentation.

EDIT FOR DRUPAL 7:

See this documentation https://www.drupal.org/docs/7/api/localization-api/dynamic-strings-with-placeholders

The variables/tokens available for use as replacements is dependent on the context of the surrounding code and whether or not the script is called via Apache or from the command line.


How to change content url content/title to text/title?

You probably have to delete and then bulk create them from the admin/config/search/path/delete_bulk and admin/config/search/path/update_bulk pages.

Be careful though if there are links pointing towards pages.


Commerce Flat Rate Shipping not being added in Paypal Express Checkout

Did you enable shipping service selection in the order confirmation
  checkout pane provided by the PayPal Express Checkout module? – Ryan
  Szrama

Thanks again Ryan for pointing out another not so obvious answer!

To "enable shipping service selection in the order confirmation checkout pane provided by the PayPal Express Checkout module"

Go to:
admin/commerce/config/checkout/form/pane/paypal_ec_review

"Checkout pane configuration
These settings are specific to this checkout pane.
Checkout panes to include on the Express Checkout review and confirm page"

Check this box! - Shipping service

Ralph Manis - Infinitee Web Design


How can I change the number of items in a view only for the first page?

This is how I got it working, use two hooks. Assuming we have a view called my_view and the display is page_1.
Pre-build: Set the items per page to 10 for the first page.
Pre-render: Add an additional CSS class to the view.
/**
 * Implements hook_views_pre_build().
 */
function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1') {
    // Page is zero indexed: first page is NULL or 0.
    if (!$view->getRequest()->query->get('page')) {
      // Default is 9, we set it to 10.
      $view->setItemsPerPage(10);
    }
    else {
      // Set the offset on subsequent pages, because we have one more on the first page.
      $view->setOffset(1);
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() === 'my_view' && $view->current_display === 'page_1' && !$view->getCurrentPage()) {
    // Add CSS class for first page.
    $view->display_handler->setOption(
      'css_class',
      $view->display_handler->getOption('css_class') . ' is-first-page'
    );

    // To attach a library, use:
    // $view->element['#attached']['library'][] = 'my_module/view-first-page';
  }
}


You can use Entity Reference module to create relations between the nodes you need.

https://www.drupal.org/project/entityreference

And it works well with Views (for both forward and backward references)


Drupal 6 - form submission data loss from empty required fields

This is the default behavior, but I agree that it would be a irritating issue.

Perhaps if you did something like a warning message at the top when the user loads a previously edited node that has empty fields that are now required? That would get them looking at it from the get go. form_alter could do this for you.

Adding some pretty CSS on the page to highlight the empty required fields would also help guide them to the fields where their input is required.


Why isn't my hook_theme being called or rendering output?

I had to add a path to my function, then it worked.

template.php

function my_name_theme($existing, $type, $theme, $path) {
    return array(
        'testy' => array(
            'variables' => array('title' => NULL),
            'template'  => 'testy',
            'path'      => drupal_get_path('theme', 'my_name') . '/templates',
        ),
    );
}


Can I edit theme CSS without FTP access to the files?

Without server access of some description either via FTP or SSH (for example) - you can't edit the files.

You could, however, try CSS Injector if you are able to install modules through the UI.

  Allows administrators to inject CSS into the page output based on
  configurable rules. It's useful for adding simple CSS tweaks without
  modifying a site's official theme -- for example, a 'nighttime' color
  scheme could be added during certain hours. The CSS is added using
  Drupal's standard drupal_add_css() function and respects page caching,
  etc.


The syntax is ubercart hook order

hook_uc_order($op, $order, $arg2)

Clear your site cache from performance page, The hook is fired for me after clearing the cache.


drupal 7 PDOException error saying I'm missing a table or view mysite_drupal.cache_views

Yes, if cache_views is missing and you have the Views module installed, you need to create it.

To do so, simply duplicate the standard cache table and rename it to cache_views; they share the same columns.

You might also need to re-create the cache_views_data table, also with the same columns.


Tokens for the current user [current-user:*] don't need any data. Leave the array empty.

What you might referring to are tokens for any user [user:*]. They need an account as parameter 'user'.


Drupal 7 GetLocations field geocoding off?

The API geocoder may be different from the Maps geocoder (see the FAQ in the API documentation). The results may even vary for users from different users from different countries. For me, Spier Wine Farm, Stellenbosch results on Google Maps in -33.9733628,18.7825561.

In general, it seems that sometimes providing less information in an address results in more exact coordinates, see this similar question on s.o.

UPDATE: Interesting fact: the same address produces even different coordinates for different browsers. Coordinates stated above came from Google Chrome. When doing the same in Mozilla Firefox, I get -33.973474,18.782544 (which is what you had in your question).


Custom service returns "401 (Unauthorized : Missing required argument merchant_id)"

You have to use the POST method in the sync_contacts_get_customers_list function:

options.method = 'POST';

Without this, you aren't "posting" anything up to Drupal Services, so your resource in Drupal will not be delivered the merchant_id.

If you want to use a GET request, then I'd recommend using a Views JSON (from Views datasource) and a contextual filter(s), otherwise custom resources in Services always use POST AFAIK, unless you're building a CRUD interface for an Entity (e.g. Services Entity API).

Also the way you are defining your custom resource in Drupal is incorrect, use actions instead:

  $resources = array(
    'sync_contacts_resources' => array(
      'actions' => array(
        'get_contacts' => array(
          'help' => 'Get customers and their contacts',
          'file' => array('type' => 'inc', 'module' => 'sync_contacts', 'name' => 'resources/sync_contacts.resource'),
          'callback' => '_get_customer_contacts',
          'args' => array(
            array(
              'name' => 'merchant_id',
              'type' => 'int',
              'description' => t('Get customers and their contacts by merchant_id.'),
              'source' => array('data' => 'merchant_id'),
              'optional' => FALSE,
            ),
          ),
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'drupalgap',
            'name' => 'drupalgap.resource',
          ),
          'access callback' => '_sync_contacts_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );


How to control path alias in custom node form #validate function?

You will find the values submitted by the user in $form_state['values]. So you can just fetch the ones submitted alter them and them send them back to the form. And the path settings are located at $form['path']. $form_state['groups'] is just a way of grouping form elements together.

/**
 * Implements hook_node_form_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Add our validate function to all node forms.
  $form['#validate'][] = 'MYMODULE_alter_node_path';
}

/**
 * Custom form validate function.
 */
function MYMODULE_alter_node_path($form, &$form_state) {
  // Fetch the path values submitted.
  $value = $form_state['values']['path'];
  // Do your changes to the path and unset pathauto checkbox.
  $value['alias'] = 'new-alias';
  $value['pathauto'] = FALSE;
  // Set the values in the form.
  form_set_value($form['path'], $value, $form_state);
}


Programming Layout Changes into Theme Templates & CSS Files

Many existing themes already provide this kind of feature (usually using a preprocess function) so I would recommend looking at a theme like Zen or another popular base theme for examples of varying the page layout with a body class which specifies the overall structure of the page.


Error 500 when downloading updates for modules

It was PHP bug with Ubuntu 32bit.

I've solved the problem after installation of newer PHP version


How to use Rules to prevent the creation of nodes if certain conditions are true?

Out-of-the Rules module-box, I think there is no solution to "prevent node creation in rules?" (as in your question). However, without using custom code and custom PHP in your Rules conditions or actions and without deleting the node after it got created, you may get it to work if you also use the Rules Forms Support module.
More details about Rules Forms Support (from its project page):

Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
For help getting started with Rules Forms Support, please see the module documentation.
Features

Activate events for form creation, validation, and submission on a form-by-form basis.
Target individual form elements or the entire form in conditions and actions.
Manipulate the attributes of a form element like title, description, weight, and more.
Validate the values of form elements during form validation.
Set form errors when rule-based validation fails.
Redirect users to a different page upon viewing or submitting a form.
Examine the attributes of elements in active forms with the element inspection tool.

Especially the "Set form errors when rule-based validation fails" should help to address your question.
More details about how to use this module can be found in the community documentation "Altering & validating forms".


Do you have the .htaccess file from 8.x instead of the one from 7.x?
The directory structure of Drupal core changed from 7.x to 8.x, and 8.x includes additional mod_rewrite rules to redirect to the changed locations of update.php and install.php


How to store a single array value into a session variable?

<?php
//If you want store the value in a session, you need first start the session
session_start();
//I suposse that your array is named $array,
//then if you want get the position 1 use the following line
$_SESSION['var'] = $array[1];
//checking the stored value
echo $_SESSION['var'];

?>

Output:

  TN201501HP


Add referencing entities into this entities renderable array

Seems custom code was the easiest thing here after a bit of research...

function HOOK_taxonomy_term_view_alter(&$build) {
    if($build['#term']->vocabulary_machine_name=='bands') {
        $units = load_bands_members($build['#term']->tid);
        $build['units'] = array(
            '#markup' => theme('bands_members', array('members' => $members))
        );

    }
}

The function load_band_members returns an array of taxonomy terms and looks like this:

function load_band_members($tid) {
    $tids = db_query("SELECT tid
        FROM taxonomy_term_data td
        INNER JOIN field_data_field_band b ON b.entity_id = td.tid
        WHERE td.vid = 6 AND b.field_band_tid = :tid", array(':tid'=>$tid))->fetchCol();
    return $tids ? taxonomy_term_load_multiple($tids) : false;
}

I'm sure it would somehow be possible to get Drupal to render my band members for me, like it does on their own taxonomy term page, as opposed to me having to call my own custom render function but that will do for now...


Alter views limit using hook_views_query_alter

Try using the following:

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
    $view->set_items_per_page(2);
}


Override default drupal_set_message() on node creation

Change $form['buttons']['submit']['#submit'][0] to $form['actions']['submit']['#submit'][0] in your HOOK_form_alter().

I don't know why that tutorial has you modifying the $form['buttons'] array. Very few forms will put something as important as the primary Submit button outside of $form['actions'], and certainly not a core form.


How to disable delete once the thread has been started in advanced forum module in drupal 7?

You're looking for hook_node_access() where $op == 'delete'.

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7


How to add gratuity when a commerce cart is updated?

I would use the Rules module for this, with trigger event "add item to cart" and action being "add another product to the cart", where the second product is a gratuity. You might need to use a further rule to set the price of the "gratuity" product as proportional to the original product.

If you don't need to do it separately for each item, like if it's the same percentage for all, you could apply it as if it were a tax, a (negative) discount, or a handling fee, using the relevant modules for those.


How to specify the latest album in a images view?

I just ended up using "arguments" with a default PHP argument if one is not specified. The PHP code:

$res = db_query("select nid from node where type  = 'node_gallery_gallery' order by nid desc limit 1");
$res = db_fetch_object($res);
return $res->nid;

Works beautifully. Only side effect being that anyone that can access this view, can view other galleries using a parameters. But in my case that's not a problem.


Create a term reference with a select list selecting one at a time

You can do it using Field Collection module

Once enabled, go to your content type and add a new field of Type: Field Collection and set to 4 values.

Then go to /admin/structure/field-collections and click on manage fields and add your select list field here and set value to 1.

Result:

If you don't want to allow users to set the same value, then you will need to use jQuery to hide value "X" in the 2nd drop down if the 1st drop down is set to value "X"


Views contexual filter based on nid (not from URL)

Use the Views Field View module and add Content: Nid as a field and check mark ☑ exclude from display.

Add Global: View a field and pass [%nid] token/replacement pattern as an argument as contextual filter.

Note: make sure it's arranged above your View field view so you have access to the [%nid] replacement pattern/token.


For someone who might experience this, for me Minify module was causing this, I think I lacked some configuration to use minified JS, so my localhost couldn't load JS, after disabling Minify module, everything was fine. Not the best solution, but for fast results its okay.

P.S. DON'T FORGET TO ENABLE IT IF YOU TWEAK SOME JS CODE AND EXPORT IT AS FEATURE.


Error trying to update database after module update

The problem you are having is likely either that the RewriteBase is not set in .htaccess, or the base_url is not set in settings.php.  Likely you can bypass the settings problem if you go directly to http://omroepzuidplas.nl/update.php.

To do database updates you have to be logged in as User 1 (often called admin or super admin, but it could have any user name).


drupal 7: showing main menu links to anonymous users

First you need to install the Chaos tool suite (ctools) module, and enable the Page Manager module, and go to admin/structure/pages

Then we need to wrap whatever we are linking to in a Page, handled by the Page Manager. Exactly how we do that will differ a little bit depending on what we are linking to. The page manager contains many options, and I cannot describe all of them in detail here. You may want to watch this video introduction if you have never seen page manager or panels before. Videos 1 to 3 together are less than 30 minutes, and are likely necessary to make sense of the instructions below.

For nodes: Enable the node template.

For Views: Click "Add custom page", add the View in that page instead, and save.

For Module defined pages: Use Page manager existing pages to hand them over to the page manager.

For Something else entirely: Comment on the answer and tell me what it is, and I'll add instructions.

Now, in the Page manager interface for the page you enabled/created above do the following

Create a variant of type "HTTP response code".
Set the response code to 301.
Set the path to /user
Go to "Selection rules" in the left menu
Add "User:role" == "anonymous user"
Save


This is how I solved a similar problem with the hook_menu() and the use of 'title callback' and 'page callback'

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

    $items['link'] = array(
        'title' => 'test',
        'description' => t('Just a test'),
        'title callback' => 'change_title_link',
        'title arguments' => array(1),
        'page callback' => 'go_to_place',
        'page arguments' => array(1),
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

In this function you can change the link title

function change_title_link($gid) {
  if(og_is_member('node', $gid)) {
    return 'Post';
  }
  else {
    return 'Register';
  }
}

Here you can redirect to the desire url

function go_to_place($gid) {
  if(og_is_member('node', $gid)) {
    drupal_goto('/someplace/post');
  }
  else {
    drupal_goto('/someplace/register');
  }
}


If we inspect views_ui_edit_view_form() we can see the following #submit handler being assigned:

  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#validate' => array('views_ui_edit_view_form_validate'),
    '#submit' => array('views_ui_edit_view_form_submit'),
  );

Drilling further down into views_ui_edit_view_form_submit() it becomes clear which caches are affected by saving a view:

  // Make sure menu items get rebuilt as neces
  menu_rebuild();

  // Clear the views cache.
  cache_clear_all('*', 'cache_views');

  // Clear the page cache.
  cache_clear_all();

  // Remove this view from cache so we can edit it properly.
  views_object_cache_clear('view', $form_state['view']->name);

In summary, these are the caches that get cleared when a view gets saved:

menu
views
block
page

In addition, the menu rebuild triggers the following hooks:

hook_menu()
hook_menu_alter()


How can I use the Review Order Pane twice in Commerce Checkout?

I haven't completely tried this out, but you can duplicate the pane by implementing hook_commerce_checkout_pane_info_alter. Something like:

function mymodule_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['my_checkout_review'] = $checkout_panes['checkout_review'];
  $checkout_panes['my_checkout_review']['title'] = '[Duped] Review'; // to differentiate
}

I don't know what the consequences are of having two review panes, but I think this would be a good starting point.


How do i implement symmetric relationship with node reference module in drupal 7?

I suggest you to look at the relation module. It allows creations of symmetric associations which involve more than to entities. Haven't tried it myself, though.


Programmatically change select field options in contact form

This is probably not a good use case for the core version of contact form based on entity forms. You have not only to take care of the validation in the form api, but also on the entity level. If you want to do this, here is a tutorial: https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

In contrast Webform provides a very flexible handling of select options. You can edit the options separately from the form in predefined options lists and then you can modify the predefined options dynamically, see these examples:

/**
 * Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
 */

function mymodule_webform_options_test_alter(array &$options, array &$element) {
  $options += [
    'four' => t('Four'),
    'five' => t('Five'),
    'six' => t('Six'),
  ];
}

/**
 * Implements hook_webform_options_alter().
 */
function mymodule_webform_options_alter(array &$options, array &$element, $id) {
  if ($id == 'custom') {
    $options = [
      'one' => t('One'),
      'two' => t('Two'),
      'three' => t('Three'),
    ];
  }
}


If you are using Drupal 6 and Views 2, the easiest way to accomplish this is by utilizing the Data module.

If you can't use the Data module and have to do this programmatically for one reason or another, the following steps will get you on your way to achieving your goal of being able to manage your custom tables through the Views GUI.  The first step is implementing hook_views_api() in a custom module.  hook_views_api() tells which version of Views you are working with and will be similar to the code below:

function mymodule_views_api() {
  return array('api' => 2.0);
}

Change the version number depending on which version of Views you are using.  Then you will define your table structures in hook_views_data().  It is a fairly lengthy discussion, so I will point you to the resource at http://views-help.doc.logrus.com/help/views/api-tables on how to do this.

In order to add fields, sorts, etc. using your table's fields, you will have to add "handlers" to the various field definitions in hook_views_data().  The documentation at http://views-help.doc.logrus.com/help/views/api-handlers is a great overview of how handlers work, and the article by Treehouse Agency is a good working example of creating handlers and adding them to your fields.

Views programming is very tough at first, and it is always helpful to look at the built in examples that come with Views.  For example, the modules/node.views.inc file will have the hook_views_data() implementation for the core Node module, and the module/node directory will contain all of the handlers it utilizes.


How to exposed custom profile fields in views

In order to use it with Views, one of the following have to be true:

You are using Profile2
You are using core User profile
You are using actual fields from Field API
The profile storage is an entity
None of the above, and you are using a custom table

One of these should let you add a relationship in Views from 'User' to 'Profile2' associated to that user, if not, the core profile fields should be available.

However, if you used a custom table, you will have to do some legwork describing your data to Views in order for it to be an option.

Here are some resources that will help you in that direction:

How to add relationship in view for custom entity
hook_views_data
https://groups.drupal.org/node/400598
http://www.zyxware.com/articles/3280/drupal-how-to-add-view-relationships-programmatically-with-custom-database-tables-in-drupal-7

Do know that just because they are 'fields' in a custom form does not mean that it is represented in Drupal the same way. As far as Drupal knows (and from what I see in the provided code) it is your standard form made with FormAPI. They are not really "custom fields" so much as form items abstracting the input to store data.


Best practice dictates that you should not put the header or footer outside of the body tag. All visible content on your site goes inside the body tag.

Correct HTML syntax looks like this (here is a basic example):

<head>
  <title>My Drupal site</title>
  <!-- Other metadata goes here -->
</head>
<body>
  <header>
    <!-- Top of the page content goes here -->
  </header>
  <section>
    <!-- Main body content goes here -->
  </section>
  <footer>
    <!-- Footer content goes here -->
  </footer>
</body>

See this page for some extra details https://www.w3schools.com/html/html5_semantic_elements.asp

I know this doesn't technically anwer your question, but I feel this is a "correct" response in regards to what information will be most helpful.


How to dynamically assign submit hooks to webforms when generating blocks

webform_block_view() returns a block object that already has the rendered webform. At that point, you're not going to be able to make any form altercations need for your custom submission handlers.

However, you can add a hook_form_alter() invocation to your custom module. Webform generates a standard form id for each form webform_client_form_NID.

MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_NID') { //@TODO: substitute NID for your webform NID
    $form['#submit'][] = 'MYMODULE_webform_client_form_NID_submit';
  }
}

If you need to pass data from your hook_block_view invocation to your hook_form_alter invocation, a global variable should help there.


cache/normal/www.example.com is indeed where Boost would store your cached files.

Have you added the proper Boost directives to your public_html/.htaccess? It sometimes takes a bit of fiddling to get them right - you need to experiment by accessing the site as an anonymous user and viewing source on the returned page to see if the Boost signature is in there.


Using Views to List a Member's Organic Groups (7.x-2.3)

This is how to get the OG membership ID:s to start with.

Add new view.
Show -> OG membership (important!)
Then in some display add a contextual filter -> OG membership: Entity id.
Provide default value -> Type -> User ID from logged in user.
Override title: %1's groups.
Specify validation criteria -> User.

Now you have the list of ID:s.

Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title.
Relationship -> Group node from OG membership.

Now you have the titles too. Add some filters and sort criterias to taste.


The reason you get that error is that the form validation handler verifies the source entered in the form is a valid menu path, using drupal_valid_path().

Setting the path alias directly in the database would cause errors, as the source of the path alias is used to set $GET['q'], in drupal_path_initialize(), which contains the following code.

$_GET['q'] = drupal_get_normal_path($_GET['q']);

In your case, $_GET['q'] would be set to mypath?foo=bar&foo2=bar2. All the functions that use $_GET['q'] expect it to the in  the format path/subpath; the presence of the query parameters would cause errors. See for example the code executed by menu_get_item().

Using a custom module, you could implement hook_url_inbound_alter(), and hook_url_outbound_alter(). The first would transform foo/bar in mypath, setting $_GET['foo'] = 'bar', and $_GET['foo2'] = 'bar2'; the second would transform mypath in foo/bar, when $_GET['foo'] == 'bar', and $_GET['foo2'] == 'bar2'.


Views contextual filter from custom taxonomy field

Yes!
If the view is a view of nodes you have to add the relation based on the term field, than you should have the contextual filter available.


In the view fields search for "Link to content", add the field, exclude this from presentation and move it to the top, and now you can use:

{% if body|render|trim is not empty %}
  {{ view_node }}
{% else %}
  {{ title }}
{% endif %}


Why doesn't "Allow multiple values" in Views' Contextual Filter work?

Try using commas instead of plus signs, i.e. sushi,asian,italian since some apache configs do not support plus signs. Slashes should only be used between different contextual filters like cuisine and street, etc.

Also, make sure to check that the operator between filters is set to and not or. hth.


I've themed these fields through code:

<?php
hide($items[0]['field_picname']);
print render($items);
print render($items[0]['field_picname']);
?>

But I'm not sure the code is the best.


There are many different types of logging, all called the same way as per the documentation:

\Drupal::logger('my_module')->alert($message);

\Drupal::logger('my_module')->info($message);

\Drupal::logger('my_module')->debug($message);

Just call this code anywhere in your module, if you want to register logmessage as a path you'll need to create my_module.routing.yml, etc.


If you need the registration feature and you need to just remove the link from the default tab, then use menu_alter hook.

function modulename_menu_alter(&$item) {
// Hide the "Create new account" tab
$item['user/register']['type'] = MENU_CALLBACK;
}


How to change status and update account?

The account proxy class doesn't have a method called save. Refer to the API docs.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Session%21AccountProxy.php/class/AccountProxy/8.2.x

What you want is the block() method:

$account->block();

As $account should be an instance of UserInterface, returned front getAccount of AccountProxy. But without seeing the rest of the code its hard to see if this is the right approach for what you are trying to do.

If you could get the user account another way, then you could do:

$account = \Drupal\user\Entity\User::load('uid arg');
$account->block();
$account->save();


Creating a contextual filter for a view based on month and day

You will find the Date module useful for this. Date contains a number of sub-modules, including Date Views. Enable the Date Views module (and its required modules) and you will have what you need in Views.

Here's a link to the module:

http://drupal.org/project/date


8 - How to open node preview in a new tab

I was able to create a simple hack with jQuery that works better than I expected. I would prefer to handle it in php though. What I did was when the user hovers over the preview button I manually add and remove the target attribute to the form.

jQuery('#edit-preview').on('mouseover', function(e){
  jQuery('.node-form').attr('target', '_blank');
});
jQuery('#edit-preview').on('mouseout', function(e){
  jQuery('.node-form').removeAttr('target');
});
jQuery('#edit-preview').on('click', function(e){
  jQuery('.node-form').attr('data-drupal-form-submit-last', '');
});

The last part, allows the form to be submitted after launching the preview.  Otherwise, it thinks you are hitting the submit button twice.


How can I call custom javascript on successful webform submissions through hook_form_alter?

Your 2nd option will work in that :

.Module

function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "webform_client_form_id"){
        $form['#attached']['js'][] = drupal_get_path('module', 'c1') . '/c1.js';
    }
}

Js Code:

jQuery(document).ready(function(){
    jQuery( "#webform-client-form-id" ).submit(function( event ) {
      alert( "Handler for .submit() called." );
    });
});


Add a checkbox on registration page for subscription newsletter with Simplenews

After you have created a Newsletter category, go to admin/config/services/simplenews and click on edit newsletter category next to your newsletter category.

You'll see subscription settings. Select "Default On" or "Default Off" to display a checkbox on user registration form.

see image below for detailed explanation of setting mentioned above


How to test if a variable is been sanitized?

Your answer is already in the comments by @Geoff and @Clive above. If there was a way to unambiguously detect sanitation status of variables in PHP then the Coder module (and probably some IDE:s) would have incorporated it already.

But in some (not all) instances you can name your variables according to their sanitation status, to make it easier to keep track of which variables are sanitised and which are not.

<?php
  $myVar_raw = some_source();
  $myVar_safe = check_plain($myVar_raw);
  unset($myVar_raw); // Optional, to make sure raw variable is not used again later
?>


Limit node reference to 1 per user & per referenced node, Drupal 7

A solution is to use hook on form_alter inside a custom module :

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'vote_node_form') {
    global $user;
    $nid = explode('/', current_path());
    $nid = end($nid);
    // I'm sure that next part can be done waaaaaaay better
    $query = db_select('node', 'n')
    ->condition('entity_type', 'vote', '=')
    ->condition('uid', $user->uid, '=');
    $query->join('your_entity_ref_field_table', 'e', 'n.nid = e.entity_id');
    $query->condition('your_reference_column', $nid, '=');
    $query->groupBy('e.entity_id')->execute();
    // I'd advice to do a dpm($query->fetchAssoc();) to check if I didn't make a mistake         :)

    if(!empty($query)) {
            // We force the user to go on any page if he has already casted a vote on that debate (you can i.e create a page with a word of explanation)
            drupal_goto('/');
            //or do whatever you want here
    } else {
            // If not, we let him go to the normal node creation page
    }
  }
}


Ended up using two blocks with contextual filters, one that shows up for the node author and the other for Submitters.


how throw a custom exception in JSONAPI?

thanks  @4k4, I solved it using customs constraints in my custom entity, JSONAPI mapping well the error and the admin UI works perfectly with that.
like @kiamlaluno said, i try to explain the solution using constraints:
I want to response in the JSONAPI Request that the content is already exists but with a different code, no 500. So when i use constraints i can validate if content already exist or not and response if is a valid request (TRUE / FALSE), this constraints works in the JSONAPI Responses and in the Drupal Admin UI.
So you need to define the constraint in the folder
"my_module/src/Plugin/Validation/Constraint" and create 2 files, for my example i need that the content is unique. so my files are:
UniqueProfileContentConstraint.php
<?php

namespace Drupal\my_module\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Plugin implementation of the 'unique_entry_constraint'.
 *
 * @Constraint(
 *   id = "unique_profile_content_constraint",
 *   label = @Translation("Unique entry constraint", context = "Validation"),
 * )
 */
class UniqueProfileContentConstraint extends Constraint
{

    // The message that will be shown if the value is not unique.
    public $notUnique = 'This content already exists';

}

And the validator:
UniqueProfileContentConstraintValidator.php
<?php

namespace Drupal\ztv_content\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the UniqueInteger constraint.
 */
class UniqueProfileContentConstraintValidator extends ConstraintValidator
{

    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint) {
      // Next check if the value is unique.
      if (!$this->isUnique($entity)) {
          $this->context->addViolation($constraint->notUnique);
      }
    }

    private function isUnique($entity)
    {
      if ($entity->isNew()) {
        $query = \Drupal::entityQuery('profile_content_entity')
          ->condition('profile_id', $entity->get('profile_id')->getString())
          ->condition('video_id', $entity->get('video_id')->value);
        $storageContent = $query->execute();
        if ($storageContent) {
          return FALSE;
        }
        return TRUE;
      }
    }

}

And finally in the Entity annotation you need to add the id of your constraint:
 *   constraints = {
 *      "unique_profile_content_constraint" = {}
 *   }
 * )
 */


csv file imports only the last row when imported in drupal 8 webform

The UUID for all your CSV records is 1 and when they are being imported, each row is overwriting the previous row. You also need to include the column headers as the first row in the CSV.


For User i am giving option of color selections for a theme

well, usually there are pre-defined color sets (like in batrik), so you save set name and then on hook_preprocess_page you chose which css to include.
So either this or you can add inline css styling using the same function drupal_add_css.

As for how to save this for each user, you can add extra field to user profile at Home » Administration » Configuration » People » Account settings
and then programmatically update it with needed value - example below, details here.

global $user;
$existing = user_load($uid);
unset($existing->pass);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($user, $edit);


strtotime() doesn't return unix timestamp in custom view when $row->field_date is an English date

$row->field_date contains markup, not just the date/string value hence strtotime() won't/can't return a valid unix timestamp. To fix, try using strip_tags() around the returned value of $row->field_date like:

strtotime(strip_tags((string)$row->field_date));

or use "Strip HTML tags" option checkbox under "Rewrite Results" in the "Configure field" dialog.


Rules: how to display the value of variables?

Two options:

At admin/config/workflow/rules/settings, set "Show debug information" to "Always."
In the rule's actions, add the action "Show a message on the site" (under the System group, I believe). Pass it the variable(s) you want to debug.


Calculate Star rating based on webform submissions

Yes. You should create a fivestar field in your webform and than create a custom module which calculate the rating and save it to a fivestar field.


Please, consider using Extended path aliases or Sub-pathauto.

For breadcrumbs you can use Path Breadcrumbs or Custom breadcrumbs.

You also can set active menu item programmaticaly, but I don't like this way:

  // Somewhere in menu callback for 'folder/subfolder/preferences' path.
  global $user;
  if (user_is_logged_in()) {
    $path = 'user/' . $user->uid . '/edit';
    menu_set_active_item($path);
    return menu_execute_active_handler($path, FALSE);
  }

Maybe someone can improve this code to be more transparent.

Tip: you often can find related modules in module description or on the right sidebar on Drupal.org. I found these modules on Pathauto page.


Devel admin interface unreachable; or I broke my Devel?

Rebuild menus ! This fixed the problem!

One of the menu tables must have been corrupted somewhere in my Drupal shenanigans.

So try that if you start getting 324's (or other non 200 responses) in weird places!


Take a look at the Login Redirect module. It should do what you are describing.


Token to show only first term in Page Title module

Delta values for field are available in token

As the description says delta start with 0 try using token as [node:field-page-title:0], remember to replace your field machine name.


Changing commerce_line item quantity to 3 decimal places

In theory, changing the commerce_line_item field's SQL (schema) definition ought to be enough. However, a cursory review of a few modules shows that some of them will round the value to 2 decimal places before using it, negating the change. You'll probably need to change it and then test it to ensure that every module you're using it with will work as you intend.


The code that makes that happen is in node.tpl.php:

<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
    <?php print $title; ?>
  </a>
</h2>
<?php endif; ?>

So to override it, you just need to re-create node.tpl.php somewhere in your theme's folder, remove the <a> tag surrounding the title, and clear Drupal's caches. Then you won't get links on title for node teasers any more.

If this is too 'all-encompassing' and you just want to do it for a specific content type then as well as copying the original (unchanged) node.tpl.php into your theme's folder, create another one called, for example, node--article.tpl.php (for the article content type), and make the alterations in there instead.


I am sure you are looking for the Subfolders Domain module.

  Create and configuring easily the hierarchy Subdirectory multi-site for your Drupal multi site from one installation and a single shared database. This module allows you to add new subdomains directories or management of subdomains directories without changing/adding any file configuration (such .htaccess, sites.php, Alias in Apache config file, ...)


How do I alter a form using an AJAX callback?

Ajax Forms in Drupal 7 states:

  Changes to the form must only be made in the form builder function. The callback function must not alter the form or any other state.

In form build/alter, check $form_state->getTriggeringElement() for the triggering element and then enable the field.


Why might the user's email address not show up in Views Send or as a Token?

YAY!

I finally managed to find out why this was happening by comparing against two other Drupal sites where Views Send behaved as expected.

The issue was with the Views Contact Form module : https://www.drupal.org/project/issues/views_contact_form

If you have that enabled, it breaks Views Send by hiding the main user email address, even if you have the format of the field set to plain text.


How to get JSON data from exception in httpClient()

This should work

if ($e->hasResponse()) {
    $response = $e->getResponse()->getBody()->getContents();
}


Views aggregation, sum of node count in _each row_

A no-custom-code solution could be something like this (not the most performant way though but you could perhaps do something with views caching).

Explanation:
Create one view for the total count that with the use of aggregration and a content type filter returns the total number of nodes (the Total column)
In another Taxonomy Terms view you attach the total count view by adding a Global: View field that is provided by the Views Field View module

Steps
 - Create a content type e.g. "Colornode"
 - Create a taxonomy vocabulary called "Colors"
 - Add three terms Blue,Green and Red
 - Add a term reference field and select Colors as the vocabulary
 - Install and enable the Views Field View  module

Then import these two views in this order:

$view = new view();
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = FALSE;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['type']['separator'] = '';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'colornode' => 'colornode',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

And the second one:

$view = new view();
$view->name = 'colorterms';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Color terms';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Color terms';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Taxonomy term: Content using Color */
$handler->display->display_options['relationships']['reverse_field_color_node']['id'] = 'reverse_field_color_node';
$handler->display->display_options['relationships']['reverse_field_color_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_color_node']['field'] = 'reverse_field_color_node';
/* Relationship: Content: Color (field_color) */
$handler->display->display_options['relationships']['field_color_tid']['id'] = 'field_color_tid';
$handler->display->display_options['relationships']['field_color_tid']['table'] = 'field_data_field_color';
$handler->display->display_options['relationships']['field_color_tid']['field'] = 'field_color_tid';
$handler->display->display_options['relationships']['field_color_tid']['relationship'] = 'reverse_field_color_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(Content: Color) */
$handler->display->display_options['fields']['field_color']['id'] = 'field_color';
$handler->display->display_options['fields']['field_color']['table'] = 'field_data_field_color';
$handler->display->display_options['fields']['field_color']['field'] = 'field_color';
$handler->display->display_options['fields']['field_color']['relationship'] = 'reverse_field_color_node';
$handler->display->display_options['fields']['field_color']['group_type'] = 'count';
$handler->display->display_options['fields']['field_color']['label'] = 'Count';
$handler->display->display_options['fields']['field_color']['separator'] = ', ';
/* Field: Global: View */
$handler->display->display_options['fields']['view']['id'] = 'view';
$handler->display->display_options['fields']['view']['table'] = 'views';
$handler->display->display_options['fields']['view']['field'] = 'view';
$handler->display->display_options['fields']['view']['label'] = 'Total';
$handler->display->display_options['fields']['view']['view'] = 'nodecounts';
$handler->display->display_options['fields']['view']['display'] = 'block';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'colors' => 'colors',
);
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'reverse_field_color_node';
$handler->display->display_options['filters']['type']['value'] = array(
  'colornode' => 'colornode',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'color-terms';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Color terms';
$handler->display->display_options['menu']['name'] = 'main-menu';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'color-terms';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Color terms';
$handler->display->display_options['menu']['name'] = 'main-menu';

Result


When rendering paragraphs in a theme, is there a way to look at the last rendered paragraph while rendering the current one?

Yes, you can do something like this in preprocess:

    <?php
    // Get entity reference revision item that points to this paragraph.
    /** @var \Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem $item_reference */
    $item_reference = $paragraph->_referringItem;

    // Get entity reference revision field items list that holds all
    // paragraphs.
    /** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $items_list */
    $items_list = $item_reference->getParent();

    // Get next index position of current paragraph in entity ref. revision
    // field items list.
    $next_delta = $item_reference->getName() + 1;

    // Check if there is a paragraph on the next delta.
    if ($items_list->offsetExists($next_delta) && $items_list->get($next_delta)->entity) {

That special property is set in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView(). And because paragraphs themself are not render cached on their own and not used in multiple places means that you can actually rely on it. (It would also be set on a node, but due to render caching, you can not rely on it being there, at least not by default).


I think you should use Field Formatter CSS Class module for this. Module page says :

  The Field formatter CSS class module allows you to set any
  text/list/option/taxonomy field to render as CSS class on the node.
  This enables the node author to select predefined CSS styling per
  node.


file_scan_directory() takes about 10 seconds to execute

It sounds like you're affected by a known issue in Drupal 7.

  Most probably, you are hitting Avoid re-scanning module directory when multiple modules are missing. It happens if you have some missing modules in your installation. Try to check your system table:

SELECT name, filename FROM system WHERE type = 'module' AND status = 1 ORDER BY filename

  And clean-up any modules that are still enabled but missing from the filesystem.

  Overall, Drupal 7 is way more resource friendly and scalable then Drupal 6, other than some unfortunate regressions like this one.

Looking at those functions, it does look like it's missing a module or maybe a single file of a module. Have a look at drupal_get_filename(), it does call the drupal_system_listing(), which calls this function if it can't find the requested file. Add a dpm(func_get_args()) right before it calls drupal_system_listing(), that should tell you which file it isn't finding.


Using hook_menu in a custom module, how do you add a menu item to more than one menu in Drupal 7?

I'm pretty sure you are looking for menu_link_save() as adding the menu_name in hook_menu() just puts this callback in that menu instead of defaulting it into the navigation menu.  So, after creating it above, with or without the menu_name, you should be able to add it to any other menu(s) with menu_link_save().