Converting a left join query with empty right side to Views On a multilingual site, I'm trying to create a view on nodes where the content should be either in the current language, or in English if no translation exists in the current language. After trying to solve this with the Views web interface for a while, I figure that what is provided for filtering is simply not sufficient.

So I'm thinking of adding module code, to extend Views to support this particular use case.

Starting from then end result, this is what the constructed query should look like:

select node.* from {node} node  -- provided by Views
-- join:
left join {node} tnode on node.tnid = tnode.tnid and tnode.tnid > 0 and tnode.language = ***CURRENT_LANGUAGE***
-- condition:
where (node.language = ***CURRENT_LANGUAGE*** or node.language='en' and tnode.nid is null)

I'm assuming that ***CURRENT_LANGUAGE*** is a macro that will be replaced by the actual value of the current language; 'en' might be an argument, chosen in the admin interface, but that is not really important.

But now I'm stuck on how to actually code this up for Views.

Any help, including alternative approaches, welcome.

You can use this function

function MY_MODULE_views_query_alter(&$view, &$query) {
    if($view->name == 'view_name'){
       }
}

https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7


D8 - Access Webform submission values programatically I have a webform whose results (some specific fields) I want to display in a table in a view. I am able to achieve that using the Webform Views Integration module. The view displays the output as

Field Name
Field Value

I want it to be displayed as

Field Value

Although it can be done via CSS using label{display:none;}, is there any way to do it out of the box or using modules?

Also, I want to overwrite the default webform submission layout which I can achieve using the answer here. But when I try to access the elements of the webform submission using {{html.fieldName}} or {{data.fieldName}}, it again prints out the label with it. I tried the nolabel filter but it does not work.

You need to apply the patch from this issue.


How do I count the number of unique visitors to Pages How do I get the number of Unique visitors to the page? I need to get Unique visitors on each page or at the content level, how can I get it?

You can not with only a Drupal instance, it's an architecture issue. But you can use Matomo (former Piwik) for such needs.

If it is a simple scenario, you could get along with setting your own visit-cookie - but you need to program a module for this. And the result will be fuzzy cause of numerous caching steps.


Delete only referenced Nodes I have created a report of each students with their paid fee invoices.

Now I would like to delete the invoices only.

Please help me out from this.

This could be solved by creating a simple view with VBO. Try this steps:

Create a view of content, without any filter criteria.
Add a relationship to the view of the reference field in the 'student' content type. Say 'field_invoice'.
Add a filter to the view of "content type", select 'invoice'. Use the relationship in the filter that was created in step 2.
Add a filter of "content title". Expose this filter. Use the relationship in this filter too.
Add a VBO field of type  "Bulk operations: Content (Content)". Select 'delete' from the operations.

From this view, you should be able to filter by name of any student. It will list the invoices. And using VBO, you should be able to delete them.


Can drush return if site is in maintenance_mode? To work in parallel with another team, I've copied via ftp the working Drupal 7 app and mysql database and am trying to get it to run. I've cleared the cache and drush happily reports connecting to the db but the home page responds with a 500 error about

Recoverable fatal error: Argument 1 passed to image_resize() must be an instance of stdClass, boolean given, called in /media/psf/Home/apps/newdom/sites/all/modules/image_resize_filter/image_resize_filter.module on line 515 and defined in image_resize() (line 279 of /media/psf/Home/apps/newdom/includes/image.inc).

I'm unable to see anything and to login. While I'm tracking down why that error is thrown, I can see in the page inspector that the css is suggesting the app is in maintenance mode. OK, looking at the drush help commands I enter:

drush vset --exact maintenance_mode 0

And it returns that maintenance_mode set to "0". But the page still looks like it's in maintenance.

My question is, can I send a command through drush to test if the site is in maintenance mode or not? I've tried leaving off the last parameter but that is required. I don't see it in the help page so maybe it does not. Drush status does not have a property for that in its list. Is there a way to verify an app is in maintenance mode by the command line?

i think if drush says maintenance_mode set to "0" it is set to 0,  none the less you can check drush variable-get but it will return 0


How to customize the comments form? For example, How can I add some classes or hide labels and instead of it add placeholder with using of ThemeName_preprocess_comment to 'subject' and 'name' comments form elements?

I have tried to usedrupal_set_message(kint($variables)); in ThemeName_preprocess_comment section, but it cause the empty screen erroe in my site.

So how can I add some classes to default (or my own created) comments elements so I can target them for adding CSS style.

How can I target default comments form element in CSS?

if you use Drupal7, you should not use

drupal_set_message(kint($variables));

but

kint($variables)

or

dpm($variables)

An example that you can see, enter in the following link:
 https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/template_preprocess_comment/7.x

function bartik_preprocess_comment(&$variables) {

  $variables['classes_array'][] = 'myclass';
  dpm($variables);

}

You can also create a file "comment-wrapper.tpl.php" and add the classes you want and placeholder.

Example:

<?php

/**
 * @file
 * Bartik's theme implementation to provide an HTML container for comments.
 *
 * Available variables:
 * - $content: The array of content-related elements for the node. Use
 *   render($content) to print them all, or
 *   print a subset such as render($content['comment_form']).
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default value has the following:
 *   - comment-wrapper: The current template type, i.e., "theming hook".
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * The following variables are provided for contextual information.
 * - $node: Node object the comments are attached to.
 * The constants below the variables show the possible values and should be
 * used for comparison.
 * - $display_mode
 *   - COMMENT_MODE_FLAT
 *   - COMMENT_MODE_THREADED
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess_comment_wrapper()
 */
?>
<?php
    //add placeholder
    $content['comment_form']['subject']['#attributes']['placeholder'] = t('Title');
    $content['comment_form']['comment_body']['und'][0]['value']['#attributes']['placeholder'] = t('Comment Body');
  ?>
<div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if ($content['comments'] && $node->type != 'forum'): ?>
    <?php print render($title_prefix); ?>

<?php print t('Comments'); ?>

    <?php print render($title_suffix); ?>
  <?php endif; ?>

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

  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

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


How do I grant edit access on workbench to specific users? All the users have a field, field_country.
All the content types have also a field, field_country.
I want the logged in user to be able to edit in workbench, his own content and the content added by other users of the same country.
I managed the first.
How can the second requirement be implemented?
Which hook should I use? Is there any example?

I solved my problem as follows:
1) Using hook_views_query_alter I fetched the desired rows. With that step I was able to see in the recent content list all the rows I want but with edit link only to the ones that the logged in user has created.
In order to see the edit to the rest of the rows whose author is somenone else I followed the step 2.

switch ($view->name) {
case "workbench_recent_content":
...
unset($query->where);
....
$where_expression = MY where statement where I filtered by content type and by a field_location field that exists on all of my content type.
 $query->add_where_expression(0, $where_expression);

2) I created a rule, on node save, grant edit access to the people that have a specific role and belong to a specific country. That way the edit link appeared even all the rows I wanted.


Dynamically add options for widget I'm developing a field widget for Drupal 8, similar to 'select' but with more functionality. Since the number of options is large and should be determined after querying an external API I was planning to retrieve options from ajax calls.

However AJAX - How to dynamically add options to select? states that it's not possible. What will be the possible workarounds or solutions?

The solution I used is below for anybody else who might have similar questions.

You can use the autocomplete_route_name property to get the options for autocompletion.

$element += array(
    '#type' => 'textfield',
    '#default_value' => $items[$delta]->value ?: NULL,
    '#autocomplete_route_name' => 'example.myroute',    //your route name
    '#placeholder' => $this->getSetting('placeholder'),
);

The route should be defined in your module_name.routing.yml file

example.myroute:
    path: <url>
    defaults:
      _controller: <controller>::<method>
    requirements:
      _permission: <permission>

Hope this helps :)


WYSIWYG module is not finding my custom plugin I am building a custom plugin. I have the WYSIWYG module 7.x-2.x-dev. I have followed the instructions here.

I realize that this question is similar to this and this. However I think this may be a slightly different issue so I am going to try a new thread.

Pertinent code:

<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function my_module_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
  $settings['extraPlugins'] = 'my_plugin';
 }
}

/**
* Implements hook_wysiwyg_include_directory().
*/
function my_module_wysiwyg_include_directory($type) {
switch ($type) {
  case 'plugins':
    // You can just return $type, if you place your Wysiwyg plugins into a
    // sub-directory named 'plugins'.
    return $type;
 }
}
/**
* Implementation of hook_ckeditor_plugin().
*/
function my_module_ckeditor_plugin() {
 $module_path = drupal_get_path('module', 'my_module');
 $plugins = array();
 return array('my_plugin' => array(
  'name' => 'My Plugin',
  'desc' => t('Custom plugin to add button styles in the WYSIWYG.'),
  'path' => $module_path . '/plugins/my_plugin/',
 ),);
}

/**
 *  Implements hook_wysiwyg_plugin().
 */
function my_module_wysiwyg_plugin($editor, $version) {
 switch ($editor) {
  case 'ckeditor':
   $module_path = drupal_get_path('module', 'my_module');
   return array('my_plugin' => array(
    'filename' => 'plugin.js',
    'path' => $module_path . '/plugins/my_plugin',
    'buttons' => array(
      'style_1' => t('Style 1'),
    ),
    'load' => TRUE,
    'internal' => FALSE,
  ),);
 break;
 }
}

This produces a blank area where the CKEditor should be and the error logs still say that it is looking in the sites/all/libraries/ instead of my custom module folder. Any ideas on what I am missing?

Turns out the tutorials and answers were wrong (at least for my set up/needs) The extra hooks and $settings['extraPlugins'] = 'button_styles'; were probably causing conflicts. I removed all but this;

function MY_MODULE_wysiwyg_plugin($editor, $version) {
switch ($editor) {
  case 'ckeditor':
    $module_path = drupal_get_path('module', 'MY_MODULE');
    return array('my_plugin' => array(
      'path' => $module_path . '/plugins/MY_PLUGIN/',
      'buttons' => array(
        'style_1' => t('Style 1'),
      ),
      'load' => TRUE,
    ),);
  break;
 }
}

and now it recognizes my plugin.js.


How to show a list of users subscribed to the current node's taxonomy terms I've been boggling my brain on this for a while now and although I seem to be getting close, so far there is now awesomness kicking in.

Here's what I want:

I have a number of articles (nodes), each with their own list of taxonomy terms
I have a number of users, each with a list of interests defined in taxonomy terms
I want to generate a list of users subscribed to taxonomy terms of the -current- node

I've tried many different approaches and often had the feeling I got close but, so far, no dice.

The closest I've gotten so far is:
view of 'user'
relationship: 'User: content authored' (yes,I know, this limits the output to author only but it DOES expose the  "(nodes)Content: taxonomy terms on node" relationship, which exposes
'(term) Taxonomy term: name of the tax-list' etc..

SO:
If someone could point out the general outline of the approach (what view type, what relationships to use) that would get me where I need to be, that would be splendid!

REWARD:
A whole lotta love will go to the one who sets me on the right track!

You can set the same vocabulary for users and your content type, so they will be related with the same terms, then you will be able to achieve your goal with these four steps:

#1

Create a View block with these settings:

View->name: Related users
Show -> taxonomy terms -> of type -> your vocabulary

#2

Create relationship:  Taxonomy term: User using [field_name]

* field_name: the name of the field with term reference in users account settings

check: Require this relationship

#3

Add field: (field_name) User: Name

* field_name: the name of the field with term reference in users account settings

#4

Add contextual filter: Taxonomy term: Term ID

Configure the contextual settings:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

provide default value: taxonomy term id from URL

check: Load default filter from term page

check:  Load default filter from node page,  that's good for related taxonomy blocks

Select your vocabulary

Check: Filter to items that share any term

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED:

Specify validation criteria -> basic validation

Action to take if filter value does not validate -> hide view

MORE:

check: Allow multiple values

That's all. If the current node will have a relation with some user or users, then the block with the related users will be displayed.


How to switch back and logout of masquerade user back to admin? I've setup masquerade module and switched to a regular user, but my switch back to admin block doesn't show up in the main theme and the user has no access to the admin theme. Is there a link I can use to switch myself back to admin?

Looking at the module code, I notice the module defines a block with links for the masquerading operations. If that block is visible for the user account to which you switched, you should see a link to go back to your original account.

This is the code used from the module to show the block.

/**
 * Implements hook_block_view().
 */
function masquerade_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'masquerade':
      if (isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'))) {
        $block['subject'] = t('Masquerade');
        $block['content'] = drupal_get_form('masquerade_block_1');
      }
      break;
  }
  return $block;
}

/**
 * Masquerade block form.
 */
function masquerade_block_1() {
  global $user;
  $quick_switch_links = array();
  $markup_value = '';
  if (isset($_SESSION['masquerading'])) {
    $quick_switch_links[] = l(t('Switch back'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
    if ($user->uid > 0) {
      $markup_value = t('You are masquerading as %masq_as.', array('@user-url' => url('user/' . $user->uid), '%masq_as' => $user->name));
    }
    else {
      $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous'))));
    }
  }
  else {
    $quick_switches = variable_get('masquerade_quick_switches', array());

    // Add in user-specific switches, and prevent duplicates.
    $user_switches = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchCol();
    $masquerade_switches = array_unique(array_merge($quick_switches, $user_switches));

    foreach ($masquerade_switches as $switch_user) {
      if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
        $account = user_load($switch_user);
        if (isset($account->uid)) {
          $switch_link = 'masquerade/switch/' . $account->uid;
          if ($account->uid) {
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
          if ($switch_user == 0) {
            $account->name = variable_get('anonymous', t('Anonymous'));
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
        }
      }
    }

    if (masquerade_menu_access('autocomplete')) {
      $markup_value .= t('Enter the username to masquerade as.');
      $form['masquerade_user_field'] = array(
        '#prefix' => '
',
        '#type' => 'textfield',
        '#size' => '18',
        '#default_value' => '',
        '#autocomplete_path' => 'masquerade/autocomplete',
        '#required' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Go'),
        '#suffix' => '
',
      );
    }

  }
  if ($quick_switch_links) {
    $markup_value .= '
' . t('Quick switches:') . theme('item_list', array('items' => $quick_switch_links)) . '
';
  }
  $form['masquerade_desc'] = array(
    '#prefix' => '

',
    '#markup' => $markup_value,
    '#suffix' => '

',
  );
  return $form;
}

Reading it, I see the same block shows you a Switch back link in the case you are masquerading as another user.
Assuming the block is enabled for all the roles in the site, and it is assigned to a region the currently-set theme uses, one of the reasons for the Switch back link not appearing could be an issue with the user session; in that case isset($_SESSION['masquerading']) could return FALSE.

There is also a bug report about switching back: masquerade/unswitch throws a no acccess error. In that issue is clearly stated you need to use the block to switch back; it also seems there are some issues when the clear URLs aren't enabled.


Twig LoaderError: Template is not defined When I try to edit a page to upload 2 documents, I get an error.

Procedure: I edit the node, upload the first document. Then I insert a new field to upload the second document. However, the second field does not appear and I get the following error message in dblog:

  "Twig\Error\LoaderError: Template
  "themes/bootstrap_sbv/layout/sbv-personenseite-layout.html.twig" is
  not defined. in Twig\Loader\ChainLoader->getCacheKey() (line 10 of
  webpath/docroot/modules/ds/templates/ds-entity-view.html.twig).

I have tried to include the layout in the "ds-entity-view.html.twig" file.

{% include "/themes/bootstrap_sbv/layouts/sbv-personenseite-layout.html.twig" %}

But it doesn't work.

Curiously, everything works on the local environment. Only on the test and production environment I get the error. I have a custom theme on my Drupalsite.

Moving the templates to the Templates folder themes/THEMENAME/templates has solved the problem. I also had to change the path in the THEMENAME.layouts.yml


Facetapi combined filter of city and zip code I am using address field module with search api and facetapi modules.
I want one filter of two fields, city and zip code. Which will be an autocomplete field.
I have used the Search API Combined Fields module. Created a combined fields filter with the following configurations:
Imitate field : Address » Locality (i.e. City)
Contained fields : Address » Locality (i.e. City), Address » Postal code

But the problem is, in facet settings I can see only links and links with checkboxes widgets. there is no autocomplete widget.
and second when I select one of a widget from links and links with checkboxes, it only displays the city names on the search page.
can anyone know the solution for this?

I used the search_api_combined.

In the search index, there will be a new tab with the name "autocomplete". Go to that tab and select your view and save the settings.

Then in the view filter, select your desired field and make it expose filter.

And also make that combined field a multivalue field with type full text.


Why am i getting this Drush error after updating a site? I use Drush 8.1.17 to update my Drupal 7 sites, and as I have been updating my sites today after the latest security update I have noticed that after I update a site if I try to run any update related command (ex: drush up -n | grep available) I get this error:

The external command could not be executed due to an application error.                                      [error]
The command could not be executed successfully (returned: PHP Fatal error:  Uncaught                         [error]
TYPO3\PharStreamWrapper\Exception: Unexpected file extension in "phar:///usr/local/bin/drush/includes/.." in
/srv/www/htdocs/fac-dev/misc/typo3/drupal-security/PharExtensionInterceptor.php:39
Stack trace:
#0 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/Behavior.php(72):
Drupal\Core\Security\PharExtensionInterceptor->assert('phar:///usr/loc...', 'url_stat')
#1 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/Manager.php(83):
TYPO3\PharStreamWrapper\Behavior->assert('phar:///usr/loc...', 'url_stat')
#2 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/PharStreamWrapper.php(412):
TYPO3\PharStreamWrapper\Manager->assert('phar:///usr/loc...', 'url_stat')
#3 /srv/www/htdocs/fac-dev/misc/typo3/phar-stream-wrapper/src/PharStreamWrapper.php(401):
TYPO3\PharStreamWrapper\PharStreamWrapper->assert('phar:///usr/loc...', 'url_stat')
#4 [internal function]: TYPO3\PharStreamWrapper\PharStreamWrapper->url_stat('phar:///usr/loc...', 2)
#5 phar:///usr/local/bin/drush/includes/filesyste in
/srv/www/htdocs/fac-dev/misc/typo3/drupal-security/PharExtensionInterceptor.php on line 39
, code: 255)
pm-updatestatus failed.

Does anyone know why this error only appeared after I updated the site and how I can fix it?

It looks like they just released Drupal 7.63 and in the release notes they say, "This is a hotfix release for a regression affecting some Drush installations that was introduced by the fix for SA-CORE-2019-002. No other fixes are included."


Error when updating modules with Drush Iv managed to install Drush to the site on Go Daddy shared hosting(thanks to the greate tutorial!). Simple commands run without any errors, but when I try:

drush pm-update ctools

It returns:

    -bash-3.2$ drush pm-update ctools
The external command could not be executed due to an application error.                                                                                [error]
                                                                                [error]

Parse error:  syntax error, unexpected '{' in /home/content/XXX/XXX/drush/includes/environment.inc on line 518

, code: 255)
Update information last refreshed: Wed, 04/18/2012 - 06:11

Update status information on all installed and enabled Drupal projects:
 Name                                                   Installed version     Proposed version  Status
 Address Field (addressfield)                           7.x-1.0-beta2         7.x-1.0-beta2     Up to date
     Administration menu (admin_menu)                       7.x-3.0-rc1           7.x-3.0-rc1       Up to date

    ...

Security updates will be made to the following projects: Chaos tool suite (ctools) [ctools-7.x-1.x-dev]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n):

The code of the line 518 in environment.inc

is

517      try {
518      $db = new PDO($constr, $creds['user'], $creds['pass']);
519      $db = null;
520     }

Drupal is 7.12, Drush 5.1

What can be the reason of this error?

Also
In hosting cotnrol panel site is on PHP 5.3
But php -v returns 5.2.17
is it ok?

This is a common issue in the Drush queue on drupal.org and the consensus is that its related to your version of PHP that runs in client mode versus the version running on your web server, ex. http://drupal.org/node/1402120 or http://drupal.org/node/436968. Of course, some of these were related to PHP 5 vs PHP 4 issues and you're just one version behind on the client but it may help to alias your php version as explained here:

echo 'export PATH="$HOME/packages/bin:$PATH"' > .bash_profile
mkdir -p packages/bin
ln -s /usr/local/php5/bin/php packages/bin/php

Patrick Kenny is right though that this parse error won't affect your upgrade in the end.


Adding the current node title as the value of the comment form title? I want a value to be automatically added to the title text-field in the comment form ; this value would be indeed the current node title.

I've started working on a hook_form_alter() (added in a custom module already installed and enabled) like this one :

   function ta_module_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'comment-form') {
        $form['comment']['title']['#value'] = 'Blablabla';
    }
   }

But as you might guess it's not working... I've got several issues:

Is the $form_id the right one ?
I didn't manage to successfully use print_r($form) (or it returned nothing) so I
guessed the path to the title value. Might be incorrect too...
And finally, I really don't know how to get the current node title
variable, so as to attribute it the title value!

Thanks for reading, I hope I've been understandable !  ;)

You're right, you most likely have the $form_id wrong.  To check this you can use drupal_set_message($form_id); and refresh the page to see all form ids on the current page.

Once you have the form id correct, then you can use print_r($form);

For example, I got this working on the comment form on my node type "Announcement":

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_announcement_form') {
    $form['subject']['#default_value'] = $form['#node']->title;
    //print_r($form);
  }
  //drupal_set_message($form_id); // Use to get $form_id
}


Migrate files with directories and sub directories I am having issues with migrating my files locally on my computer. Im using the migrate UI and my source_dir = /Users/cwahlfeldt/Sites/dev.urbanaillinois.us/sites/default/files/ which is a full path to the files I'm trying to migrate. destination_dir = public://. Im getting the following errors when attempting a migration:

Informational   Undefined property: stdClass::$value File /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 704(file: /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 704)

Error   The specified file /Users/cwahlfeldt/Sites/dev.urbanaillinois.us/sites/default/files/ could not be copied to public://files: "copy(): The first argument to copy() function cannot be a directory File /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 393"

The sources files directory has many sub directories within it and the copy() function thats used by the migrate module doesn't seem to want to take a directory. Is there a solution to this? Or is this caused by something else.

How is destination_file mapped in your file migration? See https://www.drupal.org/node/1540106 for information on how the file options interact to determine the full destination filespec.


calculate sum of user's orders in drupal commerce Is there a solution of calculating a sum of user's orders in drupal commerce (7.41 core) and display them in views? I tried to create a table in view which couldn't show anything except total number of orders but had not user filter. What should I do in order to combine "user" and "drupal commerce"?

You can use the view Commerce Backoffice: User orders.

Clone the display users orders.
IN advanced settings, set use aggregation : YES
remove All fields from the display except order Total
In order total field aggregation settings, set type = SUM, group a column = Amount

That's it.

Alternatively, if you don't use Commerce Backoffice module, you can create a view from scratch if you have no user's orders view (I don't remember which default views are provided with Commerce) :

Create a view of orders
Add a contextual filter Commerce Order:UID
Add a field total and repeat steps above

This should be enough. Remain formatting details...


Why are comments not a node content type? So Drupal has a 'special' commenting system.

  Comments are second-class citizens in Drupal compared to nodes...

But why did the core team not just create a default Content Type, Block and View for comments, and allow the site administrator add in a comment block as necessary? Just like the 'Article' and 'Basic Page' content types, which we can create blocks and views for. Why are comments so different?

To answer this, I first had to understand one thing: Entities are not nodes.

Entity Types are special groupings of fields.

Node is an entity type, which requires some fields, such as 'Title', 'Author' and 'Publish Date'.

Content Types are instances of Node which further define more fields. So a 'blog post' content type can have 'Hook', 'Introduction', 'Summary' and 'Related posts' fields, in addition to 'Title', 'Author' and 'Publish Date'.

Node is an entity type specialized for content. A comment is not designed to be a node because it is too different from a typical content. It's not necessary to have a 'Title', 'Author' or 'Publish Date' field in a comment. Because it is so different, it is created as another Entity type instead.

For more details, see this article on Drupal.


Pass arguments to hook_form_alter() I have two login boxes on the same page and, I would like to integrate different behaviors to those based on some arguments.

I'm calling myself the forms with drupal_get_form('user_login');. I would like to pass a variable to the form:

drupal_get_form('user_login', $myvar);

And then be able to get it from a hook_form_alter():

function mymodule_form_alter($form, $form_state, $form_id, $myvar) {
  // some code here
}

But i can't find a way to do this.

The passed arguments are kept in $form_state['build_info']['args']. You can find a documentation of the $form_state structure here: drupal_build_form().


Let users download entire folders (zip first) or individual files? Is there a module or a series of modules that will allow users to download a folder of files (e.g. construction blueprints and sketches) or just individual files via the browser?

The files for user A should be only accessible to user A.

I suspect that the functionality that you are looking for exist in the elFinder file manager module. It allows downloading individual files and whole folders after compressing them first.

You can manage the roles that you allow to download specific files with the native drupal permission system. Just make sure that you don't give your users access to sensitive files in drupal installation.


Assign a row class like "row-1" for row 1, "row-2" for row 2 I have a view that uses the Table format.
I want to add row classes like this:

Row 1: .row1
Row 2: .row2
Row 3: .row3

In the Views UI, if I click Settings under Format: Table, then I can specify the Row class.  This field allows tokens, but I can't find a token that refers to the views row itself.
How can I implement a row class that assigns a number based on the position of the row in the view?

There are plenty of ways to go about this question, my suggestion is overriding twig templates.
You would need to override the Twig template for that view. If you enable debug, clear cache, inspect element, you will see the template for that view. Then for that twig file, just use the loop index
loop.index  The current iteration of the loop. (1 indexed)

to track which row you are in.


Construct a View-Grid from fields of the same node? I understand that naturally it's not possible to grid fields from a single node, when using Views, and we could only display a grid if each field is coming from a different node.

Is there a module that will allow Views, somehow, to make a grid based on fields from the same\single\unique node?

I would surly prefer a way to do it with views-only, but if there is no easy\automatic way to so without installing an external module than so be it.

You could use a combination of Display Suite and Views. This is not a perfect grid... but it's close. These are the steps I followed. I created a Content Type with 6 Long text fields.

Install Display Suite and enable Display Suite and Display Suite UI
Go to Manage Display of your Content type, click on Custom display settings and enable Full content

Click on the Layout tab and select a layout. I selected a Three column stacked - equal with layout.

I distributed the fields into the three columns (Left, Middle, Right), and added the node Title in the Header area
Create a View of Content. In display format be sure to select Unformatted list of full posts
Click on the Content link under Format. Be sure to select Display Suite. Select Full Content

Visit your View. This is what it looks like (I am showing two nodes, with 6 fields each):

Now, if you want to make it look nice (e.g. more space between columns), you will have to use css - no way around it.


Automake forum on node creation with rules I'm desperately trying to programmatically add a new forum (in the 194 tid specific container) on node creation with rules.

I run php script when adding new node with rules, but I'm really newbee with php. I'm trying to use form_forum_form and form_forum_submit putting this variables :

require_once 'modules/forum/forum.admin.inc';

$autoform = array(
     'name' => '[node:title]',
    'description' => 'Forum du projet [node:title]',
    'tid' => 194,
    'weight' => 0,
);

$form = forum_form_forum($form, &$form_state, $edit = $autoform);
forum_form_submit($form, &$form_state);
print_r(drupal_get_messages());

This link doesn't helped me and there is nowhere on the web where the answer is explicitely given.
How to programmatically create forums and containers (not forum topics)?

Thanks for helping

There is no need for any custom php here. Just the below steps.

In Rules actions,

Action 1: "Create a new entity > Taxonomy term"
Enter your title based on the created node and put it in the forum taxonomy
Action 2: "Set a data value > [entity-created:parent], Value: 194"


Facet API and views contextual filters (facets block on non-search page) I'm using Facets API with SOLR and it all works fine.

I also have a standard view set up using a facets block from the search-index view. This also works OK, but it shows the complete unfiltered facet list.

What I'd like to do is apply a contextual filter from the path to the facet block, but it doesn't seem to work - I get nothing.

I'm wondering whether this is possible and if so how (and if anyone even understands what I'm asking?!)

Thanks,
Chris

OK, worked this out myself:

Use the contextual filters prefixed "Search:" in the list (not "Indexed node:". There are 2:
"Search: Fulltext search" and "Search: Indexed taxonomy term fields"

Not sure if Search: Fulltext search is ideal as I'm using it for place names and there are a few with more than one word.


Caching of blocks for anonymous user I have a little probleme with my cache block.

This is my build function :

return [
  '#markup' => time(),
  '#cache' => [
    'max-age' => 10
  ]
];

I found this specification for block cache.

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 20;
  }

Because in parent class we have $max_age = Cache::PERMANENT;

So, when I'm connected my rendered cache refresh each 10 seconds.
But when I'm a anonymous user my rendered block never change.

I don't find the solution.

Big pipe isn't install, I have aggregations css and js but I don't have max age in admin/config/development/performance.

Finnaly I want a block without cache because this block will rendered message with close button. When the user click on the close button, I set a cookie for return an empty bluid in my block.

Do you have an idea ?

Thank you

You don't have to worry about the values which are set for cache max-age in other places, because when these are merged the lower time that you have set wins.

But you can't control with max-age the page cache for anonymous users. You have to use \Drupal::service('page_cache_kill_switch')->trigger(); in the block build method to disable the page cache or you can simply uninstall the module Internal Page Cache if you plan to use the block on all pages.

  but I don't have max age in admin/config/development/performance

You should set this to the same max-age to control the browser cache and proxies.


How do I display a view content for a specific user? There are several views to show the content that is restricted by the page_access module. For now, the view shows all the content. Ideally, it must show the content that the specific user is allowed to see.

How can I achieve this?

You can set permission for the specific role in view. Check the access in page/block settings

Change the access permission to role, then check the access for the specific roles for view content.

For example, Restrict View for the authenticated user. So, the users who are belonging to the authenticated user roles can able to access the content, other roles cant access it.


Does Multiupload Filefield Widget for Drupal provides a Form API element? I have a form in on of my Drupal page that uses Multiupload Filefield Widget to upload multiple images at once.

I want to alter the functionality of this Multiupload Filefield Widget from my custom module using hook_form_alter.

At first I thought It will be a managed_file widget. But it is not.

Is there a way to do it?

Yes it does, as defined in multiupload_filefield_widget_element_info(). The element type is mfw_managed_file, so you can use something like:

$form['multi_upload_element'] = array(
  '#type' => 'mfw_managed_file',
  '#title' => t('Some file'),
  '#upload_location' => 'public://',
);


Unsetting a field before hook_form_alter I have a field collection with two entity reference fields that I keep hidden on a node creation form. The reference fields in the hidden field collection are slowing down the page load time. I need to block the field collection from rendering at all. From what I understand it needs to happen before hook form alter. See Question - Does unset($form['field']); in hook_form_alter stop entity reference views select list queries from running?. Any help would really be appreciated!

In case this helps anyone - the hidden node reference fields that I have been using were having their lists of selectable nodes generated by views. I ended up using hook_views_query_alter to stop the view query from being run. Here's the code I put into my custom module:

/**
 * Implements hook_views_query_alter().
 *
 * Disables node reference views. This drammatically
 * speeds up performance.
 */
 function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == "my_view") {
    $view->executed = TRUE;
  }
  if ($view->name == "my_view2") {
    $view->executed = TRUE;
  }
 }


How to define column css in views? How to define column css in views?

I testing a theme. I tried edit the css from CSS class one-half to one-fourth. The layout changes successfully from half column to fourth column.

I wondered how the CSS define.

I looked into the views but can't find the css added (one-half)

Click here and check if it was added as a row class.

Else, look under Advanced

If nothing is there, check your theme's templates folder. They probably created a template file (.tpl.php or .html.twig) for the view.

Lastly, if still nothing, check inside your theme's folder for template.php or theme-name.theme


Does Drupal.t() inside JS file has the same restrictions as the PHP t()? I have read that the string parameter passed to t() function should be literal, which excludes:

variables, even the parameters of a function: t($description)
a concatenation of strings: t('If you want to add a link, click on' . 'this link.')
the value returned from a function:t(get_menu_description())
a constant: t(MYMODULE_MY_WIDGET_TITLE), t(MyClass::WIDGET_TITLE)

as mentioned here Is it always bad to pass a variable through t()?.

So, does Drupal.t() inside JS file has the same restrictions? as I have find a string inside some module that is passed as a variable

 $(this).addClass('open').text(Drupal.t(settings.linkText));

This string settings.linkText can't be located at the translation interface and I tried to change it to

 $(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

but still couldn't find it. Any Ideas?

The string will show up in the translation interface if it is found by the js code parser. And a variable can't be worked on by the parser, it has to be a string. So

$(this).addClass('open').text(Drupal.t(settings.linkText));

can't show up.
It doesn't prevent the string to be translated though, if the js is aware by another way of the translation : if you write somewhere else in your js

Drupal.t('my_string');

then the parser will find 'my_string' to translate, and the js will load it next time it's called, and if settings.linkText happens to equals 'my_string', then it will be translated.

You have to flush the js cache after the js code alteration, so the parser can look again for strings. It may be why the

$(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

doesn't show '@txt' in the translation interface.


Show webform results on same page i have a webform with a lot of fields(i am making some kind of calculator for my needs) and after submit i need to show custom output under my webform.

In hook_form_alter i have added custom submit handler
$form['#submit'][] = 'common_webform_client_form_1562_submit_handler';

and after submit i need to show my results on same page.

function common_webform_client_form_1562_submit_handler($form, &$form_state) {
   //some logic here

   //redirect to node with my webform
   $form_state['redirect'] = 'node/1544';
}

As i can see i cannot modify or add anything to a $form i thought i can add #suffix to webform and attach my results but i can't, should i do it with Drupal.settings and grab it with javascript? or is there another option?

So after some research i have found the answer. I did this with ajax submit. In hook_form_alter i have added ajax submit callback with markup element:

$form['actions']['submit']['#ajax'] = array('callback' => 'common_webform_client_form_1562_submit_handler',
           'wrapper' => 'form-ajax-node-content',
      'method' => 'replace',
      'effect' => 'fade',);
       $form['markup'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#markup' => '',
            '#weight' => 2000, //set weight to show markup at the bottom of the form
       );

And in my callback i can generate any output i want to!)

function common_webform_client_form_1562_submit_handler($form, &$form_state) {
   $output = 'Dummy text';
   $form['markup'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#markup' => $output,
            '#weight' => 2000,
       );
    return $form['markup'];
}


Best practice for installing Drush? I have been a Drupal site builder for some time, but I kind of got started with it backwards. Recently, I have begun learning more server-end things like Drush, Git, etc. I'm playing around with a Digital Cloud virtual server, and I'm not having a problem per se, but I have found at least 4 ways to install Drush:

Through Pear
Through apt-get
Through Composer
By downloading the files straight from Github

(If it matters, I am on a Debian environment.)

It seems that Pear may be the preferred way from what I can tell, but that's just based on the fact that I found that to be recommended slightly more frequently than the other methods.

Is this just a matter of preference? I admit I am not very familiar with Pear and Composer. Or is there a method that most devs consider to be a best practice?

Thank you.

You have to install Drush through composer because it provides all the depencies which are required for drush. apt-get is basically supported by the Linux and Debian.

So use this link to install using composer :
https://github.com/drush-ops/drush


Why is my Pantheon git clone not loading correctly? My website is on Pantheon. I am using linux ubuntu 17.10 and LAMP for local development. I use the git clone command and it works. My drupal 8 files are there. Then I export and import the database sql file and the files folder. When I load my website on the local host I get this:

How do I fix this? What am I doing wrong? Am I missing a step?

The issue you're exhibiting is most likely a result of the database reflecting a temp directory (on the Pantheon server) that does not exist or is not writable on your local LAMP environment.

To reset the temp directory for your local development instance, you can:

use drush to set the temp directory (typically /tmp)
navigate to admin/config/media/file-system

If after setting the temp directory and clearing caches, you still exhibit similar behavior, you may want to double check the file owner/group permissions for the public files directory.

See https://www.drupal.org/node/244924 for a how to identify and set permissions, and refer to http://www.drupalden.co.uk/file-folder-permission-settings-drupal-7 which provides a good summary (note- permissions recommended for D7 also apply to D8)


Remove the "upload" button from the image field form element in drupal 7 As the title suggests I need to remove the upload button from an imagefield form element within D7.

I can't seem to find the element itself within the form array (via hook_form_alter) and I'm just wondering if it needs to be done a different way perhaps.

(I do realise the button can be hidden with CSS but I'd rather not take that option if I can help it.)

Put this code in template.php of your theme, and rename the function.

/**
 * Implementation theme_image_widget($variables)
 */
function THEMENAME_image_widget($vars){
  unset($vars['element']['upload_button'], $vars['element']['remove_button']);
  return theme_image_widget($vars);
}


get last element in URL(menu item) generated by hook_menu I have created a URL/menu item via hook_menu, and in the proprocess_html I'd like to get my item (last element in the URL) (/test) without using arg(0).

I can do it in PHP but I was wondering how it was possible to get this with drupal.

end(explode("/", request_uri()))

this code is actually bad, there could be URL such as ?test=ok

Cheers,

array_pop(arg());

will return the last component of the current Drupal path.


Referenced Entity not Updating Correctly When Saved I have node A that contains an Entity Reference Revisions field in it set to display as a Rendered Entity that points to node B of a different content type.

Initially this works fine. However, if I make an update to node B and save it, the changes don't appear on node A until I edit and save node A again.

It seems like it should update without having to re-save the parent node. Is there a way around this?

What is the reason you use a Entity Reference Revisions field? Normally this is more suitable for entities edited inline like paragraphs.

In your case this behavior seems to be what you would expect from this field, because you reference a specific revision of node B and not the latest version you've saved. If you want to do this, then use the core reference field.


How to troubleshoot subdomain issue on Aegir I set up Aegir on a rackspace server. Everything works correctly. I then create a new site and set the url to testname.mydomain.com. After Aegir is don provisioning the site I go to the front page at testname.mydomain.com and see my new site. The front page works fine, but every other page, gets a page not found error, so when I attempt to login I'm unable. How do I go about troubleshooting this issue.

So it turns out this is somehow related to platform, I added another platform based on makefile (for open atrium) and it seems to work correctly, I'm not really sure why this would happen, but I figured I would update incase anyone else is having the seam issues.

Your platform is most likely missing the .htaccess file in its top-level directory, or (less likely, or else the Aegir interface itself would likely show the same problem) mod_rewrite is not enabled on your site.

See if you can get to http://testname.mydomain.com/?q=user

If that works, but http://testname.mydomain.com/user doesn't, then your .htaccess file is missing or being ignored by Apache.


how can i define a maintenance template within a custom module? i have done this within a module for defining custom templates when having status error

function custom_module_preprocess_region(&$vars) {

  $header = drupal_get_http_header('status');

  if( $vars['region'] == 'content' ) {
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'content__404';
}
if ($header == '403 Forbidden')  {
  $vars['theme_hook_suggestions'][] = 'content__403';
}
 }
 }

 function custom_module_theme() {
   return array(
'content__404' => array(
  'template' => 'region--content--404',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
'content__403' => array(
  'template' => 'region--content--403',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
'maintenance' => array(
  'template' => 'region--content--maintenance',
  'variables' => array('xxx' => null),
  'path' => drupal_get_path('module', 'custom_module').'/templates'
),
 );
 }

How can i implement it just the same to override the theme maintenance tpl ?

drupal_get_http_header() should be treated as deprecated.

See https://www.drupal.org/node/1969270#comment-7609337

I think your approach is good, but for a little more coverage of 404/403 pages we came up with a more extendable approach, also theres a bit more room for customization in the backend within the modules settings page.

We did this by using the customerror module in conjunction with a theme function and a few overriding template files.

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

After installing, add this to your template.php file's theme_preprocess_page function. Example;

function YOURTHEME_preprocess_page(&$variables) {

  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'customerror') {
    if ($alias_parts[1] == '403') {
      $variables['theme_hook_suggestions'][] = 'page__forbidden';
    }
    if ($alias_parts[1] == '404') {
      $variables['theme_hook_suggestions'][] = 'page__not_found';
    }
  }

  <other code goes here>

}

Then in your templates folder add your custom templates (just like your page.tpl.php file);

page--forbidden.tpl.php
page--not-found.tpl.php

Clear your cache, hit one of those pages (you can test them by going to);

[yoursite]/customerror/403
[yoursite]/customerror/404

As for your maintenance page, all you need to do is create a
maintenance-page.tpl.php file and toss that in your templates folder.


Styling Rewrite results in views I have a field in my view and I have rewritten the result (  p align="left" [field_about_us_read_more] ) and also check the "Output the field as a link". in styling setting section, "Customize field HTML" is "None" and "Customize field and label wrapper HTML" is "DIV"
the html code generated is like this:

         read more

How can I get rid of the first anchor link?
and how to add extra html element in the " styling setting ".

TNX

Remove check from  "Output the field as a link" and then in rewritten the result
put this

        [field_about_us_read_more]

or if not work try something like this  (I mean in output use  tag )

 [field_about_us_read_more]


Sometimes the v= parameter is added to the product URL I have a new Drupal 8 site running commerce. When I view a product, most of the time the clean URL is perfect. Other times, it has a version parameter attached to it. I can access the page and no parameter, then refresh and I get a ?v=2 or something like that. I'm baffled. Has anyone experienced this issue? We're afraid that if users copy this link (with parameter) to other sites, it will cause us duplicate issues with SEO.

I'm not sure what I need to post here for help, so if anyone can help, let me know and I'll provide anything I can.

This is because you've got more than 1 variation on a product. The v  parameter allows you (and drupal commerce) to directly link to the product page with the correct variant set as the selected one

For example you have "t shirts" product with variations for colour. You might want to link directly from the product listing page/cart/anywhere else to a specific colour tie.


How can I add CSS variables to the HTML head? For my site I want to be able to set custom css variables to the sites head. I don't want to add css files just inline css code. In the end I want users to be able to set colors using a color picker. These colors should be translated to the css variables added to the sites head.
For this I looked at the code in the css vars module this brought me a long way. But i'm not able to add css variables in the body of the page.
For this I use hook_page_top. But my code now is ending up in the top of the <body> and I want it to be in the <head>. Strange enough...when I look at the screencast (min 7:35) of the creator of the css vars module I see that his code does get in to the <head>.
I simplified the code in my theme_color module to figure out how it works. So maybe that's the problem? How can I get my css variables in the head of the page?
I have a theme_color.module:
<?php
/**
 * @file
 *   CSS Variables module.
 */

use Drupal\theme_color\Hooks;

/**
 * Implements hook_page_top().
 */
function theme_color_page_top(array &$page_top) {
  Hooks::hookPageTop($page_top);
}

I have a Hooks.php just like the example module:
<?php

namespace Drupal\theme_color;

class Hooks
{

  public static function hookPageTop(array &$pageTop)
  {
    if ($build = self::makeThemeColorBuild()) {
      $pageTop['theme_color'] = $build;
    }
  }

  private static function makeThemeColorBuild()
  {
    $build = [
      '#type' => 'html_tag',
      '#tag' => 'style',
      '#value' => "html:root {\n--test-var: yellow;\n}",
    ];
    return $build;
  }
}

Update:
I tried earlier, and again after get the suggestions in comments to use hook_preprocess_html
function theme_color_preprocess_html(&$variables)
{
  $build = [
    '#tag' => 'style',
    '#value' => "html:root {\n--test-var: pink;\n}",
  ];
  $variables['page']['#attached']['html_head'][] = [$build, '?tag?'];
}

This is working but what kind of tag do I need to put after the $build in the $variables line of code??

To do this from hook_preprocess_html like in accepted answer to the duplicate question it works like in the snippet below.
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_html(&$variables) {
  $style = [
    '#tag' => 'style',
    '#value' => ":root {\n  --test-var: pink;\n}",
  ];
  $variables['page']['#attached']['html_head'][] = [$style, 'foobar-my-id'];
}


Hide a view programatically D8 I am trying to hide a view block if it has one or less results, i am doing this using the MYTHEME_preprocess_views_view function.

Here is the code

// Removes product range if only one product is availiable!
if($variables['view']->id() == 'brand_product_range') {
  if(count($variables['view']->result) < 2) {
    // $variables['view']->destroy();
    // $variables['view']->setDisplay(false);
    // I want to hide block here!
  }
}

I managed to get the id of view block and number of results in the view, but I don't know how to hide the block, I tried the above methods but they are not working.

I assume your view is using a block display and you don't want the block to display at all if there is only 1 result.

In my opinion you are hooking in too late in the process to hide the view there. It is possible to hide it in the theme layer but I don't think it is the optimal approach.

There are a number of ways you can do it but here are a couple of ways using a hook in a custom module, not in a theme. (This is not an exhaustive list of options that you have.)

Option 1

Hook into the view execution process and tell the process that execution has failed, so it will not render the view.

For example:

use Drupal\views\ViewExecutable;

function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // If there is only 1 result set the failure condition so that
  // execution will not continue and the view will not display.
  if ($view->id() == 'VIEW_NAME') {
    if (count($view->result) == 1) {
      $view->build_info['fail'] = TRUE;
    }
  }
}

Option 2

Configure your view to have 'Hide block if the view output is empty' = Yes
Hook into the view execution process and clear the results when you don't want it to display.

For example:

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute().
 */
function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // Clear the results if there is only 1 result.
  // The view will then hide as it is configured to hide the
  // block if empty.
  if ($view->id() == 'VIEW_NAME') {
    if (count($view->result) == 1) {
      $view->result = array();
    }
  }
}

Note: Depending on how you decide to hide the view, if your views block is the only block in your region then be aware of this outstanding bug, which may cause your region to still display even though your block doesn't: https://www.drupal.org/project/drupal/issues/953034


Correct way to render fields from Entities? This very popular article explains correct way to render fields:
http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

According to the article, the correct way to render fields is like this:

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

But this is for rendering fields that are stored in a node. How would you use the code for fields in an entity?

 More info

I am using Paragraphs module that lets you create custom bundles in the predefined "paragraph" entity.

You can use entity.tpl.php to override the output of Paragraph module fields.

I want to print my fields that are stored in the entity, but the above code won't work because it is for nodes.

The equivalent to the sample code you posted from the article, but for an entity type other than node would be:

$entities = entity_load('ENTITY_TYPE_NAME', array($YOUR_ENTITY_ID));
$entity = $entities[$YOUR_ENTITY_ID];
$field = field_get_items('ENTITY_TYPE_NAME', $entity, 'field_name');
$output = field_view_value('ENTITY_TYPE_NAME', $entity, 'field_name', $field[$delta]);

If you're doing this in a template, your entity's fields should have already been retrieved by the entity module's template_preprocess_entity() function and made available under the $content variable, so you shouldn't have to do all these steps in an overridden entity template.


Menu Callback and CSRF How can I get a link with the correct csrf token for an internal path? Here is what I have:

in mymodule.routing.yml

mymodule.test:
  path: '/mymodule-test'
  defaults:
    _content: 'Drupal\mymodule\TestController::handleTest'
    _title: 'Handles test'
  requirements:
    _permission: 'access content'
    _csrf_token: 'TRUE'

building the link:

//$url = Url::fromRoute('mymodule.test');
//$settings['url'] = $url->toString();
$settings['url']=Drupal::url('mymodule.test');

the url contains the token in the query string as I expect, but it doesn't validate if I try to visit the link. When I edit CsrfTokenGenerator and dump out the token and the expected token, they do not match. All I can come up with is that the token is being generated for the page that I'm currently viewing rather than the route that I'm generating the url for.

Am I missing something? any ideas are appreciated!

Routes that need CSRF tokens have the _csrf_token: 'TRUE' route option. That's how URLs pointing to those routes automatically get a CSRF token.

So we need to look at \Drupal\Core\Access\RouteProcessorCsrf:

public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
  if ($route->hasRequirement('_csrf_token')) {
    …
    if (!$bubbleable_metadata) {
      $parameters['token'] = $this->csrfToken->get($path);
    }
    else {
      // Generate a placeholder and a render array to replace it.
      $placeholder = hash('sha1', $path);
      $placeholder_render_array = [
        '#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
      ];

      // Instead of setting an actual CSRF token as the query string, we set
      // the placeholder, which will be replaced at the very last moment. This
      // ensures links with CSRF tokens don't break cacheability.
      $parameters['token'] = $placeholder;
      $bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
    }
  }
}

So there we can see that if $bubbleable_metadata is NULL, then we generate the CSRF token right away. $bubbleable_metadata being NULL signals to the CSRF route processor that the URL is being generated in a context where no cacheability metadata and attachments can be bubbled (e.g. when generating a URL to be sent in an e-mail). The downside is that the HTML containing this URL will then be uncacheable (well, very poorly cacheable), because the CSRF token is depends on the session.

That's why in the other case, where $bubbleable_metadata is a BubbleableMetadata instance, that signals to the CSRF route processor that the URL is being generated in a context where cacheability metadata and attachments can be bubbled (e.g. when generating a URL to be rendered in some HTML). So there we generate a placeholder token that will be replaced with the CSRF token, and specify a "placeholder" attachment that will ensure that placeholder token is replaced with a CSRF token at the last possible moment. Consequently, the HTML that this URL ends up in is still perfectly cacheable, because the URL is cacheable.

Now that problem has been confirmed. If this happens in a preprocess function, as the following one, then you end up with $variables['url'] = GeneratedUrl(…). Twig ought to bubble the cacheability metadata and attachment metadata in that object, but it does NOT, in all versions of Drupal 8 before 8.1.2. We're fixing this for Drupal 8.1.2 at https://www.drupal.org/node/2575519.

function hook_preprocess_HOOK(&$variables) {
  $variables['url'] = \Drupal::url('mymodule.test');
}


How to display data from external tables in Drupal without coding? I want Drupal users to be able to display data from external databases. There is no processing involved, just listing the results based on filters. What Drupal 7 techniques are capable of accomplishing this?

I am not interested in anything that requires coding, just using the admin modules. A little coding at the start to configure access to the external databases is fine, but the main linking and displaying shouldn't require coding.

Have a look at the Forena module. You would use its report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file.

Samples

Refer to this online example in the Forena demo site for a report you could (easily) create:

Using Forena's Query builder you would create the required SQL statement (if you'd rather want to write the SQL with your favorite SQL editor that's another option).
Using forena's WYSIWYG report writer you would develop your custom report (if you'd rather want to write that report with your favorite XHTML editor that's another option).

Some more details about the sample report mentioned above:

Use the "Parameters" pulldown option, to select any other state.
Note the PDF hyperlink: using that link, you'll get a PDF version of that report. When creating such report, you could as well ask for other (or additional) report export formats, one of them is CSV (or XLS, DOC, HTML, ...). This is how the CSV equivalent version of that sample report looks like.

The Master Summary with drill down sample report demonstrates how you can also "link" various reports together (while it also shows some of the charting features of Forena). Click on either any of those bars in the chart, or on the total-hyperlink in tabular report below the chart. Doing so will bring you to the report "for the selected state" (= the first sample report mentioned above).

Direct access to data blocks

All data blocks are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at /reports/sample.states:

in XML format (= demo with anonymous access).
in JSON format (= demo with anonymous access).
in XML format (= demo without anonymous access).
in JSON format (= demo without anonymous access).

Video tutorials

The Forena Video demos and tutorials contain quite some links to live demos. They should help a lot to get you started.

Disclosure: I'm a co-maintainer of Forena.


Updating node title inside Rules Action I am creating a Rules Action that will update the node title after it is created.

Here is my code, but when I try to create new content using Postman, it keeps loading. I dont get response in Drupal logs.

...
class ContentTitle extends RulesActionBase {

  protected function doExecute(EntityInterface $entity) {

    $entity_id = $entity->id(); // Getting dynamic entity ID
    $controller = \Drupal::entityManager()->getStorage('node');
    $node = $controller->load($entity_id);

    $title = $entity->label();
    $item = $node->get('field_xyz')->value;
    $new_title = "Title is " . $title . $item;

    \Drupal::logger('custom_rules')->notice('new_title: ' . $new_title);

    $data = array(
      'type' => 'custom_content',
      'title' => [
        'value' => $new_title,
      ]
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);
    $node->save();
  }
}

Im getting the expected output in the logger.

I dont think I am setting the title in $data properly. Any suggestion is greatly appreciated. Thanks!

You can set a node's title with the "Set a data value" action - you don't need to write your own action. I'm going to assume that you're putting this into your own action because there are other things you want to do that you haven't mentioned or because you are learning how to write an action - if this is ONLY about setting the title then I don't see the point of a custom action.
Problems with the approach and the partial solution given in the initial post:

You don't need to get the entity ID then load the entity from
storage, because Rules is already passing you the loaded entity.

You're using entity instead of node, which wrong - Nodes have
titles, Entities in general DON'T.

You're hardwiring in a title taken from a specific field 'field_xyz'.
Instead, you should pass in a string variable which holds the title.
That way the Rule configuration can get the value out of 'field_xyz'
or out of 'field_nlm' or from a thousand other places - writing the
action with a string parameter will make it far more useful.

The EntityManager has been deprecated since Drupal 8.0 and should not be used. You should be using EntityTypeManager instead. But as I said in #1, this isn't even needed.

You don't have to save the node, Rules will handle the saving
automatically.

This really only requires one line of code (plus some boilerplate code, like all plugins...). Here's a complete solution that takes two context variables:

The node to change.
The title to use.

namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Sets the title of a content item.
 *
 * @RulesAction(
 *   id = "rules_node_set_title",
 *   label = @Translation("Sets the title of the selected content item"),
 *   category = @Translation("Content"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node",
 *       label = @Translation("Node"),
 *       description = @Translation("Specifies the content item to change."),
 *       assignment_restriction = "selector"
 *     ),
 *     "title" = @ContextDefinition("string",
 *       label = @Translation("Title"),
 *       description = @Translation("The new title.")
 *     ),
 *   }
 * )
 */
class NodeSetTitle extends RulesActionBase {

  /**
   * Executes the action with the given context.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node to modify.
   * @param string $title
   *   The new title.
   */
  protected function doExecute(NodeInterface $node, $title) {
    $node->setTitle($title);
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    // The node should be auto-saved after the execution.
    return ['node'];
  }

}


How to pass metatags from a node into a view? I'm sending the information of my node into an external application and I need to be able to send the meta tags of that node as well. Unfortunately, I do not see the meta tag fields.

My question is...

How can I send my meta tags into a view?

NOTE: I'm using the Metatag module, I have seen few posts that suggest using the metatags_quick module to add this functionality. However, I need to be able to do it with the instead Metatag module

There is a sandbox project call Metatag Views Field, which provide metatags as a field into Views.


How to handle field with multiple items I have created a field with unlimited number of values allowed. Now, using view I want to display all even number items (like 2nd, 4th, 6th and so on). How can I do that?

My thought: May be I need to edit views-view-field.html.twig file. But I'm not finding any way to display items in field instead of complete field. Please help me.

View source of views-view-field.html.twig:

{{ output -}}

The standard field handler in Views returns flat rendered output. To change this or put in the feature for even/odd numbered values you would need to implement a field handler plugin. For this task that would be a bit too much work. You can improvise in theming to get the same result.

In Views you can define a separator for multiple field values. Choose a separator that is not in the content of the field. Default is ','.

In Twig you can use the filter split to get the array items. Use the separator from the multiple field settings.

views-view-field--field-fieldname.html.twig

{% set items = output|split(',') %}

Put items in a loop and display only even number items:

{% for item in items %}
  {% if loop.index is even %}
    {{ item }}
  {% endif %}
{% endfor %}


Webform: prepopulate fields through URL, "page not found" I'm trying to prepopulate fields in a webform from the URL.  I'm using Webform 7.x-3.20.  I have a form named prepopulate. It has a field "First Name" which has the default value set to %get[first_name].  I have tried to prepopulate the field from the following URL:

http://localhost/test_site/?q=content/prepopulate?first_name=miranda

This results in a "page not found" error.  Does anyone know why this happens?

Thanks in advance!

*UPDATE: I've figured out this happens because it is a rewritten URL (Pathauto).  Still don't know how to fix it, though.

Here is the answer.

It seems clean URLs are not enabled in your site. So here I'm giving the solution in both ways

Assuming that your Field Key  for First Name field is first_name

If clean URLS not enabled.

  http://localhost/test_site/?q=content/prepopulate&first_name=miranda

If clean URLS enabled

  http://localhost/test_site/content/prepopulate?first_name=miranda

I've tested this on my environment and works perfect. Hope this helps


How to attach browser-specific stylesheets in D8? In D7 it's possible to attach a css file based on browser sniffing, like this:

drupal_add_css(
  $path_to_css,
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

Drupal 8 does away with drupal_add_css in favour of #attached => array('css' => array( $path_to_css )) but how, in that situation, can you achieve the same thing.

(Nb. I'm not actually using D8 yet, but where things can be done the D8 way in D7, I'm adopting them to ease the learning curve to come!)

I think this'll do it in Drupal 7, it should be the same for Drupal 8:

$build['#attached']['css'][] = array(
  'type' => 'file',
  'data' => $path_to_css,
  'options' => array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE,
    ),
  ),
 );


Ctools wizard back button with #action I'm trying to build a multi-step form with Ctools that will submit to another website upon completion (a hosted payment page). On the last form page, I have set the #action property in the form array to allow it to submit to this other website. My issue however is that this seems to affect the Back button behavior on this form page and directs me to the website I specified in #action when clicked, which is obviously not desired.

Are there additional settings I can tweak to make the Back button behave correctly with the #action property set?

You could drop the #action, then add some curl() code to your #submit callback function for the final step.

Trickier, sure, but it'll work without messing up the form caching for Drupal.


How can I query on a custom content entity base fields? I am trying to write a entityQuery and add condition on the base fields I've defined.

The query:

$query = \Drupal::entityQuery('map_object')
    ->condition('body', 'Test')->execute();

And the error:

Drupal\Core\Entity\Query\QueryException: 'body' not found in Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

The definition:

    $fields['body'] = BaseFieldDefinition::create('text_long')
      ->setLabel(t('Body'))
      ->setDescription(t(''))
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'text_textfield',
        'weight' => 9,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

The column "body" does exists in the entities base table.

I was missing data_table in the Entity annotation. By adding that and update the entity it allowed me to query as expected.

 *   base_table = "map_object",
 *   data_table = "map_object_field_data",


Custom theme region for page I would like to be able to custom theme a region for specific pages, is this possible? If so how?

For example I have a ragion called rightbar and I know the region can be themed using region--rightbar.tpl.php but is there a way of theming this using something like page--node--1--region--rightbar.tpl.php?

Or am I going to have to condition the region--rightbar.tpl.php script?

Use the following code:

/**
 * Implements hook_preprocess_region().
 */
function YOURTHEME_preprocess_region(&$vars) {
  // Make sure we are on a single node page
  // This code will allow you to add the following templates for regions:
  // region--node-NID.tpl.php
  // You can update the conditions to anything you want and rename the template
  // suggestions.
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $vars['theme_hook_suggestions'][] = 'region__node_' . arg(1);
  }
}


Conditionally display one of two fields in Display Suite? I'm wondering if there is a clever or preferred way of using Display Suite to display one of two fields.

So my case calls for either an image, if it is uploaded, or a EVA (entity views attachment). I have them both displaying correctly, and of course if the image is not uploaded (unpopulated), then the EVA field displays fine. But if the image is uploaded, I want to hide the EVA field.

I guess I could do a custom code field, but I would like to avoid that if there is a built-in method of choosing one over another field. Maybe something with field groups?

Thanks!

Use the field formatter conditions module: https://www.drupal.org/project/ffc

This will give you the same options that you have on a blocks (and more). So you can show the field based on any url pattern just as you would blocks:

http://cl.ly/image/2A2Y373Y3e1J

Hope this help.


Drupal file manager that shows relations to content Is there module or simple way to show file relations to content with file manager like elfinder or any other? I am using Drupal 7.

I had that need recently for sorting my images since their file names were weird. What I ended up doing was to create a View of files, with relation to content that used the field that the file was assigned to.

After you do that you can either add the content's fields and properties (like title, nid, etc) and/or group by them.

Hope this helps.


Payment form with Internationalization I have a simple form which should be able to accept payment via Paypal. The form(site) will support multiple languages and depending on the language, it should change the currency appropriately after applying forex conversion.

I don't want to use drupal commerce since it's too bulky for my requirements. I was thinking if possible what set of modules be used to accomplish this, e.g. webform, paypal webform, which internationalization/localization plugins and so on?

The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.

  This module does not directly integrate with Paypal's APIs.
  This module allows a site user to generate a Paypal 'Buy Now', 'Add to
  Cart' or 'Donate' button and replace their form's submit button with
  that button.
  You can manually keep track of the payment status on individual
  submissions.


array_flip(): Can only flip STRING and INTEGER values with nested Field collection I'm getting the error Warning: array_flip(): Can only flip STRING and INTEGER values! in EntityAPIController->load() when using a field collection in another field collection.

Is this a bug in Field collection or the way I load the entities?
Either way: How can I solve the warning?

Here's a simplified version of how I load my entities and sub-entities:

foreach ($node->field_chapter[$language] as $chapter) {
    $items = entity_load('field_collection_item', $chapter);
    foreach ($items as $item) {
        //Some echo's from fields in $item
        foreach ($item->field_paragraph as $paragraphItem) {
            $paragraphs = entity_load('field_collection_item', $paragraphItem);
            foreach ($paragraphs as $paragraph) {
            //Some echos in paragraph
            }
        }
    }
}

The problem is with your code.

You need to pass entity_load an array of entity IDs but the structure of a field on an entity is not just an array of IDs.

$item->field_paragraph is an array of field items and field items can come in many different structures based on the type of field.
Then there is also the ability to have different languages so the language is part of the structure.

The basic structure is like this:

$entity->field_name['language code'][delta]['column_name']

I think for field collections the entity id is stored in the "value" column so you would access it like this (this assumes you aren't using multiple languages):

$item->field_paragraph[LANGUAGE_NONE][0]['value']

That would get you the entity ID of the first item for that field.

It is generally considered better though to use field_get_items() like this:

// Pass a lang code into field_get_items() if you have a multilingual site.
if ($chapter_items = field_get_items('field_collection_item', $node, 'field_chapter')) {
  $chapter_ids = array();
  foreach ($chapter_items as $chapter_item) {
    $chapter_ids[] = $chapter_item['value'];
  }
  $chapters = entity_load('field_collection_item', $chapter_ids);
  foreach ($chapters as $chapter) {
    // Some echos from fields in $chapter.

    // Pass a lang code into field_get_items() if you have a multilingual site.
    if ($paragraph_items = field_get_items('field_collection_item', $chapter, 'field_paragraph')) {
      $paragraph_ids = array();
      foreach ($paragraph_items as $paragraph_item) {
        $paragraph_ids[] = $paragraph_item['value'];
      }
      $paragraphs = entity_load('field_collection_item', $paragraph_ids);
      foreach ($paragraphs as $paragraph) {
        // Some echos from fields in $paragraph.
      }
    }
  }
}

When you are using entities and fields like this it is a good idea to do some debugging to check out the actual structure of the data you're trying to use.


Progress bar based on role I am looking to creating a progress bar on which it is displayed how far you are between role 1 and role 20 (Role names: Level 1 - level 20)?

I take it I would have to use some php or javascript with a hook into the specific users role.

Any ideas on how to go about this?

Cheers,

You can read user roles using below code...

global $user;
$user_roles = $user->roles;
$progress_value = x * 5; // where x is value extracted from $user_roles
if( is_numeric($progress_value) && $progress_value > 0 && $progress_value <= 100 ) {
  $style = "width: ".round($progress_value)."%; display: block";
}
print '

  <div id="progress-value" style="<?php print $style; ?>">

';

Now the solution needs some CSS to make it look like a progress bar. Start with a basic style - just a black border with a gray filling:


How to make a chart in Views with date as x-axis (using the charts module)? I want to make a simple view using the Charts module.

The x-axis will be a custom field of type Date that I want to show in Y-m-d format and grouped by the same date. The y-axis will be NID with COUNT aggregation.

This seems so easy but the problem is the aggregation of the date field. Apparently, views doesn't like to aggregate those kind of fields. Tried Views Date Format SQL but this only works for core date fields (Posted Date, Updated date...)

So, is there any other way to do this?

Within the Charts module, there is an interesting issue about this, i.e. Graph node input over time (support date formatting on a continuous axis).

In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'. The patch(es) included in this issue are expected to soon be applied.


Drupal Commerce - Persistent Data Storage within the Cart My objective is to build an commerce site that attributes 'tokens' (integer values) to products and than keeps a running total of the complete token value within the cart. The idea is to check against how many tokens the user has before allowing a purchase, allowing a product to be added to cart, etc. etc. So far my strategy has been to do this:

Hook_entity_info_alter on the line item product type 'token-based-products' to add a persistent data field for the token value which is required and accessible within views. This seems pretty straight forward.
My Question. How do I keep persistent data storage about tokens within the cart for validation? The objective for this is to create a few hooks that check the running total token value of the cart before allowing/disallowing a product being added AND before allowing products to be checked out.

I discovered that the wise thing to do was to attribute tokens per user and do either a custom module validation or rules before the product being approved for checkout. Due to the fact that quantities can change in the cart, the validation would also trigger on deletes, or quantity changes in the cart.


custom module in user I am making a custom module and the link to the path appears on navigation menu by default but I am interested it appears on primary menu when module is enabled. Is it possible in Drupal 7?

Set the menu_name key of your menu-router item. From the docs:

  menu_name: Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

By default the primary links are set to the Main menu (machine name: main-menu). Therefore use something like this in your implementation of hook_menu:

function hook_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}


Cron task does not create images I've made a module which will parse a few RSS feeds, and automatically creates new content. But I've got an issue creating images.

Since D7, cron are run anonymously, so I think my problem comes from here.
Is there a way to allow anonymous user to create images?

Here's the way I'm doing it. It works if I call FeedController::import via a route, and connected ; but not if I call it through Drupal's cron task.

rssfeed.module

<?php
use Drupal\rssfeed\Controller\FeedController;

function rssfeed_cron() {
  FeedController::import();
}

src/Controller/FeedController.php::import

public function import()
{
  $params = array();
  // some stuff to fill $params array

  $hash = ...;
  $src  = ...;
  $alt  = ...;

  $data = file_get_contents($src);
  $size = getimagesize($src);
  $extension = image_type_to_extension($size[2]);
  $file = file_save_data(
    $data,
    sprintf('public://rss/%s.%s', $hash, $extension),
    FILE_EXISTS_REPLACE
  );

  if ($file) {
    $params['field_image_main'] = array(
      'target_id' => $file->id(),
      'alt' => $alt
    );
  }

  $node = Node::create($params);
  $node->save();
}

As a possible (but possibly not the best) solution it might be the 'account_switcher' service could help. It would elevate permissions for your cron job.

use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();

zessx, please share your solution, if you've found one.

See original Q&A here.


Line breaks are stripped by ckeditor after saving a node programmatically I'm setting a value to a long text using this code :

$node->language = $language->language; // Or e.g. 'en' if locale is enabled
$node->field_job_description[$field_langcode][0]['value'] = $description;
$node->field_job_description[$field_langcode][0]['format']  = 'filtered_html';
$node->field_job_description[$field_langcode][0]['save_value']  = $description;

When viewing the node the line breaks are showing, when I edit this node using ckeditor all link breaks are automatically removed

I would try disabling the Advanced Content Filter in CKEditor as a starting point.

In a typical scenario, most people are exclusively using CKEditor to set and update their field values, so the content stays exactly the same between viewing and editing the node, which is the behavior you're expecting.

However, since you are setting the field programmatically, when you edit the node it's the first time CKEditor is seeing the field value (i.e. the first time CKEditor filters are being run). CKEditor will filter and "correct" your HTML to its standards, so it's not safe to assume your field value will be untouched if it's the first time CKEditor is seeing it.

Your options are to 1) tweak how CKEditor filters your HTML, or 2) conform the HTML you're programmatically saving to the CKEditor standards.


Custom template for media I am using media module and using it in WYSIWYG.
Is it possible to customize the display of media image? Is there any template file I can rewrite or any hook to call? I found file_entity.tpl.php. but it doesn't seem the correct one.
Please suggest.

Thanks

Credit for most of this answer to this article: http://forumone.com/insights/styling-inline-images-with-drupals-wysiwyg-and-media-modules/
First I went and edited the relevant displays and added a caption field (which is what I was trying to do)

Then used hook_media_wysiwyg_token_to_markup_alter() to change the output, in my case I needed to catch the situation where the image got floated in the WYSIWYG, and float the parent element rather.

<?php
function MODULENAME_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
    if (($element['content']['#bundle'] == 'image')) {
        // check if a caption has been set
        if(!empty($element['content']['field_caption'])){
            if(isset($element['content']['file']['#attributes']['style']) && strstr($element['content']['file']['#attributes']['style'], 'float')){
                // move floats to the wrapping element
                $element['content']['#attributes']['style'] = $element['content']['file']['#attributes']['style'];
                // remove inline style on image
                $element['content']['file']['#item']['attributes']['style'] = '';
                // add class to wrapping element so we can style it
                $element['content']['#attributes']['class'][] = 'media-with-caption';
            }
        }
    }
}


Add content links for Organic Groups I'm using OG and OG Extra to make some kind of community website.. but unfortunately I don't see the group content block even when I added it to a region. .
Please what could be the solution for that and is there any alternative
Here's images from my configuration:

Make sure you also install the eva module, in addition to clearing your caches via admin/config/development/performance.

Also, og_extras only works with og 7.x-2.*.

For the "create content" block, look  for "Node content links" under blocks. You also need to configure the Organic Group module to work with the entityreference_prepopulate module, to make it work properly. See here for guidance.


Custom template for custom page in custom module in D6 So I know there is a way to specify a custom template for custom content types etc, but if I have a custom module where I am using hook_menu() to add custom pages with a page callback function, how can I specify that the pages I create use a custom template? This particular site is still on Drupal 6, so I would need to know the Drupal 6 method if it's possible

THANKS

Your custom callback functions still use url aliases so you would just need to define a preprocess_hook that adds template files if that particular alias is being served. Here is a basic function you can use in your template.php file, modified from this handbook page:

function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'YOUR CUSTOM HOOK')) {;
      $template_filename = 'page' . '-' . 'YOUR CUSTOM TEMPLATE';
      $vars['template_files'][] = $template_filename;
    }

}

So, for example, if your menu hook was /trigger/awesome then the code could look like this:

function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'trigger/awesome')) {;
      $template_filename = 'page' . '-' . 'awesome';
      $vars['template_files'][] = $template_filename;
    }

}

and the theme would now look to serve this page using the page-awesome.tpl.php file in your theme folder.


Site Down for few minutes after clearing cache My site is going down every time whenever I am clearing the cache. Site will works again in 5-10 minutes after refreshing web page 2-3 times.
Also I am getting 500 internal server error after clearing the cache.
After refreshing web page 2-3 times site is working fine as before.
Additional information as follow.

Drupal 7
Boost
APC
Apache web server

Can any one put some light on above issue.

Edited

Apache error logs
[Tue Jul 07 08:51:12 2015] [warn] mod_fcgid: read data timeout in 40 seconds, referer: xxxxxxxxx.com

[Tue Jul 07 08:51:12 2015] [error] [client xx.xx.xx.xx] Premature end of script headers: index.php, referer: xxxxxxxxx.com PHP Warning: Module 'apc' already loaded in Unknown on line 0

[Tue Jul 07 08:51:18 2015] [warn] mod_fcgid: process 26541 graceful kill fail, sending SIGKILL PHP Warning: Module 'apc' already loaded in Unknown on line 0 PHP Warning: Module 'apc' already loaded in Unknown on line 0

Have you installed "Memcache" module ? If no then :

First of all, check mysql slow query log. Also install "Memcache" module which will help you to reduce mysql server load.

Please refer this link for Drupal Memcache installation.


Adding a 'Add New Listing' (Create Content) Link on Local Tasks Menu I am working on making user pages for a certain type of user who can add/edit/delete content on my Drupal site. I've figured out how to use Views to create a 'Manage Listings' tab which appears on the user's profile, now I need to make another Local Task tab (or any kind of link) that allows the user to add new content.

I tried just adding a header to the view using basic markup text that contains:

Add New Listing

But because the link is displayed from the 'users/admin/' page, the link ends up bringing them to 'users/admin/node/add/' which doesn't exists (obviously). How can I create a create content link without messing up the path?

I would provide a screenshot, but my reputation isn't high enough to do so. Thanks.

Add a forward slash at the beginning:

Add New Listing


Titles on pages underneath the text I must have checked or unchecked a button somewhere, sometime, because ever since I remember starting to work on my site the titles of the pages are showing underneath the articles / texts on the pages, instead of on top of them, like they should. (example: see link to screenshot) I tried the 'manage display' option but I the title isn't part of that with the basic pages.

Does anyone have an idea of how I could fix this? :) For I have no clue...

Screenshot: http://img89.imageshack.us/img89/2140/headerunder.png

(the tags I wanted to use were not available for me so I hope I tagged this right..)

well propably is a theme issue. if you encounter this on all pages check your page.tpl.php and make sure this

  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

is before

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

this is all i can say with the info provided.


How to print paragraphs in twig template? I have a content type, basic, where i have added a Paragraph field field_pr that has two fields: field_text, field_color. I have a twig template node--basic--full.html.twig where I want to print the value of the paragraph field node.field_pr.

node.field_pr can have between one and ten paragraph values.

When I print the array for content.field_pr, I get a huge array. However, I only want the values from the field_pr.field_text and field_pr.field_color. How would I be able to do this from the node twig template?

I have tried the following but cannot seem to access the values. What am I missing?

{% for field in content.field_pr %}
   {{ field[loop.index0].entity.field_text.value }}
   {{ field[loop.index0].entity.field_color.value }}
{% endfor %}

{% for field in content.field_pr %}
   {{ field[loop.index0]['#paragraph'].field_text.value }}
   {{ field[loop.index0]['#paragraph'].field_color.value }}
{% endfor %}

Here is an image of the array that is printed for the node.field_pr field.

Not sure if it's possible with your current approach. Here is how I would approach this.

In your node template file just do a {{ content.field_pr }}

Create a template file for your paragraph.

  paragraph__[view_mode] (e.g. paragraph--default.html.twig)

  paragraph__[type] (e.g. paragraph--image.html.twig)

  paragraph__[type]__[view_mode] (e.g.
  paragraph--image--default.html.twig)

  source: Theming in Paragraphs for Drupal 8

In paragraph--[type].html.twig you do {{ content.field_text }} and {{ content.field_color }}