How to get user.field value in node--teaser.twig

This bit's the problem:

$node = \Drupal::routeMatch()->getParameter('node')

Even if that returned a value, it would probably be the wrong one; it's not common to render the node as a teaser on its own view page.

As it happens, you don't need to load it yourself for any of the view modes. The node is already in $variables:

function MYTHEME_preprocess_node(&$variables) {
  $variables['author'] = $variables['node']->getOwner()->field_name->value;
}

You may need to add a further check of $variables['node']->getType() if the field is only available to certain content types.


warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'search_form'

You need to either

Enable the core search module or
remove the search form block from being rendered in your theme (perhaps in template.php or page.tpl.php)


Loop trough a list of referenced nodes, "entity_metadata_wrapper()" style

entity_metadata_wrapper() has you covered, the entities will be lazy-loaded as you'd expect:

$wrapper = entity_metadata_wrapper($entity_type, $entity);

foreach ($wrapper->field_plan_tpl as $related_entity) {
  $foo_field_value = $related_entity->field_foo->value();
}


Views is notoriously heavy with memory, but it does seem odd that a view that only touches 6 nodes would crap out at 256 MB.

I see you've got a dpm call there - does removing that and turning off the devel module make a difference? And do you have xdebug enabled or any other profiling enabled by any chance? All that stuff would contribute.

The other thing you might want to double check from phpinfo() is to see if your memory limit really is set to 256MB.


You can just use views to filter on the catalog pages for product variations if they are set. You should take a look at http://www.drupalcommerce.org/user-guide/products the guide will help you create product variations, you can then create a view for the catalog, you can then create a exposed filter (lets the users change the filter value) for product variation so they user can select PS3 or XBOX and get only those products on the filter. But if you went to that page, you would still need to select "PS3" or "XBOX" to place a order.


Drupal 7 errors after upgrading from 7.12 to 7.14

I ran into the same issue and found the solution here: http://drupal.org/node/1427430

Do you happen to also have the opengraph_meta module installed?
If so just edit this file:

sites/[your-site]/modules/opengraph_meta/opengraph_meta.module

search for this line:

'#attributes' => array('class' => 'opengraph-thumbs-wrapper clearfix'),

and change it to look like this one:

'#attributes' => array('class' => array('opengraph-thumbs-wrapper','clearfix')),


How do I skip language selection with installation profile?

This cannot work, because $install_state is passed as value, not as reference. So changing it has no effects.

function efocus_install_tasks_alter(&$tasks, $install_state){
    $tasks['install_select_locale']['function'] = '_efocus_locale_selection';
}

// local callback function
function _efocus_locale_selection(&$install_state){
    $install_state['parameters']['locale'] = 'en';
}

This one works. I am simply replacing the standard_locale_selection with a custom function, which gets the install_state passed as reference. So i can change the value...


How do I add a custom template to my feature?

For either content-type or views templates, you're going to need to manually add these to your features set since ctools exports doesn't handle these. In your features folder (ex. testfeature), you want to create a subfolder for templates:

/testfeature
    testfeatures.features.inc
    testfeatures.info
    testfeatures.module
    templates/

and then copy all of your custom templates into this folder. Then in the testfeatures.module folder, you just need to use hook_theme_registry_alter to add your content-type templates in:

function testfeatures_theme_registry_alter(&$theme_registry) {
    $theme_registry['template-file']['path'] = drupal_get_path('module', 'my_feature')."/templates/";
}

For views templates, you should have more success using a hook_theme function, ex:

/**
 * Implements hook_theme().
 */
function nigel_gallery_theme() {
  return array(
    'views-view--gallery-content' => array(
      'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
      'template' => ' views-view--gallery-content',
      'path' => drupal_get_path('module', 'nigel_gallery'),
    ),
  );
}


Lightweight way to check to see if another user has a role

Something like:

function MYMODULE_get_user_roles($uid) {
  $roles = &drupal_static(__FUNCTION__, array());

  if (!isset($roles[$uid])) {
    $query = db_select('role', 'r')
      ->fields('r', array('rid', 'name'))
      ->condition('ur.uid', $uid);

    $query->join('users_roles', 'ur', 'ur.rid = r.rid');

    $roles[$uid] = $query->execute()->fetchAllKeyed();
  }

  return $roles[$uid];
}

You might want to add static caching to that if you plan to call it more than once for any single user during a single page build.


Log into the Drupal 7 admin dashboard.
Using the top menu bar, locate and click on the Structure option.
From this next page, click on the Content Types link.
On the Content Types page, find the type of content you want to work with. I have been working with Basic Pages so I will stick with that. After locating your desired content type, click on the correct Manage Display link.
From this page you will need to find the filed row  you want to hide and then the Label dropdown. Set the Label field to  to remove the label from the image field.
Once finished, click on the Save button at the bottom.
Clear cache

Or you can use Automatic Nodetitles module

"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.


Panels content not displaying on copied site

Check your Apache error logs and see what errors are reported when loading the Panels page - this is an essential part of your debugging toolkit.

Are you really using PHP5.4? That is likely to be the issue. http://drupal.org/node/1469736 indicates that the published release of Panels is not PHP5.4 compatible, but the dev release may be.


Embed a single webforms different fields in to two different pages - Drupal 6

Have not received an answer So based on my research I believe the Webform paging can solve this problem since it can display the webform in two parts.


What arguments does a _custom_access callback exactly receive?

See \Drupal\Core\Access\AccessArgumentsResolverFactory::getArgumentsResolver() which is called by your snippet above to create the argument resolver, I think that covers it pretty well.

It gets all raw parameters, all possibly upcasted parameters, plus request, route match and account. The access callback receives the arguments from that list, based on the names and type hints.

So account isn't ignored.

That logic is the same as for any other access check, the whole point of _custom_access is to have an easy way to do a one-off access check without having to go through the additional steps of a service that's defined with a special tag.


Make a copy of your_drupal_site/modules/field/theme/field.tpl.php in your theme directory and name it field--field_related.tpl.php  In this file  You can attach the class (grid_1) to each field as follows:

<?php foreach ($items as $delta => $item) : ?>

<?php print render($item); ?>

 <?php endforeach; ?>

All the available variables are listed in the comments of this file so you will be able to customize as you like.

On any given node you can check how many fields have been created and theme according to that. You can change the above code to count how many fields are there on any node, the revised code is as follows:

<?php foreach ($items as $delta => $item) : ?>
    <?php
    if (count($items) > 2) {
        print '
' . render($item) . '
';
    } else {
        print '
' . render($item) . '
';
    }
    ?>
<?php endforeach; ?>

This will add class "grid_1" to any node with 3 or more fields of field_related and add class "two_or_less" to the nodes with 1 and two fields.


Passing a number via page arguments in hook_menu()

I normally just wrap the value in quotes, that should convince the router system to leave it alone:

'page arguments' => array("$record->id", 2)


How to write a template_preprocess_node hook to get the Image Style for an Image field?

It is part of the render array generated by the formatter: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldFormatter%21ImageFormatter.php/function/ImageFormatter%3A%3AviewElements/8.2.x

You can see that it is set on #image_style, so in node preprocess, that should be $variables['content'][field_imge][0]['#image_style'].

Depending on what you want to do, you could also write your own formatter or you could preprocess/alter the image_formatter template.


500 internal server error on a single node

Display PHP errors for that page or examine your Apache log file with errors enabled. Nobody can tell you what's misconfigured, or whatever typo you've made in your PHP ... log files can tell you though.

EDIT:

For further explanation on "errors" and specifically 500 error from Apache see:
https://stackoverflow.com/questions/8564259/php-5-3-troubleshooting-500-errors-debugging-parse-errors

  PHP will respond with a "500" when it encounters a Fatal error, such
  as E_PARSE, E_ERROR and uncaught exceptions. 500 is the HTTP response
  code for "Internal Server Error" - something unrecoverable happened
  while processing the request.

  In your php.ini, on a development machine, you should set your
  error_reporting level to (at least) E_NOTICE - preferably E_ALL - and
  make sure display_errors is on. This will show you the error message
  in the browser, including for "500" errors.

  You can also check your Apache error logs, the errors will be listed
  there, as long as log_errors is enabled in php.ini. By default, this
  will be at \logs\error.log.

  You can also control all this at run time with ini_set() and
  error_reporting()


How to render taxonomy field_custom in page--taxonomy--term.twig?

You need to prepare the Twig variable in a preprocess hook:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['field_example'] = $term->field_example->view();
  }
}


Saving user specific customization settings

The best place maybe the drupal user object's data array for tiny amounts of information, like preferences on a per user basis.

$user->data

I'm trying to solve this myself but these links seems useful:

drupal 6
drupal 7
http://www.braahm.be/node/7
http://randyfay.com/node/85


How to get translated field using Twig tweak?

Try the language parameter:

{{ drupal_field('field_name', 'user', uid, user.langcode.value) }}

This was added to drupal_field() in this issue Support drupal_field translatability.

For this to work the user entity needs to be available in your template.


Drush cannot find your database connection details

First of all, you should really use Drush 9 or 10 - see https://docs.drush.org/en/master/install/#drupal-compatibility And install Drush site locally as described on the same page.

However, the message Unable to find a matching SQL Class probably means that shared server you are running Drush on is missing the needed PHP database extensions. This is typically PDO with MySQL (pdo_mysql and mysqli) - see https://www.drupal.org/docs/8/system-requirements/php-requirements#database

A typically problem is that PHP in the web server has these extensions, but not PHP on the command line.


Problem solved by https://www.drupal.org/project/rules/issues/2990211#comment-12716081

  I have another rule that modify the title of my node with event
  After updating content (rules_entity_update:node). But since that rule is necessary, then it should not be deleted but still I dont want
  to get a duplicate result when a node is created. So what I did, is I
  change the other rule that modifies the title into event Before
  saving content (rules_entity_presave:node) so it wont be called on
  node creation, and this works!


If I understand your (main) question correctly, you want to show additional images in the slider. In that case you have to narrow down which modules are used to create the slider. Typically a View is used to retrieve all content (stored in your database, normally not encrypted), an overview of all Views can be found at admin/structure/views. In the View there is an option to set the number of items that have to be shown in the Pager section (setting the number of items to show to 12 would in a typical installation be the thing you want to do).

When this is indeed the set up and you don't see the expected change after altering the value, don't forget to clear the caches (drush cr or via admin/config/development/performance).

If your environment is different, please provide additional details: which module is used to create the slider, e.g. Flex Slider, is Views used to provide the data (images provided by the user), etc.


If you check your console in your DevTools, you can see the error message says:

It says that Vimeo allows the content to be displayed only from the Same Domain. The Vimeo videos provide links in the following format which can be embedded in external websites.

https://player.vimeo.com/video/12345.

You can try embedding video in the above format.


Display images as a form element in a webform

If you install the IMCE module and set up the right permissions, users can upload and insert images into a webform.
Another option is to change the Webform module's default HTML Editor to use a Text format which supports inline images. You would do this by going to Webform > Configuration > Elements ( (/admin/structure/webform/config/elements)


Drupal 7 tables that can be excluded

Here is a list of tables in Drupal 7 that you can either clear (to reduce the database size) or safely exclude to do a migration (as in the question about How to reduce the locally exported database size to get around my server import limit?):

accesslog
batch
all cache related tables, such as:

cache*
cache_block
cache_content
cache_filter*
cache_form
cache_calendar_ical
cache_menu*
cache_page*
cache_views
*_cache, such as features_cache or views_data_object_export_cache

ctools_views_cache
ctools_object_cache
devel_queries
devel_times
flood
history
queue
various search_* tables, such as:

search_dataset
search_index
search_keywords_log
search_total

semaphore
sessions
watchdog
webform_submitted_data

Usually tables such as search_index and watchdog use a lot of database space, so just eliminating those 2 tables can make a huge difference already.

Other tables that might be excluded

Check the size of your remaining tables and identify which one of them are the biggest in size.

Typically you might find session tables for which no cleanup procedure is in place. Such tables you can probably also exclude.

Module Backup and Migrate

To further reduce the challenge as detailed in "How to reduce the locally exported database size to get around my server import limit?", look at the Backup and Migrate module also. Here is a quote from its project page (bold markup added here):

  Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

And there is even more: if your local environment (e.g. Win or Mac) differs from the OS that the server of your hosted website is running (like Linux), then these differences between OS-es imply potential extra challenges. I've had good experiences with the Backup and Migrate module between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.


How to have html not just sitename or logo in site heading block? (via subtheme or preferably editing WITHIN drupal)

Keep it simple. Just disable the logo in your theme settings and use a block in it's place. You can throw anything you want in there.

Just place a block using Drupal UI into the header region of your theme. No coding, no template files creating/hacking is needed.


The number of iterations is wrong. The stored value is the power of 2, encoded using a Base64 alphabet. D means 32768 iterations (215).
The other issue you have is that the hash and salt values are Base64 encoded, but using the same alphabet used by cript() (the POSIX function also part of the BSD Library). The PHP code Drupal uses to encode is the following one. It may be helpful to write the JavaScript code you need.
function _password_base64_encode($input, $count) {
  $output = '';
  $i = 0;
  $itoa64 = _password_itoa64();
  do {
    $value = ord($input[$i++]);
    $output .= $itoa64[$value & 0x3f];
    if ($i < $count) {
      $value |= ord($input[$i]) << 8;
    }
    $output .= $itoa64[$value >> 6 & 0x3f];
    if ($i++ >= $count) {
      break;
    }
    if ($i < $count) {
      $value |= ord($input[$i]) << 16;
    }
    $output .= $itoa64[$value >> 12 & 0x3f];
    if ($i++ >= $count) {
      break;
    }
    $output .= $itoa64[$value >> 18 & 0x3f];
  } while ($i < $count);
  return $output;
}

function _password_itoa64() {
  return './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
}

The full code used from Drupal 7 to hash passwords is contained in the password.inc file. In particular check the following functions:

_password_itoa64(), the function returning the Base64 alphabet used
_password_base64_encode(), the function to encode in Base64 using that alphabet
_password_generate_salt(), the function that generates the salt
_password_crypt(), the function to hash the password, which calls all the other functions

I cannot say what should be used for saltOrder, since that isn't used from Drupal code and it's specific for the platform to which you are migrating the users.


If you need to create/update a file alongside the entity posted JSON you need to create the file in your code like:

//Implements of hook_services_request_preprocess_alter().
function my_module_services_request_preprocess_alter($controller, $args, $options) {

switch ($controller['callback']) {
case '_user_resource_create':
case '_user_resource_update':
  if (isset($args[1]['avatar'])) {
    $data = base64_decode(trim($args[1]['avatar']));
    $finfo = finfo_open();
    $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
    finfo_close($finfo);
    // get file type png. jpg
    $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
    $file_name = str_replace(' ', '-', $args[1]['name']);

    $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
    $args[1]['field_field_user_picture'] = array(
      'fid' => $file->fid,
      'width' => 100,//set your own
      'height' => 100,//set your own
      'alt' => $args[1]['name'],//set your own
      'title' => $args[1]['name']//set your own
    );
  }
}

By that way you could create any image field with any entity easily.

From the best practice I advice you to use the module user picture field that let's you deal with the user picture as a field so you could have it in views with different formats instead of just have the file id.

Another tip is to send the image format as It won't be possible to get the mime type from the json decoded file source.

Sure you still be able to create a file through file services but I think you have to make the post request format www/url-encoded instead of json


It's /og/%/%/unsubscribe. See og_ui_unsubscribe() in og_ui.pages.inc to learn what are the arguments passed onto this.


How do I place thumbnails from videos in a views slideshow?

I found out that a few boxes were unchecked that I didn't know about.  This link shows a good tutorial on this: http://webwash.net/tutorials/display-video-thumbnails-media-module


Drupal 6 make a content edit form be in a specified theme

Implement hook_form_alter in custom module and check for current theme :

global $theme;
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'example_node_form_id' && $theme != 'theme_machine_name') {
    // redirect anywhere using drupal_goto.
  }
}


The problem is that you are using bad modifier for the t() function.

$variables = array(
    '@site_name' => variable_get('site_name'),
    '@tags' => $params['tags'],
);

$subject = t('@site_name: Verify your Subscription', $variables);
error_log("subject=$subject");

Note the @site_name change.
If you use

@site_name --  it will be run through check_plain and returns without any theming.
%site_name -- check_plain with theme_placeholder.
!site_name -- Allows all HTML.

Also note that this is not limited to site name. Whenever you use t() function, you should use above placeholder pattern to ensure CSRF-safe variable display.
Do not use t() function for use-entered variables. For an example, t($form_state['values']['name']); is bad!. Real use of t() function is when you use it with your own text and optionally user-entered data.

Good luck!


Load menu items from one menu in other menu

you can add new module twig tweak, after rendering blocks menu with Twig Tweak on template.


Is it possible to run Drush without root?

You do not need root-level permissions to use Drush: it'll work as long as the user invoking it has direct access to the Drupal installation directory.

Having the the same filesystem permissions as the web user should be enough for most operations: but for things like downloading modules, you'll need write-level access to the Drupal directory as well.


Add database value in views for entity type user

Although I haven't had a chance to play with it myself just yet, assuming everything else is implemented correctly, it seems as though using EntityFieldQuery Views Backend as your Views backend should make your new Rank field visible to Views.


Dependency injection or \Drupal class methods?

In Drupal 8, you should always use dependency injection within the context of classes.

However, if you create a custom service, you don't have to manually implement the ContainerInjectionInterface.

Instead, you define your service and the arguments for the constructor within your module's example_service.services.yml file (read more about .services.yml files here and about service injection here):

services:
  example_service.my_service:
    class: Drupal\example_service\ExampleService
    arguments: ['@current_user']

And your service class like this:

<?php

namespace Drupal\example_service;

use Drupal\Core\Session\AccountProxyInterface;

/**
 * My Example service.
 */
class ExampleService {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct an example service instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   Account proxy for the currently logged-in user.
   */
  public function __construct(AccountProxyInterface $current_user) {
    $this->currentUser = $current_user;
  }

}

Then you can create an instance of your custom service either via dependency injection as well (within the scope of another class), or within your module/theme files by using:

/* @var $my_service \Drupal\example_service\ExampleService */
$my_service = \Drupal::service('example_service.my_service');


Showing "New content" form on main theme

In Drupal 8 there is the entityform_block module which gives you the option to display an entity form as a block.
You just need to go to Blocks, select Place block in the region you want and select Entity form.
When you add your from you can select Entity Type + Bundle, where you have to select your content type and also in which pages you what this block being visible.

Keep in mind that using this way, on submit the user will be redirected to the content page but you can write your custom handler using hook_form_alter.


Maybe the Multi Node Add will cover what you require :

  This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
  It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.

See if it does it for you. But also beware that it's a beta release.


Combine recent and popular items in Views

You can create two separate views which will display two 2 popular items and  2 most recent items and use script below that will print content from these views on the page.

for ($i = 0; $i <= $n; $i = $i + 2) {
  $popular = views_get_view('popular');
  $popular->set_display('block');
  $popular->set_offset($i);
  $popular_content = $popular->preview();
  print $popular_content;

  $recent = views_get_view('recent');
  $recent->set_display('block');
  $recent->set_offset($i);
  $recent_content = $recent->preview();
  print $recent_content;
}


How to display only "after now" dates (of multiple) of a date-field in a node?

Ok, I dived into the drupal variables with the help of the devel module and came up with a solution (first version, see better version below the edit):

I now parsing all dates directly from the content in my specific node--event.tpl.php. I then iterate through them and store all dates that are in the past in a new array. In the end, if that array contains any values and my new option is activated (differentiating between teaser and full display), I remove those past-dates from the date-field array in the content:

<?php
// remove dates in the past from the date-field if enabled
if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    $past_date_array = array();
    foreach($content['field_eventdate']['#items'] AS $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        array_push($past_date_array, $date_array);
      }
    }

    if (count($past_date_array) > 0) {
      $only_future_date_array = array_filter($content['field_eventdate']['#items'], function ($var) use ($past_date_array) {
        return !in_array($var, $past_date_array);
      });
      $content['field_eventdate']['#items'] = $only_future_date_array;
    }
  }
}
?>

Maybe there is a cleaner way of preprocessing the content (let me know), but this was the quickest I could come up with and I now have the option per-node.

== EDIT ==

Why make it complicated: I forgot about hiding fields, so no more array-assigning, just on-the-fly hiding of past-dates:

if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    foreach($content['field_eventdate']['#items'] AS $key =>  $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        hide($content['field_eventdate'][$key]);
      }
    }
  }
}


Make sure to configure your base url in your settings.php file and revert your .htaccess to the default from drupal.


The code $build['pager_pager'] = array('#theme' => 'pager'); returns the pager for the table.

The example module output with that line of code:

The example module output without that line of code:

If you are not seeing the same difference I am, it might be a cache issue, try clearing your cache between changes.


How to implement per user caching when restricting display of comments by author

As Clive said in the comments, all I needed was the following.
I won't mind if people down vote the question for being too stupid…

// was user.permissions, but that means there will only be a single
// cache shared by all reviewers, and we must cache according to authorship
$build['#cache']['contexts'] = ['user'];

Caveat: the view block cache setting also needs to be 'none'.

Drupal docs - cacheability of render arrays


cache issue - misaligned views cached output

It looks like you need to add clearfix to the css attribute of your views rows.


When you are in edit mode of your view:

you should have an option of adding fields

When you click on add field, you should see a drop down of all types of field available.

Choose Content from the drop down.

You should be able to see your cck field there, click add and review the settings for the display of the field.
I suggest you checkout this video to get overview of views - http://mustardseedmedia.com/podcast/episode9


How to add new reference in entity reference field in node edit form keeping old references intact and hidden?

Edit the field and set number of values to be unlimited. If you want more control and flexibility you could put the entity reference within a field collection.


Users aren't redirected to the front page after account cancellation

I solved it using custom service. Will post it here shortly.


You should have a look at the Services module. You can use XMLRPC and/or REST server (and many more) to communicate with your remote server. Link to the documentation.

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


These are the two routes for the original form class:

comment.routing.yml:

comment.admin:
  path: '/admin/content/comment'
  defaults:
    _title: 'Comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'new'
  requirements:
    _permission: 'administer comments'

comment.admin_approval:
  path: '/admin/content/comment/approval'
  defaults:
    _title: 'Unapproved comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'approval'
  requirements:
    _permission: 'administer comments'

You have to alter both routes like this

  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('comment.admin')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyForm');
    }
  }

in a RouteSubscriber.


Views Accordion not working when other Jquery plugins are used

There is a module called http://drupal.org/project/views_isotope

Using that would be better as it would play well with the rest of the js.

The js behavior with in drupal 7 has changed a bit and placing the js directly might not work well in many cases.


LDAP Module - Notice: Trying to get property of non-object in ldap_authentication_init() appears

This message disapears when i add data in a 'Authorization Tab' In a email section and I select a "LDAP Server Type" (This option belongs to LDAP server's configuration from Server tab) such as Active Directory.

Thank, you Anyway


How to relate nodes by field, not title?

You are mistaken. Node reference uses the node id - the primary key for nodes to create the reference. The form element where you need to enter the node you want to reference, uses autocomplete to make it easier to find the node you want to reference, but the value stored is the node id. So there is actually no problem in using node reference and changing the title.

Code from the node reference module to illustrate this, can be found where the schema is defined for the field type it uses to create these reference:

/**
 * Implements hook_field_schema().
 */
function node_reference_field_schema($field) {
  $columns = array(
    'nid' => array(
      'type'     => 'int',
      'unsigned' => TRUE,
      'not null' => FALSE,
    ),
  );
  return array(
    'columns' => $columns,
    'indexes' => array('nid' => array('nid')),
    'foreign keys' => array(
      'nid' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
    ),
  );
}


How do I get debug_backtrace() to fire on the endpoint site of a Deployment process?

note the following: fc661e5c-62de-fa34-2557-0f6f5a2acbfe
and then... General error: 1366 Incorrect integer value:

the number or UUID is not an integer.

therefore you'll get that sort of error message. I'm assuming deploy has either a bug in it or you've forgotten to run update.php on your DB the FID field is marked in the DB as an integer when it should be a varchar / string field.

Take a look at the schema and see what needs to change. that should at least give you an indication of where things have gone wrong.


Printing fieldable panel pane custom field in template properly

Ignoring the empty field-labels was a problem! The issue was with those field labels, which were generated by the Fences module. They were somehow causing the h2 to close too early.

I ended up modifying the module myself, so that the template checks if a field label exists before adding it to the DOM.

I also ended up finding an issue on the module's issue page which has a patch to fix it directly, in case anyone is interested: https://www.drupal.org/node/2605808


How to make question answer content type with answer as a separate node?

If you don't want to reinvent the wheel, you should have a look at the Answers module. Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

Question.
Answers.

The "Best Answer" submodule can be used so that the question author can "accept" one of the answers as the best one. And you could make the Rules module to either trigger all sorts of subsequent things to happen "when an answer gets marked as best answer", or to add all sorts of validations when posting an answer (or question).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module and supports voting.

Demo

Have a look at the (new) demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

Disclosure: I'm a (co-)maintainer of this module.


As the first parameter to form_set_error(), pass the name of the field to be highlighted. If it's a nested structure, pass it with square brackets, like so:

form_set_error('[your][nested][field]', 'Your Error Message');

There's a convenience wrapper around this, form_error, which takes the element instead of the string, like so:

form_error($form['your_field'], 'Your Error Message');

Also see the docs to form_set_error() (d7).


Drupal Views: How to remove 1 item if it matches the Node TItle

It's better and easier to match by Node ID. To do that, add a "Node: NID" argument (or a 'contextual filter' in newer Views versions) to your view, set it to "Provide default argument", choose "Node ID from URL" as default argument type and check the "Exclude the argument" box. That should do the trick.


Disable the Module
Uninstall the Module
Delete the Module folder from sites/all/modules
Remove the CkEditor folder from site/all/libraries
Clear the Cache
Copy the CkEditor Module to site/all/modules folder
Copy the Downloaded CkEditor to sites/all/libraries folder
If in *nix systems, check the folder permissions. (Most of the time this happens to be the issue)
Enable the Module as usual.

More info is given CkEditor docs


How can I filter multiple nid at the same time using Views exposed filter?

I don't think this can be done by Views only.

You must create a custom module that use the hook_views_query_alter() (The code is for Drupal 7)

function my_module_views_query_alter(&$view, &$query) {
  // we only want to alter this view, so we check against the machine name
  // and we make sure our exposed filter is set
  if ($view->current_display == 'my_current_display' && $view->exposed_raw_input['nid']) {
    // first we grab the value from our filter and convert it into an array
    // make sure you use the same character you used to delimit the string
    $nids = explode(',',$view->exposed_raw_input['nid']);

    // now we loop over the array of values we created from our exposed filter field
    foreach ($nids as $nid){
      // Be conscience of the ‘where[1]’
      // In the $query object you noticed the conditions array had multiple arrays.
      // Each filter in your view will be placed in a conditions array.
      // It is important to include the empty brackets [] after ['conditions']. This will append the new conditions instead of overwriting them.
      $query->where[1]['conditions'][] = array(
        'field' => 'node.nid', // this is ‘table.field’ from your database. If you used another filter than ‘Content: nid’ this will change. i.e ‘users.uid’
        'value' => $nid,  // looped value from our values array
        'operator' => '!=',  // condition operator. I want to filter out nids, so I am using ‘not equal’
      );
    }
  }
}

Disclaimer: I run a similar issue and the solution gave to be by the below article. The code and the credits go to Peter Schuelke.

More information can be found here:

  http://www.metaltoad.com/blog/passing-multiple-values-through-exposed-filter


how to give the same style as the back-office theme for people allowed on edition?

Set the permission View the administration theme and make sure that the option Use the administration theme when editing or creating content is enabled on page /admin/appearance.


Set default value radio button in template

Add direct user registration form alter and try to change "1" to 1.

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

  $form['field_gender']['und']['#default_value'] = 1;
    <---or --->
  $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = 1;

}


how to add html elements inside block and get data when saving

Does it have to be in a block?

If you want to add fields to the registration form and do something with the values when they submit, you really have to add them to the registration form itself, not in a block somewhere nearby.

To do this you can create a custom module that implements a form alter.

For example:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULENAME_form_user_register_form_alter(&$form, &$form_state) {
  // Add your fields.
  $form['firstname'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#description' => t("This is help text that will display with this field. you can leave it off if you don't need it."),
    '#required' => TRUE, // Leave this line out if you don't want a required field.
    '#weight' => -10, // This controls the field order. Smaller number is higher up the form.
  );
  $form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
  );
  $form['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
  );

  // Add your own submit handler to save the values.
  $form['#submit'][] = 'MODULENAME_custom_submit_handler';
}

/**
 * Custom submit handler for user register form.
 */
function MODULENAME_custom_submit_handler($form, &$form_state) {
  // Do whatever you need to save the values here.
  // Submitted values are in $form_state['values'] like this.
  $fname = $form_state['values']['first_name'];
  $lname = $form_state['values']['last_name'];
  $company = $form_state['values']['company'];
}

Now having said all that, is there some reason you want to do this custom?
It is possible to use a module that lets you add fields to the register form, like the profile2 module.
That module lets you add profiles (essentially a group of fields, similar to a node) to users, which can also be displayed on the registration form for the user to fill out at that point.

The module handles saving the data for you, along with a lot of other features, like views support.


Unit Testing code that retrieves content

By definition, when unit testing your function you should focus on the logic the unit delivers, which, in your case, is the following conditional logic:

IF (nid IS NOT FOUND) OR (a node for a found nid HAS NO CONTENT)
  => FALSE
ELSE
  => NODE.CONTENT

That being said, you could:

Mock the two internally-used methods:

methodA:

CaseA1: returns an empty result (no nid found)
CaseA2: returns X as a nid
CaseA3: returns Y as a nid

methodB:

CaseB1: Given X as a parameter returns an empty result (no content found)
CaseB2: Given Y as a parameter returns some dummy content

Assert that the retrieve() method returns for each of the following cases:

CaseA1: FALSE
CaseA2+CaseB1: FALSE
CaseA3+CaseB2: TRUE

This is not very "deep" testing, but your function does not carry much logic. It is still testable in this minimal way.

Good luck!


Configuration management with different database and websites

Basically you need to make sure both sites share the same UUID.

Do you have drush? If so:

In the shell of your old site (copying from) get the UUID

drush cget system.site uuid

(You'll get something like 'system.site:uuid': bfb11978-d1a3-4eda-91fb-45decf134e25 - copy the value)

Then in the shell of your new site (copying to) set the UUID

drush cset system.site uuid <your_uuid>

EG: drush cset system.site uuid bfb11978-d1a3-4eda-91fb-45decf134e25

Then if you get an error something like "placeholder ... These entities need to be deleted before importing." run this command:

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

After all that, drush cim sync -y should allow you to sync the settings between your environments.

Source


Make flippy pager appear in full content view

I found an answer to this. I am also going to post the answer to drupal.org. I modified flippy.module using the following changes:

--- flippy.module.orig  2013-03-10 13:14:53.000000000 -0500
+++ flippy.module       2013-03-10 13:19:09.000000000 -0500
@@ -233,6 +233,8 @@
   // for getting node type
   if ($node = menu_get_object()) {
     $vars['node'] = $node;
+  } else {
+    $vars['node'] = node_load($vars['list']['current']['nid']);
   }

   $label_type = variable_get('flippy_label_type_' . $vars['node']->type, NULL);
@@ -315,7 +317,8 @@
   if (!is_object($node)) {
     return FALSE;
   }
-  return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  //return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  return variable_get('flippy_'. $node->type, NULL);
  }

 /**

Notes: This should be an option selectable in the module UI. Probably not everyone wants the pager in a view. Also, I'm not sure why menu_get_object() is really needed at all, since the current node is already available in $vars['list']['current']['nid'].


Inheritance value from the exposed filter

Try replacing

function customSearch_views_pre_view(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

with

function customSearch_views_pre_execute(&$view) {
  if ($view->name == 'search') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_price2_value']['value']['min'] = $view->exposed_input['field_price1_value']['min'];
    $filters['field_price2_value']['value']['max'] = $view->exposed_input['field_price1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}

And then clear your cache.


Getting Bootstrap Carousel to set Active class?

Looks like a bug occurs on this line for the 2nd Carousel where $key never equals $first_key – No Sssweat

That's exactly the answer!

    <?php foreach ($rows as $key => $row): ?>
      <div class="item <?php if ($key == $first_key) {print 'active';
     } ?>">
        <?php print $row ?>

    <?php endforeach ?>

Whoever set up the site or theme commented out the part about printing "active" in the  class list.  Probably so it wouldn't auto-rotate, but unfortunately it also made it become hidden when the screen is made narrow.


OK, you really have two options.

One is to put a more specific rule in your media query sheets.  So, you would need to place a rule in mytheme-alpha-default-wide.css  Normally, this comes before the grid sheet, so you either need a more specific rule or !important.

.zone-content .container-12 { width: 1300px !important; }

Your second option is to implement implement a hook_css_alter(), find the wide sheet for your grid system (eg, alpha-default-wide-24.css), and then swap it out with your own version.  Then, in your own version you can do something like:

.container-12 { margin-left: auto; margin-right: auto; width: 1200px; }
.zone-content .container-12 { width: 1300px; }

And, as a side note, you will likely have issues due to redefining the grid width.  The grid classes inside it will not work as expected.


How to edit personal contact form e-mail content - Drupal 7

I don't believe that this can be done through the admin panel though it is quite easy through a module using hook_mail_alter()

if it is the drupal core contact form then use this in YOUR_MODULE.module

function YOUR_MODULE_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    //MODIFY THE MESSAGE HERE
  }
}

(always remember to clear caches after adding a hook)

It is a good idea to get the devel module and add

dpm($message);

see what the variables are that you want to modify and enjoy.


How to change to default Localization Client language to translate

No.

The reason is the way the Drupal translation system is built. Original strings (defined in modules) must be written in English. This means all translation will be from English to X-language.


You can use the Block class module which adds a field to each block where a class can be added.

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent <div class="block ..."> element of a block.


The Webform module for Drupal 8 supports a Computed Twig element which can be used to combine and calculate a dynamic value using Twig based on multiple elements.


I think you have to believe that node_save() is doing its job.  But, if you don't, node_save($node) is declared as sending $node by reference, so, if anything changes $node during the node_presave() hook, it will be reflected in $node after the fact.  That notwithstanding, if you wanted to be perfectly sure, you could do something like:

$nid=$node->nid;
node_load(NULL, NULL, TRUE);
$node=node_load($nid);

if ($node->.....

which would clear any node caches in your page and then reload the node from the database before your if check.

ADDITION:

From your example, the failure logic imho should be in your generation of the taxonomy value, not in worrying about if node_save() has or hasn't done its job.  For example:

   // assuming we have $node populated

   $some_taxonomy=programmatically_created_tid($args);

   if ($some_taxonomy !== FALSE) {
     $node->field_some_field['und'][0] = array('tid' => $some_taxonomy);
   } else {
     drupal_set_message(....
     watchdog(.....
   }

where your function looks something like this:

   function programmatically_created_tid($args) {

     // do whatever logic is necessary to generate the tid

     if ($success) { // success
       return $tid;
     } else {
       return FALSE;
     }
   }

would alert the user to the problem you are actually concerned about.


You can use Corresponding Entity References to achieve this.

Follow these steps:

Create two content types: Region and City.
Insert entity reference field: Cities in Region and Region in City.
Now enable Corresponding Entity References and update its configuration by going on your site: Configuration >> System >> Corresponding entity references.
Check this configuration: Correspond Region on node(s) of type city with Cities on node(s) of type region.

Now in next tab Updating existing entities of entity type: node.


ajax update seperate page when a button is clicked on a popup

If you are using JavaScript to open your new window, you can assign that window a name and refer to its parent (or refer to it from the parent, as well). One site that explains this is at http://www.codeproject.com/Articles/25388/Accessing-parent-window-from-child-window-or-vice


Tried several things, but the one bulletproof solution that I could come up with is to use Views Attachments

add a page display, filter by node type 1.
add an attachment display, filter by node type 4, attach to the page display, after its content.

Repeat 2 for each of the remaining node types in the desired order.

It will be a big view, but should do the trick.

Edit: that is the best solution I came up with, without an extra module.


How can I add static text into a Views exposed filter block?

You can do this with Better Exposed Filters.

Enable the module and then navigate to your view edit page.  Under Exposed Form, click Basic, which is next to Exposed form style, and change it to Better Exposed Filters.  Add a Description of "or" to your title.  This will place the text on the page; you will then need to style it with CSS to place it where you want.


Hiding empty section of a custom content type if field is left empty

If I'm understanding your question correctly, you're testing for a string in $fields['field_text']->content and finding that even when it seems to be blank, it still prints the table.
You might try outputting the contents, like

var_dump($fields['field_text']->content);

Perhaps there is some "invisible" content, like

If that's the case, then you could strip that out before testing for the existence of a string in the variable.

$tmp_content = strip_tags($fields['field_text']->content,'
');
if($tmp_content):
// print table, etc.


Department-based web site in which users can only edit content in their own department

You should look at the Organic Groups (OG) modules.

With OG, departments (i.e. "groups") is set up and managed by means of the graphical user interface.  It simply provides a way to delimit a department in terms of content and members.  Unlike the Spaces module, there is no total separation between departments.  OG modules presents an evironment where departments appear to exist side by side within a single website. In other words, the groups are non-hierarchical, leverage the same theme and share common modules, etc.

Within this framwork, OG can provide multiple levels of privacy and membership.

It allows one to create content types that can associate any number of nodes to a group node. Then, developers and users can create pages that only display content intended for that particular department.

Note, however, that OG does not provide a base URL for a department namespace (e.g. http://example.com/startrek/ for a department named "Startrek".)  If you want this, the convention approach has been to install OG + Spaces + PURL to get this.

However, this article suggests an alternative approach building on a sandbox module named OG Token.  I haven't tested this tho'.  There is also another bridge module, named OG Purl that may do this for you.

Alternate, lightweight solution: If you can relax the requirement that all departments shall have access to the same content types, you can implement this with the core alone (i.e. without any external module), just using Drupal's built-in ability to clone content types and built-in role based access.

For instance, let say you want to have a department named "Startrek" (for fans of the classic TV-series).  Clone the Article content type and call the clone "StartrekArticle".  Now create a role named "StartrekEditor".

Navigate to Administration » People » Permissions and scroll down do the Node section.  Grant the role StartrekEditor the following permissions:

StartrekArticle: Create new content
StartrekArticle: Edit own content
StartrekArticle: Edit any content
StartrekArticle: Delete own content
StartrekArticle: Delete any content

Now, just give any user that is going to be editor in the Startrek department the role StartrekEditor.

Also note creating department-specific content types have no impact on the user's ability to view content.  The Drupal default is that any user may view any content, and users will not even be aware of the fact that they're viewing content in different departments that differ by name only.

To have a base URL for a department namespace using this lightweight solution, you still need to install PURL, but you will not have to deal with heavyweight modules such as OG + Spaces.


How to get the list of fields which are referenced to particular vocabulary

The vocabulary that a term reference field is associated with is held in the data column in the field_config table. Unfortunately that's a serialised PHP array so there's no clean way to query it directly.

The Field Info API doesn't seem to have a function to query fields by type so you'll need to implement your own. The basic logic would be to grab a list of fields that have the taxonomy_term_reference type, along with their data, then loop through each to determine if it has the correct vocab assigned.

Something like...

function MYMODULE_term_reference_fields_by_vocab($vocab) {
  $args = array(':type' => 'taxonomy_term_reference');
  $data = db_query('SELECT field_name, data FROM {field_config} WHERE type = :type', $args)->fetchAllKeyed();

  $field_names = array();
  foreach ($data as $field_name => $info) {
    $info = unserialize($info);

    if ($info['settings']['allowed_values'][0]['vocabulary'] == $vocab->machine_name) {
      $field_names[] = $field_name;
    }
  }

  return $field_names;
}

You'll probably want to add a static caching mechanism to that for performance, but it'll work as-is if that's not important.


How do prevent other users from seeing certain views in a user profile?

This is honestly, a question that I have faced many times.
You have 2 options.

Use a path like /my_posts and then using UID argument with "logged in user" as the failback argument.
This is a common wa. Modules like Flag comes with default Views that uses "logged" in user as the failback argument so it doesn't need to mess with php.

However, the ideal solution would be,

A. Add the UID argument as necessary (user reference, author, etc).

B. Set When the filter value is NOT available to Provide default value and then to User ID From URL.

C. Check Specify validation criteria. and choose "php code".

<?php
global $user;
if ($user->uid == $argument && is_numeric($argument) && $argument >0 ){
  return TRUE;
}
?>

D. 'Action to take if filter value does not validate'  => Display "Access Denied"

Good luck!


Best way to integrate "customization" to the front page

As a possible starting point, you might use the Panels and Panelizer modules.

When you define a custom CTools page (using the Page Manager module included with the CTools module), you can define its layout and content.

Concerning your second question, it is also possible to edit the page without moving to the administrative interface, by using the IPE (In Place Editor) provided by Panels.

You should be able to find many tutorials about Panels, in drupal.org too: https://www.drupal.org/node/1857644


Pass php variables to js without drupal behaviour

You can follow document.

  Attaching configurable JavaScript

  In some cases, you may want to add JavaScript to a page that depends
  on some computed PHP information.

  In this case, create a JavaScript file, define and attach a library
  just like before, but also attach JavaScript settings and have that
  JavaScript file read those settings, via drupalSettings (the successor
  to Drupal 7's Drupal.settings). However, to make drupalSettings
  available to our JavaScript file, we have to do the same work as we
  had to do to make jQuery available: we have to declare a dependency on
  it.

  So that then becomes:

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

  and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

Where 'bar' is some calculated value.

  Then cuddly-slider.js will be able to access
  drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

In your case. You need use hook_preprocess_node() to add array geofield.

function YOUR_MODULE_preprocess_node($vars) {
  // You nedd process to get $geofield
  $vars['#attached']['drupalSettings']['geoField'] = $geofield
}

and file js/my-googlemaps.js you need code.

(function($, Drupal, drupalSettings) {
  Drupal.behaviors.yourbehavior = {
    attach: function (context, settings) {
       var geoField = drupalSettings.geoField.
      // You can init map here.
    }
  };
})(jQuery, Drupal, drupalSettings);


drupal not detecting function in custom module's inc file

By default inc files are not included(only module files are included). They should be called explicitly like below before making a call to a function in that file.

module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');

Further Reading on inc files and how they differ from .module files : https://drupal.stackexchange.com/a/54069/4876


The player uses JS to load the current track title into the pushtape player block based on the audio link for the current track. Basically all the script does is take the inner HTML of the original audio link and copies it to the global player block in .pt-current-track-title. Anything between the audio's link tag will show up as the current track title.

Track title

So what you could do is find whatever is generating the .pt-link link markup and add a small img tag next to the track title and upon playback it would get copied to the global pushtape control block when it is the current track.

  Track title

You might want to add some additional span markup to make it easier to style.

Also if you want to learn more, check out the pushtape-player.js github page for more details about how the script works. The Drupal module is basically just a wrapper for it.


Create a new page of particular content type and make it home page during drupal installation

You should do it in the same way as in common module. Your code will be in files YOURPROFILE.install and YOURPROFILE.profile.
You can see, for example, how new content type “Article” created in Standard profile. To set front page programmatically you can easily call variable_set('site_frontpage', $path);

If I needed to create this functionality, I would create a content type, a view and a Feature with my content type and view. Then I would add Views, Features and my Feature module in dependencies. So I wouldn't write any PHP code in my profile except maybe setting front page.

Other way is to create your own module with your own hook_menu(), page callback and all the staff you need. Then again you should add this module in profile dependencies.
Modules from dependencies can be placed in profile folder or downloaded manually to sites/all folder.
Of course, you can add all the code from such module to YOURPROFILE.profile and it will work, but I think it can be difficult for support.

Reading:

How to Write a Drupal 7 Installation Profile
Drush Make theory for happy profile development


This might happen for a couple of reasons. Here are some pointers:

Make sure your module implementing the migration is enabled (I believe you must have checked that already).
Make sure your migration classes are registered with Drupal using the files directive in the .info file.
Make sure you clear the cache, especially the class registry.

I hope it helps! I'm currently stuck in a D8 migration.


In Twig, drill down to the timestamp value:

node.html.twig:

{{ content.field_name['#items'].value | date('F d, Y') }}

For a loop, do:

{% for items in content.field_name['#items'] %}
  {{ items.value | date('F d, Y') }}
{% endfor %}

field.html.twig:

{% for item in items %}
  {{ item.content["#markup"] | date('F d, Y') }}
{% endfor %}

Note: Set field format display option to plain or custom if using the field template. This field option can break your site just by someone changing the format option for the field, so use caution.


How to merge multiple fields into one, across multiple content types?

By using Views (to build a list of nodes to be updated) and a combination of Rules and VBO (to mass update such lists) you should be able to perform the merge of those fields.

Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that, which is about a variation of your scenario (ie change the value of an existing field, while you want to "copy" the value of an existing field to the value of a new field).

For your case, this example of a Rules Component (in Rules export format) should be close to one of the Rules Components you'd need for your "field_image":

{ "rules_set_an_initial_value_for_image_field" : {
    "LABEL" : "Set an initial value for image field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_image" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-image" ], "value" : [ "field_article_image" ] } }
    ]
  }
}

Note: by using an approach with modules such as above (instead of SQL magic), you do have the advantage that all possible relatic magic will happen automagically and behind the scenes (eg: create a new revision of such nodes). And it avoids your Drupal database gets corrupted because "you forgot some table".


How to resolve the "undefined variable" notce when I put a flag on a Views page?

The error arises because there is no $node variable defined in the scope.
Try looking inside the $results variable; something like this should work:

<?php print flag_create_link('subscribe', $results[0]->nid); ?>

This will print a subscribe link for the first row of the view.
Also, you have to ensure that the nid is present in your result object. It should be already there, but if not, add the "Content: Nid" field and hide it by checking the "Exclude from display" option.


Allow users to submit content that is approved before it is published

You might want to try: http://drupal.org/project/workflow & http://drupal.org/project/formfilter

If you create a workflow you can set it to only allow users to create content in the 1st state, something like "needs review". Then, an admin can come in and progress to the 2nd sate, say to "published".

I used an action and trigger to automatically publish any content placed into the 2nd state.

You can use the form filter to disable the ability to set the content straight as published in the normal node edit form.

Ideally you will want some type of approval queue too, you can use the default Workflow summary but I think this requires views.


How to add a correlated subquery expression in hook_views_query_alter?

This doesn't answer the question as stated, but provides a very simple approach to get at the result using Views without implementing hook_views_query_alter.

The example provided is for workbench_moderation, although the principle applies in other scenarios as well:

Creating a new Workbench view showing recently updated content and its state


Unless you URL encode, the fragment (what you have after the # sign) is not sent to the server.

If you want to include the hash in the destination parameter, it has to be URL encoded.

  http://example.com/modal_forms/nojs/login?destination=comment/reply/NID%23comment-form

Note the %23 above. It makes the browser think that the fragment is part of the destination parameter.


How can I automatically rotate a picture?

ImageCache Actions seems to provide an "autorotate" feature. If server has  Exif PHP extension enabled, and user's camera saved orientation in EXIF data, it automatically rotates image correct side up.


I have created a module that only allows logins through services.. therefore, you can only create a node through services if you use it in conjuction with a Session Limit, or other module which prevents multiple sessions.

http://drupal.org/sandbox/tpainton/1851382

Still experimental but please try, and if you find bugs, report.  Hope it works for you.


Custom javascript file not working in mobile browsers

It seems like your code is the problem. You have extra });

Should be

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      $(document).ready(function() {
        // code goes here
      });
    }
  };
})(jQuery);

But it is nonsense to use $(document).ready as it is already handled by Drupal.behaviors.

So the proper way is.

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      // code goes here
    }
  };
})(jQuery);

The attach() method is called when the DOM has loaded both initially and after any AJAX calls.

See this doc for more info. https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How to Add "Add to cart" Button in product categories display

Here's the code I that built the add to cart button using a specific product_id:

<?php

$form_id = commerce_cart_add_to_cart_form_id(array($product->product_id));
$line_item = commerce_product_line_item_new($product);
$line_item->data['context']['product_ids'] = array($product->product_id);

$form = drupal_get_form($form_id, $line_item);
// render your $form somewhere

?>


Problems displaying full article - teaser only

It sounds like the "Format" for the Default display is wrong. What is the "format" value shown in http://YOUR.DOMAIN/admin/structure/types/manage/YOUR_CONTENT_TYPE/display? Typically it should be "Default". If the Default Display is set to "Summary or Trimmed", then you'll get the effect you mention, with the Summary in both the Teaser and Default versions.

You can check this by changing the settings and doing Preview on the node edit page. Preview shows the Teaser and Default versions simultaneously.

Also, is "Custom Display Settings" checked for the Full Content, or just the Teaser? Typically it would be just the Teaser. If you have set Custom Display Settings for Full Content, then check the settings as above.

By the way, <!-- break --> works fine in Drupal 7. I use it.


How to turn off url aliases on dev site?

I think the problem is that the {url_alias} still has the aliases in it.

My suggestion would be to take a backup, then delete a few manually from "admin/build/path" (Drupal 6) or "admin/config/search/path" (Drupal 7), and then try the "node/nid" paths for the entries you deleted.  Then, take another backup :) and either delete them via the Delete aliases tab.


How to prevent users from changing Workbench Access Section

Users can only assign a node to a workbench access section if their user or role has permissions to do so? But perhaps it gets tricky with assigning permissions to the different transitions too.

Anyway, you can lock the workbench access field on node edits, so they can't lock themselves out if you like:

<?php
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Make sure this node type actually has workflow_access stuff setup.
  if (isset($form_state['node']->type) && variable_get('workbench_access_node_type_' . $form_state['node']->type, 1) == 0) {
    return;
  }
  // Once the page has been created, don't allow changing the workbench area again.
  if (preg_match("/^node\/([0-9]+)\/edit/", current_path())) {
    $form['workbench_access']['#disabled'] = TRUE;
  }
}


Help with rules - remove shipping option if coupon applied

Check for shipping address and coupon code application in the same rule.
events: "After updating an existing commerce order".
conditions: your conditions
actions:
Condition IF -> "Coupon code for a particular discount has been added to the order"(Select your 10off discount from drop down list) -> "Remove all shipping line items from the order".
Condition ELSE -> "Apply shipping rate to an order".

Although your business logic may require a different approach.


drupal_get_form('user_login');

And

drupal_get_form('user_register_form');

Will return the form for you and will deal with all the form stuff that needs to be dealt with. You just need to print whatever is returned by that function out and it should work.

Note: You did not specify the Drupal version, when using 7, drupal_get_form() returns an array which you need to pass through drupal_render() first to get a string that you can print.


How to split content for different target audience?

@max I am assuming that since there is a 1-1 relation between 'private' and 'business' content, you are probably just hiding (restricting) content in on of the two.  So if for example, your 'private' content is only available to authenticated users, or user who paid for the content, then essentially the other (business) content is a reduced version (teaser)?

If that is the case, then maybe you can consider using different display modes for the same node - in other words, you only have one node for both business and private, but with different view modes.  The one with restricted access (lets assume that is business) will show nodes using the 'teaser' view, while the other will render the node using the 'full' display mode.

It should be easy enough to change the display mode dynamically on load / render based on the user's status (logged in, paid for content, etc).

The other option, and you could even combine this, is to use content access modules, specifically field level access, to automatically control which fields will be rendered or not.  So in this configuration, you could always render the node using the same (possibly different) display modes, but based on the authentication level of the user, simply do not show the field: I can confirm that I have personally used this and it does work (http://www.startnetwork.org).

All things being equal, I would personally only have one node (as opposed to 2 implicitly related nodes) and then simply control what information (or how much) is shown.

If you have any questions - please let me know: happy to help.


Drupal 7 Custom Theme - Administration menu missing or not showing

You need to print the $page_bottom just before the  tag in html.tpl.php.

You do need $page_top too, and $page, so taking the default html.tpl.php as an example:

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>


How do I manually configure the Link module?

You can override that in a container services file.

For example, create/edit /sites/default/services.yml, and add/alter the following lines:

parameters:
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
    - file

and make sure you have this line uncommented/added to settings.php:

$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';


I found a solution that worked for me via this article.

The author propose to change the Commerce view settings.


Database password changed and I am not able to access my site

You can edit settings.php (located in sites/default) to change database information like username and password.


Drupal 7 hook_block_info and hook_block_view permission wise display

An easy solution is just to check the user role in hook_block_view():

function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'payouts':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'commission_payments':
      if (in_array('Site Owner', array_values($user->roles))) {
        $block['content'] = t('Hello Site Owner');
      }
      break;
  }

  return $block;
}


Should I save temporary data in $form_state or in my form class?

While the storage in $form_state can be cached, the class property can't. So if you build a multistep form you would need to use the first option.

And a validate or submit function is not necessarily in the same class or in no class at all if it is defined in a hook. This also answers the related question.


Extract email addresses from composite field type using Computed Twig

I'll provide 2 links as an answer, but it has really been answered by others.

Write custom webform handler:

How to create a custom Webform handler to submit to a SOAP API

Use hook_form_alter() to add a custom submit handler.

Add a custom submission handler to a form

Drupal 8 version of hook_form_alter(): https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.8.x


How do I preserve custom files in my Drupal configuration across minor core upgrades?

You can build a site totally with git to help manage this process. The process is basically

Git clone into your DOCROOT:

git clone --branch 7.x http://git.drupal.org/project/drupal.git /var/www/mysite/docroot

Rename the remote:

git remote rename origin drupal

Checkout the latest tag, and make a site branch for your site:

git checkout 7.26
git branch -b mysite

Now, you can build your site and customize robots.txt and .htaccess to your needs.

When there is a core update, you can:

git fetch drupal

and then use the normal git methods for merging your changes in, eg:

git merge 7.27

or you can preview what will happen, check for conflicts, etc.

If you do this, you need to make sure you don't do a plain:

drush pm-update drupal

as this will then mess things up. I do not think that drush pm-update --lock=drupal works to prevent this.


Create a Corresponding Entity Reference preset programmatically

[EDIT]

Almost a year later, I found a better way (the entity_import way actually did not work).

CERs are entities. The best way to create one is using $cer = entity_create('cer', array('bundle' => 'cer'));   adding appropriate values to the fields of the created entity, and saving it by using entity_save('cer', $cer);

=======================

Finally figured it out. You can use the entity_import function.

Create a variable containing a JSON-like string of the entity (which you can get by exporting a CER entity), something like:

$j = '{
  "identifier" : "node:time_slot:field_ref_student*commerce_line_item:registration:field_ref_slots",
  "cer_bidirectional" : { "und" : [ { "value" : "1" } ] },
  "cer_enabled" : { "und" : [ { "value" : "1" } ] },
  "cer_weight" : { "und" : [ { "value" : "0" } ] },
  "cer_left" : { "und" : [ { "path" : "node:time_slot:field_ref_student" } ] },
  "cer_right" : { "und" : [ { "path" : "commerce_line_item:registration:field_ref_slots" } ] },
  "rdf_mapping" : []
}';
Then import and save:

$e = entity_import('cer', $j);
entity_save('cer', $e);


REST Post creating entities with relations

Okay so this issue is actually a bug. For me the issue was fixed by applying the latest patch for now, likely the patches will need work and tests.

There were issues with my request and I have changed them above to reflect how an actual comment request should look like ( at the time I am writing this ).


How do I get JSON data from a custom entity

Dou you have an access control handler or an admin permission to control view/create/update/delete access to your entities?

You need to have that, in addition to the rest specific permissions. In fact, those will go away in 8.2, only the generic entity access will matter then.


It's a generic term to encapsulate all the programming interfaces Drupal provides. Any further meaning would have to be inferred from the context of how it was used (FWIW, I've never heard "Drupal API" to refer to the documentation site api.drupal.org).

When specifying a particular component of the Drupal API, you'll often see it labeled with its functionality (e.g. Drupal Routing API, Drupal Batch API, etc.) to clarify what part of Drupal's API is being discussed.


Hide default "all" parameters from Views Querysting

This is a known issue that hopefully will be solved in Drupal 8.

I accomplished it with JS:

jQuery(document).ajaxComplete(function(e, xhr, settings) {

let src = window.location.href;
let url = new URL(src);
let title= document.title;
let re = /all/;
let props = [...new URLSearchParams(url.search)]
            .filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();

history.pushState(null, null, ("/page?"+params.toString()))

});


Redirect After User Registration if Referred from Specific URL

I think you need to set the redirect in a submit handler. Add your custom submit handler to $form and then in your custom submit handler set $form_state['redirect'] to where you want it to go. Doing it in a form_alter could be why it's not working. See Redirecting a Form

function my_redirect_form_my_content_type_node_form_alter(&$form, &$form_state){
  $form['#submit'][] = 'my_redirect_node_form_submit';
}

function my_redirect_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/10'; // the address of your thank you page
  // if you are really, really determined to force the redirect, even if a destination has been set in the url, add this:  unset($_GET['destination']);
  // you could also add a message (this is in addition to whatever message is produced by the nodeapi function): drupal_set_message(t('Congratulations!'));
}


How does one add a new base field to a content entity?

Adding fields just works. Define the new field, run update.php, it will compare the new and existing definitions and figure out that there's a new field to create.

Renaming/deleting fields works too, but only when you have no data. When you have data, then you will still need to write an update hook, or a migration. We're missing documentation on how that will look exactly, but basically, you use the same schema functions as in 7.x and then update the last installed field definitions.


How can I display multiple images of single image field each in a different row?

Well, on the same view, on English side of the website the view displays same field, of same field of the same node ID, on separate view rows.

Problem disappeared after the field configured to be to be translate.

Now display every item (image) on its own views row as expected.


drupalSettings object not showing for anonymous users. core/drupalSettings is added as a library dependency

Solved the issue... and the answer is weird...

within the html.html.twig file, we have a <div class="body-inner"> tag that wrapped the <js-bottom-placeholder token="{{ placeholder_token }}"> placeholder.

For whatever #drupalWTF reason, if this placeholder tag is wrapped inside of a div, drupalSettings will load an empty object. Once I moved it directly underneath the body tag, it worked fine.

Hope this helps someone!


Send Commit message on Acquia Hook by Slack

The commit message isn't passed in to the script, so you have to get it from somewhere else. I'm not sure if there is a git repository available to the cloud hook scripts on Acquia's cloud servers in general (it seems like there must be, but...I can't find an answer about where it is in their docs). You do have the repository url and the branch/tag, so you could try a shallow clone of the tag to get the data:

git clone --depth 1 --branch $deployed_tag $repo_url clonedirectory
cd clonedirectory
commit_message=`git show -s --format=%B`
...
echo $commit_message

You can use the $commit_message variable in the slack commands.

Of course...you have to figure out how to authenticate to the git repo and I'm not sure what's a great solution there.

Really I hope someone will reply with the location of a git clone that's available on cloud servers.


Breadcrumbs stopped going to third level

You can search for theme_breadcrumb(), they may develop it with this function ( search in template.php )


When you use db_query() the query is executed for you, I think the error you're getting is because you're re-running execute() on it. Also it looks like you're trying to interpolate variables into a string using single quotes, when you need to use double quotes (or none at all in your case).

Try this:

$q4 = db_query("
  SELECT MAX(nopeserta) AS nopeserta FROM {1_jp_peserta} WHERE jpke=:q1 AND lomba=:q2 AND kelamin=:q3", array(':q1'=>$q1,':q2'=>$q2,':q3'=>$q3))->fetchAssoc();


This is more a CSS question I think. I solved this problem already for various sites using another menu block, with its own css markup, or using a jump menu.

Using media queries you will have to set the threshold on where to break:

@media all and (max-width: 370px) {
    .default-menu-region {
        display:none;
    }
    .mobile-menu {
        display:block;
    }
}

@media all and (min-width: 371px) {
    .mobile-menu {
        display:none;
    }
}

Adaptive theme provides files for those media queries already, you can just drop your custom content in there instead of writing new media queries like in this example.


Since you're using Views and the user name. All you need to do is:

Add a Contextual Filter, User: Name
Under it's settings pane, under WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED, check Override title
Then just input %2

So now /person/jon-doe/roster would display as jon-doe as the page title.
If you would want the user's normal name like Jon Doe, then you could follow Immanuel Paul's answer because you aren't basing the page title literally from the URL.


Bulk Delete Custom Entities (Not Entity Types)

You can  delete multiple entities using below API functions

entity_load

  Load entities from the database.

  The entities are stored in a static memory cache, and will not require
  database access if loaded again during the same page request.

  $entity_type: The entity type to load, e.g. node or user.

  $ids: An array of entity IDs, or FALSE to load all entities.

entity_delete_multiple

  Permanently delete multiple entities.

For Example to delete all node entities

<?php
  $results = entity_load('node');
  $entity_ids = array_keys($results);
  entity_delete_multiple('node', $entity_ids);
  ?>


How to add rel=author when you have "multiple authors" in one site?

This is simple.

Add a text field to the user profile at /admin/config/people/accounts/fields and call it Google Profile (or similar).
Go to the Metatag configuration page and look up the token for Google Profile.
Add this token to the Author Metatag for the relevent content type(s). The token for my setup is: [node:author:field_google_profile]
Have every author load their Google+ profile to this field in their user profile.

[EDIT] It's worth noting that Google no longer uses rel=author as a ranking factor, so this discussion is now purely academic.

Regards

David


How to allow users unsubscribe without logging in by changing the value of a custom field?

This can be solved using the form API.

Define a path using hook_menu().
Define an unsubscribe form for the menu path.
Write a validation handler to check the email address.
Write a submit handler for the form.


Panelizer settings page not found for OG group node

It turns out that this is correct, though not very user-friendly, behavior. The user must enable a default panel, or trying to set settings for the default panel will not work.

on admin/types/manage/[nodetype]:


Populate a Chosen select list from a view

You can programmatically invoke a view to retrieve data and process it as needed:

  // Example select form array
  $form['my_selectbox'] = array(
    '#title' => t('My Select Label'),
    '#type' => 'select',
    '#description' => t('My select label.'),
    '#options' => array(),
  );

  $view = views_get_view("my_view_machine_name");

  //use "default" for default display
  $view->set_display("my_view_display_machine_name");

  // @TODO: Alter any other view properties
  // (e.g. exposed_input, offset, etc.) as needed

  // Pre execute & execute view query
  $view->pre_execute();
  $view->execute();

  // $view->result contains an array of row objects inside the view.
  // the properties will vary based on your view
  foreach ($view->result as $row) {
    $form['my_selectbox']['#options'][$row->nid] = $row->node_title;
  }


I got it: The theme ID should be user_register_form, not user_register. Now it works.


Form API submit with AJAX removes wrapper element?

If you don't want to 'replace' element with id 'view-cont', use another 'method', like:

'method' => 'append',

And if you in fact want to replace it, modify fung_filter_form_callback to make it return div with that ID again - that way you will replace original div with another div of the same ID, and will be able to repeat that process.


How to add library if Ajax is enabled for view?

Found my answer after doing ksm($view)

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->ajaxEnabled()) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}


How do I create sub-pages for a custom content type?

Take a look at pathauto and Entity Reference field


Adding Roles with Rules upon Webform submission not working — Why?

Okay, it looks like I figured it out:

 Event: After a webform has been submitted
 Condition: Webform has name

   Parameters:

      The form id of the submitted form: [form_id]
      Webforms: Mid-program quiz

 Action: Add user role

   Parameters:

     User: [user]
     Roles: Mid-program quiz: Passed

So the confusing things to watch out for are:

 "After a webform has been submitted" is the one to choose, over "After a webform submission has been added."
 Webform Has Name has first parameter as ID and second as the webform (as selected from a list of webforms). It makes it seem like you're saying nid has to be equal to a title, which doesn't seem like it would work, but that's apparently not what's happening.
 Add user role takes simply Parameter:user, rather than site:user or any other attribute of user


How to assign a rendered view result to a variable without displaying it on the screen?

This turned out to be an issue with the views_datasource module, not the views module.  Solved by enabling "Views API mode" in the View settings.


How to add condition for 1st Iteration in views-view-fields.html.twig file

If your code snippet is within a for loop, you could use either loop.first or loop.index in your if statement to target the first iteration.
 Refer to https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

Thus your twig template would probably resemble:

{% for item in items %}
  {% if loop.first 1 %}
    {% set tag = "active" %}
  {% else %}
    {% set tag = "" %}
  {% endif %}

... render row/field with class in template ...
{% endfor %}


Things to try:
http://groups.drupal.org/node/242443
http://groups.drupal.org/node/210683

But in reality we don't know until you can profile the code.
http://getmuhammad.blogspot.com/2011/08/installing-xdebug-and-webgrind-on.html


Issues with namespaces and Migrate module migrating XML content

A few things had to be changed.

public function &xml() {
    if (!empty($this->currentUrl)) {

      // $this->currentXml = simplexml_load_file($this->currentUrl);

      // simplexml_load_file wasn't explicit enough, change to file_get_contents
      // then explicitly call it a new SimpleXmlElement.

      $xml = file_get_contents($this->currentUrl);
      $this->currentXml = new SimpleXmlElement($xml);

      if (!$this->currentXml) {
        Migration::displayMessage(t(
          'Loading of !currentUrl failed:',
          array('!currentUrl' => $this->currentUrl)
        ));
        foreach (libxml_get_errors() as $error) {
          Migration::displayMessage(self::parseLibXMLError($error));
        }
      }
      else {
        $this->registerNamespaces($this->currentXml);
      }
    }

    return $this->currentXml;
  }

However, the major issue was this function in xml.inc:

protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

The if($itemXML) needs to be changed to if($itemXML->asXML()), like so:

protected function getElementValue($itemXML, $xpath) {
    $value = NULL;
    if ($itemXML->asXML()) {
      $result = $itemXML->xpath($xpath);
      if ($result)
        $value = (string)$result[0];
    }
    return $value;
  }

After applying the patch manually and changing the simplexml_load_file and the if statement in the above functions, the import works successfully with namespaces.

I re-rolled the patch mentioned earlier with my changes: https://drupal.org/comment/8260027#comment-8260027


As you're loading all these sites from one directory: 'example.example.de'. You only have one site and therefore one settings.php file and ONE base path which defaults to the root domain.

To do what you'd like to do you'd actually need to multisite these with separate directories for each site. To the best of my knowledge anyway.


A possible solution is entering the following code into the console, where "xxx" is a part of the name of the script you want refreshed, and "yyy" its exact adress; the string after the question mark has to be changed each time to force Chrome not to cache it.

jQuery("[src*=xxx]").replaceWith('<script type="text/javascript" src="http://yyy?m2fua6ijsufsds"></script>')

It could probably make for a nice useful mini module, which would provide a button/shortcut that would automate the call.


check your CKeditor settings in the following path:
yoursitename/admin/settings/ckeditor/editg
If you find anything related to this
"your content type@node/add/your content type.edit-body" in the "Fields to exclude/include: " textarea, just remove.


This can be done with the Simplify module. Here is a quote about it (from its project page):

  Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Grouping data to be displayed in the a template.

An approach I have used at the moment is to use a preprocess hook in my template. Added the following preprocess template to a custom module

THEMENAME_preprocess_views_view_unformatted__PAGENAME(&$variables)

where variable is an array containing
- view : the view object
- rows : an array of row items and each row is an array of content.

I looped over the data and constructed my required object, which then I set as a new property resource  (i.e. $variables['resource']) of variables.

Within the template (views-view-unformatted--PAGENAME.html.twig), I then have access to the resource variable to use in the twig template. e.g {{ resource.type }} , where type is a property added to the resource variable in the preprocess hook.

Not sure if this is the best way to approach the problem, but at least it is one way of approaching the problem.


Ok, so I realise that due to the fact that the exposed filters are on one form, it will be difficult to separate the rendered elements. However, I ran some tests using jQuery to  reposition the sort elements, and so far it seems to work using the following:

jQuery(document).ready(function() {
  jQuery('div#edit-sort-by-created').appendTo('#custom-sort-block');
  jQuery('div#edit-sort-by-title').appendTo('#custom-sort-block');
});

NOTE: This breaks if Ajax is enabled in the view, but that can be circumvented using the jQuery live() function I'm sure.

It certainly isn't pretty and definitely is a hack, but it will have to do for now. I won't be marking this as the answer in the hopes that someone can suggest a more elegant and Drupaly way of accomplishing this.


Division by zero in theme_image_style_preview after moving to production server

Apparently it is not safe to chmod files to 777.

A preferred way is to chmod files to 644, directories to 755 and set the ownership to the webserver, so the webserver can write files.

Here's a script for Ubuntu:

# Change directory permissions to 755.
find sites/default/files -type d -exec chmod 755 {} +
# Change folder permissions to 644.
find sites/default/files -type f -exec chmod 644 {} +
# Set ownership to webserver.
chown -R www-data:www-data sites/default/files

Learn more on - Recommended directory permissions.


Menu token. Problem with [current-user: name]

check permissions and make sure anonymous users don't have access to that page (or set of pages, content type)


How to get programatically 'display_options' for a specific page in Views

Try with:

function association_exportCSV($view, $page) {
  $view = \Drupal\views\Views::getView($view);
  // $display_id in this case is  'rest_export_1
  $view->setDisplay($page);
  $path = $view->getPath();
  file_unmanaged_save_data($page, 'private://' . $path . '.csv', FILE_EXISTS_REPLACE);
}


Get values from unlimted field programmatically in node_presave hook

You can loop over a field object and access each item separately, that's often more convenient than going through getValue():

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     foreach ($node->get('field_class_division') as $item) {
       echo $item->target_id;
     }
   }
}

And to access a specific delta (that's what the index in a multi-value field is called in the Field API), you can access it like an array as well, but you need to make sure that the deltas exist:

echo $node->get('field_class_division')[1]->target_id

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a very useful cheat sheet on how to work with the Entity Field API.


How to add code logic to Display Suite fields without PHP in Drupal 8? Twig?

Showing hiding fields in twig is pretty simple. You can check if a field has a value like so:

{% if node.field_foo is not empty %}
  {{ content.field_foo }}
{% endif %}

You cannot execute raw PHP from a twig file, nor can you inject Twig and parse it out through field formatters (probably not without a lot of work, anyway).

Note the difference between checking the node object and rendering the content array.

You want to do checks against the entity object, and never (in my opinion) the render array. In the above code, if the field has a value, then the condition is true. If you want to check the value for a specific string, it is likely better suited for a preprocess hook.

What if the twig template being rendered is a Paragraph, and not a Node template? Not much difference:

{% if paragraph.field_foo is not empty %}
  {{ content.field_foo }}
{% endif %}

If you need more muscle, I would advise moving your logic to a preprocess hook in mytheme.theme where you can use whatever PHP you want, and inject new variables into your Twig file.

function mytheme_preprocess_node(&$variables) {
  $variables['show_foo_field'] = FALSE;

  // if field ...
  // and maybe some more conditions?
  $variables['show_foo_field'] = TRUE;
  // end if...
}

Then in the twig template...

{% if show_foo_field %}
  {{ content.field_foo }}
{% endif %}

Now, you say you are using Display Suite - I personally don't inject condition or code through the UI like what you are asking. But one thing I do know about Display Suite is it (when I last looked) tends to hijack a majority of the preprocess calls - so check its docs or API for the right preprocess hook to call for nodes.

The current hooks for Display suite can be viewed in its .api.php file.

Definitely enable twig debug to be able to check what the Twig template naming pattern should be (suggestions) in the HTML source, and be aware of mytheme_preprocess_node potentially not firing. You will need to locate the correct DS hook.


How to set form action to default contact form action

I not sure will this help you. If you have no other solution, how about try to use webform module with form builder. I not sure what you mean filter, but its help to store in database and send email easily.

Hope this help you.


How can I prefill taxonomy tags for a new node being created through the node form?

Have a look at the Prepopulate module.

Read the documentation on how to use it.


Views slideshow overlapping right hand sidebar block

I found two ways of resolving this.

Permissioning the splash screen so that only non authenticated users can see it.  That way, whenever anyone logs in they do not see the slideshow.
Use the corporate clean them - much better than anything I can develop!


Thanks can be done with with the hook_js_alter function

    function hook_js_alter(&$javascript) {
    $javascript['js/contextual.js']['data'] = drupal_get_path('theme', 'THEMENAME') . 'js/override/contextual.js';
    }