How can I include user pictures in e-mail notifications sent by the privatemsg module? I have the Private Message module configured to send notifications when users receive a private message.  I have the Mime Mail module configured and working; the private messages are sent as HTML and display properly.  However, I have been unable to find a way to include user pictures in the messages.

On my site, I have a field that contains the user picture (I am not using the standard user pictures built-in to Drupal).  However, I have overridden the user pictures template to show this field, so a solution that works for user pictures should hopefully work for my case as well.

I tried to solve this with tokens.

The token module makes available the following token: [privatemsg_message:author:field_acc_profile_picture]

However, when I include this token in the message, it is simply returned as a text string; no substitution is performed.

I thought this could be done with PHP but there is no way as far as I can tell to include PHP in the e-mail notify message field.

So, how can I include user pictures in e-mail notifications sent by the privatemsg module?

One way you could do this (which is what I do on a couple sites), is to implement hook_privatemsg_message_insert() in a custom module. Turn off the privatemsg module emails or any rules-generated emails, and instead write a custom bit of code that sends the private message.

In my case, I needed to do a few other customizations, but at its simplest, you can get a profile picture URL by loading the user $account from $message->author->uid.

A quick example:

<?php
/**
 * Implements hook_privatemsg_message_insert().
 */
function custom_privatemsg_message_insert($message) {
  global $base_url;

  // Get the account from which message was sent.
  $account_from = user_load($message->author->uid);

  // Get the person to whom the message is being sent (I only handle one).
  foreach ($message->recipients as $key => $recipient) {
    $account_to = $recipient;
    continue;
  }

  // Set up variables for our message body.
  $variables = array(
    'from' => $account_from->realname,
    'link' => l('Click here to view/reply to this message', $base_url . '/messages/view/' . $message->thread_id, array('external' => TRUE)),
    'message' => check_markup($message->body, $message->format),
  );

  // Print the message body using a custom theme function. Because email clients
  // require obnoxious markup, it's best to use a theme function or template...
  $body = theme('custom_private_message', $variables);
  $body_plain = strip_tags($body);

  $subject = t('New Private Message: ') . $message->subject;
  $email_to = $account_to;
  $email_from = $account_from->realname . ' <' . $account_from->mail . '>';

  // Now, use whatever mechanism you want to send the actual email.
}
?>


'After update' event firing when node is deleted I have a rule set up that uses the following action:

  After updating existing content of type

It's working fine when a node is updated, but I just discovered that this rule also fires when nodes of the specified type are deleted. This makes sense, since changing the status of a node is technically an update, but this is not the desired effect as emails should not be sent when the node is deleted.

I added a small chunk of PHP inside the email generated by the rule to see what the value of $node->status is in this rule, but it is still 1, not 0 as I expected.

How can I use the 'After updating existing content of type' event, but not have it react when a node of that type is deleted?

Have you tried adding a rules condition for the published status of the updated node? That should stop the rule from firing.


How to grant permissions for some role to execute custom Rules Components? I created a view (table) and i asociated views bulk operations. I created 4 rules components. I have permissions only for user/1 (admin). Another user role (eg. editor) can't see these options. "editor" user can see only "DELETE ITEM" rule components.

In permissions I have only the default actions (components); I created 4 new Rules Components, and these aren't displayed in Admin > People > Permissions.

Is there another method (trick) to give permissions for another role for custom Rules Components? Am I missing something?

If you've enabled "Action permissions" check the role has permission to "Execute [action]" in Admin > People > Permissions


How to iterate over all the nodes from a content type I want to recover some info from a field of all the nodes of a specific content type.
I know how to do it using a db_query and getting all the node ID then iterate over them.
What I would like to know is if there's is another way around this using drupal functions.

Drupal core provides a class called EntityFieldQuery().  There is also a handy document page for using it, that has lots of examples.  In its simplest form:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    // do something awesome
  }
}

This will load all published nodes of type "page". You periodically need to adjust this to

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

 foreach ($nids as $nid) {
    $node = node_load($nid, NULL, TRUE);
    // do something awesome
  }
}

to avoid loading too much at once, which can cause memory issues.


Is there a way to make the comment module email the administrators when a comment needs approval? I'd like to be notified whenever comments are made on the site which require administrator approval before publishing; basically, I'd like to know when something new appears in the Approval Queue. I can't see any obvious settings for this.

Sounds like something Rules should be able to do.


Show field's help text on node page I'd like to achieve the following:

I'd like to give help text for a field in a content type, and I would like to show that help text on the node page as well.

I've looked at $content in page.tpl.php and $variables in theme_field() but these variables doesn't seem to contain these help texts.

How can I make these help texts appear?

You can get access to help by use field_info_instance function in Your template.php

At the beginning let's assume that You have a field called 'spagetti' created in content type 'Article'. Also,  in this case, mytheme is Your default theme.

First, edit mytheme's template.php file and put into following code:

/**
* Implements template_preprocess_field
*/
function mytheme_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if($field_name == 'field_spagetti') {
    //Get help ('description' parameter) of field Spagetti
    $instance = field_info_instance('node', $field_name, 'article');
    //Add new parameter to the field
    $variables['element']['#help'] = $instance['description'];
  }
}

Now You can get help value from field array.

For example You may to create template for field spagetti:
(field--field-spagetti.tpl.php)
and render field inside:

$field = $variables['element'];

echo $field['#title'];
echo $field['#items'][0]['value'];
echo $field['#help'];


Drupal 8, error on order view page I'm working on a Drupal 8 / Drupal Commerce website, and I run into "Website encountered unexpected error" when trying to access /admin/commerce/orders/* pages (order view page).

In log messages I get :

Error : Unsupported operand types dans Drupal\views\Element\View::preRenderViewElement() (/---/core/modules/views/src/Element/View.php ligne 49)
#0 [internal function]: Drupal\views\Element\View::preRenderViewElement(Array)
#1 /---/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#2 /---/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#...
#10 /---/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('commerce_order', Array)

So it seems that a view displayed on these pages causes this error. Does anyone ran into this error ?

Thanks

EDIT

After some debugging, I found that in

/core/modules/views/src/Element/View.php L49
$element += $view->element;

...$view is null, which causes the error. Above that line, $view is defined by this line (L43) :

$view = Views::getView($element['#name']);

...and $element['#name'] = commerce_order_item_table.

The View::getView() method is :

public static function getView($id) {
  $view = \Drupal::service('entity.manager')->getStorage('view')->load($id); // this call returns null
  if ($view) {
    return static::executableFactory()->get($view);
  }
}

So it seems that I miss a view (commerce_order_item_total) ?...
I'll report further info here.

EDIT 2

My missing view seems to be defined in

/modules/contrib/commerce/modules/order/config/install/views.view.commerce_order_item_table.yml

...but is not found apparently.

EDIT3

On /admin/config/development/configuration/single/export (exporting a single element), selectting "view" as configuration type, I cannot find "commerce_order_item_table". Doing a manual full export (drush cex --destination=sync) I don't find a views.view.commerce_order_item_table in sync folder.

I didn't find out why my order views disappeared, but I was able to import them back using configuration synchronization :

https://www.drupal.org/node/2917828#comment-12321847


How to dynamically add options to  list in CKeditor dialog I am building a CKEditor plugin for Drupal 8. Currently it adds a toolbar button which triggers a modal dialog containing a select list with a few options. I've hardcoded the options in plugin.js, and everything works as expected. But those options must actually be dynamically added with php.

This is my plugin dialog definition, as per http://docs.ckeditor.com/#!/api/CKEDITOR.dialog.definition.select with hardcoded options.

This goes in the plugin.js file loaded via CKEditorPluginInterface::getFile() in my plugin class:

CKEDITOR.dialog.add('pluginDialog', function(editor) {
  return {
    title: 'Available options',
    minWidth: 300,
    minHeight: 200,
    resizable: CKEDITOR.DIALOG_RESIZE_BOTH,
    setup: function(e) {},
    commit: function(e) {},

    contents: [{
      id: 'tab-options',
      elements: [{
        type: 'select',
        id: 'select-options',
        label: 'Select an option:',
        items: [
          ['Option 1', 'Option 1'],
          ['Option 2', 'Option 2'],
          ['Option 3', 'Option 3'],
          ['Option 4', 'Option 4']
        ]
      }]
    }]
  };
});

CKEDITOR.dialog.definition.contents.elements.items[] have to be built from PHP. Any help is appreciated.

You can pass data to ckeditor via the getConfig method in your plugin, e.g.:

public function getConfig(Editor $editor) {
  return [
    'pluginName_options' => $this->buildOptions()
  ];
}

And in the JS:

items: editor.config.pluginName_options


Simple OAuth + JSONapi response when token is expired - Decoupled We're using the 'Simple OAuth' and 'jsonapi' modules for the front end authentication in Angular of our decoupled Drupal project.

We've noticed that when the user credentials are correct but the token is expired the header response is still 200 'ok' with a message that indicates that the Token no longer valid.

But we need a 400/401 or 403, like it is described in the oath documentations.

Is there a reason why this is implemented like this? Or is there a way to alter the response?

Is there a reason why this is implemented like this?

200 ok is expected status code for collection resources, even if one, many, or all entities were excluded from the collection resource for access reasons.
From https://www.drupal.org/project/jsonapi/issues/2853066:

The status code for a "collection resource" should be entirely distinct from any or all of the entities represented at that resource.
Unless there is an access control mechanism that is explicitly a prerequisite for accessing any list of entities of a given type that we can leverage, then it must be assumed that any consumer must have access to any collection resource.
It is completely consistent with REST to return a 200 response to an empty collection, even when all those entities have been elided for access reasons.

Or is there a way to alter the response?

Of course, you can. Check the documentation about altering routes and providing custom access tagged service:

https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones
https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

Finally, the link you provided in the question is to oauth specs, and is irrelevant to jsonapi. Oauth resource in Drupal (/oauth/token) will correctly give you 4xx in case of any errors when obtaining a new token.


setTimeout and QuickTabs I'm using QuickTabs with a couple of views to show some content within tabs. This works fine.

Now, I want my tabs to automatically cycle. Basically, this issue sums up what I want to do.

The thing is, it partially works. I have two tabs, and it cycles to the second tab, but immediately goes back to the first. I have enough time to see it blinking, but that's it.

Here is the slightly modified code (original code does the same, I just find it nicer):

var rotateSpeed = 5000;
setTimeout(function featureRotate() {
  var active_tab = $('ul.quicktabs-style-basic').find('li.active')
  var next_tab = active_tab.next()
  if(next_tab.length){
    next_tab.find('a').trigger('click')
  }
  else {
    /* remove the following line if you don't want it to cycle */
    $('ul.quicktabs-style-basic').find('li.first a').trigger('click')
  }
  setTimeout(featureRotate, rotateSpeed);
}, rotateSpeed);

Debugging it, it looks like the setTimeout function works when it goes through the else statement, but not when it goes through the if one.

Alright, the problem was just plain old Javascript.

The bug made it look like the setTimeout had no delay parameter, which defaults to 0.

After looking more at it, the rotateSpeed variable was not available in the block scope of the featureRotate function, but in its closure.

So I replaced the following:

// In the featureRotate function
setTimeout(featureRotate, rotateSpeed)

With:

// In the featureRotate function
setTimeout(featureRotate, this.rotateSpeed) // Look at this magic :-)

And it works perfectly!


Is there an input filter to add the class clearfix to all  tags? I have a lot of inline images in my content. Most of the time I want to have some sentences and an image grouped together. To get a nice layout I have to mannually add class="clearfix" to all <p> tags. This is especially anoying because the class often gets lost when I edit the text in the wysiwyg editor.

Is there an input format, or some other easy way to do that automatically?

If you are trying to add the "clearfix" class to all of your paragraph tags, sitewide, it would probably be more simple to apply the "clearfix" properties to your "p" tag in your CSS files.

So you'd find:

.clearfix { ... }

and add in your paragraph tag like so:

.clearfix, p { ... }

Or copy the properties to your custom CSS file if you are worried about overwriting your changes.


Permission tmp problem: Change of tmp directory I recently installed one new Drupal (7.32) on a server that doesn't belong to me. Since then, I have a permission problem, I can't edit CHMOD rights and when I try to add new content (with image(s)), I can't. Here's the mistake returned by Drupal:

Warning: move_uploaded_file(): open_basedir restriction in effect.
File(/home/tmp/php/phpBKRRLYL) is not within the allowed path(s): (/home/tmp/sessions/:/home/XXX/public_html/:/home/XXX/shared) in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file(): open_basedir restriction in effect.
File(/home/tmp/php/phpBKRRLYL) is not within the allowed path(s): (/home/tmp/sessions/:/home/XXX/public_html/:/home/XXX/shared) in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file(/home/tmp/php/phpBKRRLYL): failed to open stream:
Operation not permitted in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

Warning: move_uploaded_file():
Unable to move '/home/tmp/php/phpBKRRLYL' to '/home/XXX/www/public_html/YYY/drupal-7.32/sites/default/files/anime.jpg' in drupal_move_uploaded_file() (line 1639 of /home/XXX/www/public_html/YYY/drupal-7.32/includes/file.inc).

As we can see, Drupal apparently uses the server's tmp directory (in which I have no rights) and I would like it to use another tmp directory in "/home/XXX/www/public_html/YYY/drupal-7.32/" so that I can add/edit content properly.
How could I do this? By editing the "/includes/file.inc" file (if so, which line(s) shall I modify to do this?)? Something else?

NB: The system administrator is unavailable for an extended period so he can't change my rights for now. That's why it's important that I could change this tmp directory.
Thank you!

You can edit the relevant setting in Configuration > Media > File system > Temporary directory (/admin/config/media/file-system).

You can choose any directory in your document root skipping the forward slash. I would recommend you to specify tmp. Take care of the permissions.


New region shows up weird If you visit http://balancesocialmedia.com/, under the carousel, there are 4 boxes of content; they are block views with col-md-3 as CSS class.

The new region I created is called content_bottom.

regions[content_bottom] = 'Content Bottom'

I then put this code in the page--front.tpl.php under content region (near the bottom of this snippet).

  <section<?php print $content_column_class; ?>>
  <?php if (!empty($page['highlighted'])): ?>

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

  <?php endif; ?>
  <?php if (!empty($breadcrumb)): print $breadcrumb; endif;?>

  <?php print render($title_prefix); ?>
  <?php print render($title_suffix); ?>
  <?php print $messages; ?>
  <?php if (!empty($tabs)): ?>
    <?php print render($tabs); ?>
  <?php endif; ?>
  <?php if (!empty($page['help'])): ?>
    <?php print render($page['help']); ?>
  <?php endif; ?>
  <?php if (!empty($action_links)): ?>

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

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

   <?php if ($page['content_bottom']): ?>

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

<?php endif; ?>

I tried moving the code under the closing section tag, removing the container and row class but the first block view is always renders a bit funny.

Also, I can move the blocks to the content region and shows up as expected. I can't track down what's different between the two regions.

Does anyone see where I'm messing up?

You seem to have CSS that removes the top margin from the first block:

.block:first-child h2.block-title, .page-header {
   margin-top: 0;
}

You can override this by simply adding this piece of CSS in your CSS file:

.region-content-bottom .block h2.block-title {
  margin-top: 21px;
}


how to retrieve date in computed field How to retrieve date from a date field and store it in computed field? I have tried this code:

$start_date = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_start_date')));
$entity_field[1]['value'] = $start_date;

But it displays 'datetime'. I want to retrieve the value.

It looks like you're indiscriminately popping values off of the array returned from field_get_items, without checking to see which index you actually need. I haven't tested this but I think you'll have better luck with code like this:

$items = field_get_items($entity_type, $entity, 'field_start_date');

// Use array_shift if you want the FIRST field item
$item = array_shift($items);
// OR
// Use array_pop if you want the LAST field item
$item = array_pop($items);

// Get the date value of the field
$start_date = $item['value'];

// Use start date
$entity_field[1]['value'] = $start_date;


Translation has duplicate admin content listings When I add a language translate option to a piece of content for French.

Drupal now adds a second listing of that piece of content in the content admin view.

Is this the expected behavior?
What if you had 10 different language transaltions, would you have 10 times the content listings?
Is there a setting or module to only show a single listing and access the translations under that content entities "translate" tab?
Is there a better way to translate all my content to another language that could avoid this duplication issue?

Yes, that's expected - until filters are applied, that page is designed to list all content on the site, and separate translations are considered separate content.
Assuming you had 10 translations for each piece of content, yes, you'd see 10 times the number of listings as you would if you didn't have the translations.
That page is powered by a View. You can edit that View and do what you want with it - there's a language filter, maybe you want to set the default for that to the default language, thus allowing people to still browse the other translations using the filters if they want, but keeping things to the default language for most cases. Maybe you want to leave it as-is, but add a "Language" column, to make it easier for admin users to distinguish. There are a lot of options so you can probably get it configured in a way that makes sense for you.
No, there's no other way to translate content.


Undefined variable error in node.tpl.php I'm having an issue with an undefined variable

  Notice: Undefined variable: comment_count in include() (line 33 of ...\themes\simplecorp\node.tpl.php).

This is what my line 33 looks like:

<?php print $comment_count; ?>

I don't understand this error, Can someone tell me how to do it?

If you want to get rid of this notice, replace your line 33 with:

<?php if (isset($comment_count)) print $comment_count; ?>


How can I make the "field_media_document_display field be filled with a 1? Although I have the Files displayed by default set as true and when I manually add one it defaults to 1 , when I use the step one process it put s a null there . Since it has a null the next time a user tries to change the name it doesn't work.
I am using the Migrate File Entities to Media module, this is my code in step 1. where can I add something to make it fill in the field_media_document_display_field as a 1 ?
field_media_document/title: title
field_media_document/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'

In media-migration-step1.yml.twig I see:

So should be:
field_media_document/display: TRUE
field_media_document/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'

If still not, try:
field_media_document/display:
    plugin: default_value
    default_value: TRUE
field_media_document/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'


Drupal 7: Customizing the display of a view I'm using the latest version of Drupal (7.8). I am using Views to list out all articles with a certain tag in a block. I'm showing the latest 5 articles. No problems so far.

Now I want to customize the display so that the latest article displays with the title as well as the featured image whereas the other 4 articles show up with the title only.

I'm trying to use the suggested templates feature but am not sure how to use it since the HTML comes pre-created in the $rows variable.

Sort of like this:

Look into creating your first article display as an attachment.  Attachments allow you to group different views together. This is for Drupal 6 and Views 2, but it should give you some idea of what attachments are.

  A Views Attachment is simply a type of Views Display that gets attached to another View Display (usually a page display or a block display).


How do I get the rate vote number? How do I get the rate vote number, e.g. the number after "funny," "angry," or "mad"?
I looked for the values in the database, but I didn't find a column that stores it.thank you.

I think that is the rate module, like many such modules it uses the voting api.

You should use votingapi_select_results() to get the results. The $criteria array that you pass to it will be

$criteria = array(
    'content_type' => $content_type,
    'content_id' => $content_id,
    'tag' => $widget->tag,
  );

I have only skimmed the code but I belive that $content_type and $content_id are node type and node id. The $widget->tag will be specific to your widget.


Résumé upload functionality in Drupal 7 Is there any module available in Drupal 7 for getting a résumé uploading functionality? I need a form with a couple of text fields and a file upload field that accepts files of .doc, .odt, and .docx formats. My requirement is to send an email also with the attachments, and also see the list of submitted résumés.

Add a Résumé content type. Add your text fields and a file field to this content type. Set your permissions accordingly, allowing whichever user roles you want (or anonymous) to create this content.

This will allow people to upload their resumes.

Get the Rules module and create a rule a bit like follows

Events

Node - After saving new content

Conditions

Node - Content is of type:  Résumé

Actions

System - Send mail

You can use Token to put content fields into the email, but I'm not sure if you can put links to the file.  If not, you can at least put a link to the content that contains the file.

Lastly...use Views and create a simple view that shows Résumé content -From here, get  sorted however you want.

For extra points, you could also use the Flag module to flag résumés (e.g. follow up, spam, not useful and so forth), and then create more views based on those flags (so you can only see useful résumés for exampleetc).


Create Relation between two vocabulary terms in views expose filter Suppose if i have 2 vocabularies in which first vocabulary name is "Country" which contain some country names and Second is "Cities" which contain some cities names. If i want to select a particular country from "country" expose filter and i want that only few selected cities will automatically appear in "cities" expose filter. So that user dont have to go through all the list of cities of all the countries.

Is it possible with drupal views or any contributed module ? otherwise i have to do it with jquery hide/show .

I am posting answer to this question, as it might help somebody.
I havent got any suitable module which can create relation between two taxonomy vocabularies as i want, But i have modified my taxonomy a little bit to do this from a module.

I have merged my 2 vocabularies into single . I have placed country as parent term and all the cities as sub-term. So my structure is like this :

India

Delhi
Rajashtan
Chandigarh
Gujrat

USA

Alabama
Alaska
Georgia
Illinois

Then I have used a simple module called "Simple Hierarchical Select" https://drupal.org/project/shs or you can also use Hierarchical Select" https://drupal.org/project/hierarchical_select
But hierarchical select has more functions but if you have taxonomy related task only then you can use only SHS as in my case.

Now go to the content type -> manage fields -> select term reference-> simple hierarchical select .

Now go to your views => select the "your-field-name" (hierarchical select ) from filters
and force it to some depth.

Then it will show first country name and then child term which are city names.


Does install.php open a connection with ANSI ON? Please accept my warm regards . I need some guidance and light to move ahead.

I am from SQL Server background and has been doing some work on Linux machine offlate and making it connect with SQL Server. I have succesfully installed FreeTDS and can connect to Windows SQL Server machine. Now, I installing Drupal in Linux and during its installation it creates multiple tables in the database.

After creating few tables it quits. I traced and found that it stopped because it needed ANSI settings ON to create an index on the table date_formats  but found it off. I cannot set it at my DB because it chooses the client settings at the runtime.

I am not sure if Drupal install.php opens a connection with ANSI off settings because this causes the index creation to fail. Please help to investigate it.

Regards
Chandan Jha

If you look in database.inc for your database driver you can see what parameters are passed from drupal on the default connection. If you apply this patch to drupal8 you can set additional PDO options supported by the driver https://www.drupal.org/node/1926284


Redirect contact form on submit Using Drupal 8 and trying to get the contact form to redirect to the same page after submitting. By default it seem to redirect to the home page.

I have edited my themename.theme file

function themename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
  }
}

This throws a bunch of mysql errors. Like so:

Uncaught exception thrown in session handler.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes: UPDATE {sessions} SET uid=:db_update_placeholder_0, hostname=:db_update_placeholder_1, session=:db_update_placeholder_2, timestamp=:db_update_placeholder_3 WHERE ( (sid = :db_condition_placeholder_0) ); Array ( [:db_update_placeholder_0] => 1 [:db_update_placeholder_1] => ::1 [:db_update_placeholder_2] => _sf2_attributes|a:1:{s:3:"uid";s:1:"1";}_sf2_flashes|a:0:{}_sf2_meta|a:4:{s:1:"u";i:1454074283;s:1:"c";i:1452243053;s:1:"l";s:7:"2000000";s:1:"s";s:43:"dVseXv540u6wL5GZm_gs6fzuP9qtck-j5A5lexqnaQE";}authorize_page_title|O:48:"Drupal\Core\StringTranslation\TranslatableMarkup":3:{s:9:"*string";s:14:"Update manager";s:12:"*arguments";a:0:{}s:10:"*options";a:0:{}}messages|a:1:{s:6:"status";a:2:{i:0;O:25:"Drupal\Core\Render\Markup":1:{s:9:"*string";s:1020035:"<script class="-kint-js">(function(){if("undefined"===typeof kintInitialized){kintInitialized=1;var e=[],f=-1,g=function(b){var a=window in Drupal\Core\Session\SessionHandler->write() (line 89 of /Users/timmcdonald/Code/waypoint/v3/core/lib/Drupal/Core/Session/SessionHandler.php).

and other errors.
Is there something I am missing?

Here is what I ended up doing in a custom module if anyone else needs to do this

use Drupal\Core\Url;

function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $form['actions']['submit']['#submit'][] = 'custom_module_contact_submit';
    dpm($form['actions']['submit']);
  }

}

function custom_module_contact_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    drupal_set_message('we sent a form woohoo');
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
}


Linking organic groups - or am I overlooking a better solution? I'm attempting to use Drupal 7 with organic groups to create a network of groups for local affiliates of a national organization. Initially we want users in each group to be able to post private content inside of the group, which is not a problem. However, since local affiliates tend to share ideas and files we'd also like a group administrator to be able to "link" their group with another trusted affiliate so that users of the two affiliates can have access to the content in the linked groups.

I realize the people in each group can be added to other existing groups, but as far as I am aware this is on an individual basis and thus would not be sustainable going forward as members that are added and removed from their primary group would not automatically have their membership changed in the other affiliated groups.

The closest thing I've seen is http://drupal.org/project/og_affiliations but it's no longer being updated. I was wondering if anyone has any ideas for approaching this setup or if there might be a better solution than OG that I'm overlooking?

I have not played around with og much but from what you are saying this should be possible with rules. Basically you would create an event based on the change (perhaps create a group admin role only flag which lets them flag each other to create the bond and the trigger. That way if one breaks the bond, the permissions are reversed which would require an extra but similar rule) that would trigger an action to load a list of users from the group. Then add a loop to loop through the list of users performing an action on each one as you go (i.e. add to other group). Not sure what custom actions og brings to rules or vice versa but I see no reason why it shouldnt be possible this way.


How to override ID's in Drupal and comply to CSS Lint|? How to override ID's ( or not use ID'S) in Drupal and use Classes only to comply to CSS LINT ( consider that I must use a subtheme and not always can write the HTML. I will have to work with what Drupal gives me). Can anyone advise me about best practices?

Using a subtheme you can override whatever templates contain IDs and change them to use classes instead, updating the CSS along the way.

For example you can override the node template by creating a node.tpl.php file in your subtheme, and the markup can be changed to whatever you need.

You'll have to identify which templates need to be overridden yourself, as there isn't a list available; it will depend on what modules you have installed, and what base theme you're using.

It's also worth bearing in mind that contributed modules (and possibly core modules) may use IDs to target elements in javascript. So test thoroughly, as you might need to make some changes there as well.

However

Don't forget that you're just trying to comply with CSS standards here. You don't need to actually remove the IDs to do that, just any CSS that uses them in selectors.

Drupal 8 core conforms to the rule anyway (see .csslintrc in the root), so you should be covered there, but contributed modules may not. That's when you'll need to check manually and maybe override templates/CSS files that they provide.

Earlier versions of Drupal don't conform to the same standards as far as I know so YMMV.


Jquery in my custom zen theme the following is my js file mymodule.js

$(document).ready(function(){

    alert('test');
});

and i just add this file in my customtheme.info .

scripts[] = js/mymodule.js

However, the js code only be executed at some pages, not all pages.

What could the problem will be?

Does anyone have the same situation before?

Please help me fix this.

In Drupal 7 to avoid conflicts with another library you should wrap your code in:

(function ($) {
  // Original JavaScript code.
})(jQuery);

To learn more visit: http://drupal.org/update/modules/6/7#javascript_compatibility


How to translate admin interface in Drupal Commerce Kickstart? I have translated my site in Japanese. But it is not translating all the content. I want to translate all the strings available on the site, including admin panel.

I searched for the string in the translate interface, but I couldn't find it. I used Translation template extractor to search the strings. But this thing also didn't help me.

Please tell me how to change the admin side text?

Here's the image showing what kind of strings I want to change :

I did a search on my computer, I found product.html which contains the text you were looking for:

Help on products

Each product has both a display and can have many variations (size, color, etc). This page lists all of the products grouped by display.

To see the variations of a product, click on â€œQuick Edit.â€ Using bulk updates (located at the bottom of the page) more than one product can have various actions applied.

More Information

Product Management Overview

Choosing between Products and Product Variations

Adding a New Product

What are Product attributes and variations?

What are Product Node Displays?


Re-creating complex CSS footer layout in Drupal I've been given some HTML & CSS files by our university web designer and need to replicate essentially the same layout into the library website I'm creating in Drupal. The footer (pleased see attached link) has been the biggest hurdle so far. With this type of column-based inline layout consisting of menus (which I haven't created as menus yet), should I be creating new regions in my .info file to handle each menu? Also with the university address info. and icons, should this be another region or should I add custom variables and HTML so it is just part of the main footer region? Or is there a way using Blocks, Panels or another module to create this layout more efficiently?

One last thing-as you can see the columns have three headings (Who Are You?, Quicklinks, and Admissions) so I plan to create a menu with each name as title. What's the best strategy to deal with the overflow of menu items over more than one column without having to create six separate inline regions for layout purposes?

Thanks for any assistance, guidance, or suggestions. This site has been an invaluable resource in learning Drupal over the past few months and I've learned a lot from all your posts, responses & comments to each other.

The footer design:
footer http://dl.dropbox.com/u/664958/footer.png

I'd set up one region for those menus, in that region have 3 x menu blocks (http://drupal.org/project/menu_block), 1) Who Are You, 2) Quicklinks 3) Admissions.

CSS will be your friend to get the required layouts.

The "Who Are You" menu should be easy, float the menu block left and fix the width. The same for the "Admissions" menu.

The middle menu will be similar but all you need to do is have a wider fixed width menu block, fix the width of the menu items and float them left. Then you'll have to order the menu items to make them appear in the correct columns.

The text below the menus should simply be 2-3 more standard text blocks just styled appropriately.

I hope this makes sense. I'll be interested to see how other developers would attack this.

Cheers.


Change the value in the user join date field I am building a Drupal 7 site.

User can register in my site using Hybridauth or regular registration form.

I want to change the value in the joined date field.
Meaning change the date a user joined the site.

How can I do that?

Old users:  update the users table in your database.  It will be far more efficient.

New users:  https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7     I don't think the date/time are saved in that form, so what you could do is find the UID and update the table using a sql query after the save is done.


The best way to update existing Paragraphs in Production with newField = TRUE how are you?
Do you know what's the best way to fill a new field inside of Paragraphs in a Production Environment?
E.g.:

I have a Paragraph called "MyParagraph" and this Paragraph has two fields "Title" and "Description";
This Paragraph is already present on our Production Environment and there are 500 nodes with this Paragraph filled;
I created right now a new field called "Show Description". This field is a checkbox and default is "Checked";

Now I need to update all of these 50 Paragraphs in production with this new field "Show Description" = TRUE
Do you know what's the best option to do that?
I used a simple hook_update to do this, and another script with a batch process.
But I want to see if there is the best solution to do this update.

For a no custom code solution, Use Views Bulk Operations with Views Update Fields
Or with Views Bulk Edit, although it's crashing with Paragraphs, so maybe in the future for this particular  case.
PS: Do first a dry run on dev/local before doing it on live.


Contact form node integration I have content type and I want to add contact button at the bottom of node page, but

I've problem so how I can add easy contact form that add node title at the message and When anonymous user goes node page called "Example 12" and after body text there is "Contact" or "Ask more" button and it goes form page.

After user left the message it goes admin content list and admins knows page where he/she goes that contact form.

Example I check page named "Example12" and there is ask more button.. I press that and I goes Ask more form and there is some fields and "You want to know more about example12" (example12 page title) and then I send that and it goes admin content list page so admins can contact me because I left mail in mail field.

So what is the best way to do it? Is there any good modules for that?

It sounds like a case for the Webform module.

  Webform is the module for making forms and surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has an extensive API for expanding its
  features. Some good examples could be contests, personalized contact
  forms, or petitions.

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


How to join three entities in a view? I have a Drupal schema where I want a view to display node 'item' results based on fields from an associated 'catalogue' node. Each associated 'catalogue' has a 'catalogue_ranking' node which is used to order 'item' results.  So the join I am looking for is:

items <== LEFT JOIN catalogue <== LEFT JOIN catalogue_ranking

I can manually construct the SQL I need to produce the results as follows:

SELECT node.nid, substring(node.title, 1, 20) AS title, field_data_field_catalogue.field_catalogue_nid,
       node_catalogue.nid AS cat_nid, substring(node_catalogue.title, 1, 20) AS cat_title,
       field_data_field_ref_catalogue.field_ref_catalogue_nid, node_cat_ranking.nid AS rank_nid, field_data_field_priority.field_priority_value
  FROM node node LEFT JOIN field_data_field_catalogue field_data_field_catalogue ON node.nid = field_data_field_catalogue.entity_id
                 LEFT JOIN node node_catalogue ON node_catalogue.nid = field_data_field_catalogue.field_catalogue_nid
                 LEFT JOIN field_data_field_ref_catalogue field_data_field_ref_catalogue ON node_catalogue.nid = field_data_field_ref_catalogue.field_ref_catalogue_nid
                 LEFT JOIN node node_cat_ranking ON node_cat_ranking.nid=field_data_field_ref_catalogue.entity_id
                 LEFT JOIN field_data_field_priority field_data_field_priority ON node_cat_ranking.nid = field_data_field_priority.entity_id
  WHERE LENGTH(node.title) > 1 ORDER BY IFNULL(field_data_field_priority.field_priority_value, 0) DESC LIMIT 5;

However, I've been going bananas trying to figure out the exact forward or reverse relationships needed to produce the same results using the Drupal view UI. The "Priority" field remains stubbornly blank no matter what combinations I try! What am I doing wrong?

You can implement custom relationship using hook_views_data_alter() and define exactly in this hook which fields to use for JOIN - https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7

Example:

/**
 * Implements hook_views_data_alter().
 */
function custom_log_views_data_alter(&$data) {
  // Expose uid as a relationship to users.
  $data['custom_log']['uid'] = array(
    'title' => t('User information.'),
    'help' => t('Information related to user who triggered the event.'),
    'relationship' => array(
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('User information.'),
    ),
  );
}


Can not login with HybridAuth I installed Drupal HybridAuth module on my site for social authentication. I configured this module and it is displaying fine on site block. But when I try to login with any Social Media account details, it is processing correctly, but I cannot login in my site. How can I solve this?
Here's a link to the site:
example.com

A couple of things I would check.

Make sure you're using the correct redirect URIs and JavaScript Origins. For example, the redirect URI should be https://www.example.com/coupon/hybridauth/endpoint?hauth.done=Google and the app you've registered at Google contain this too. The JavaScript Origins at Google should contain www.example.com (and example.com if you allow that too).
Since you're running the site in a subdir, make sure you've set RewriteBase in .htaccess to /coupon/. That might cause a problem with redirecting after auth.


D8 Search api - taxonomy pages Is there way to replace /taxonomy/term/% on search api views?

I was trying create new indexed views with Content datasource: Categories » Taxonomy term » Term ID but when i visit page, it's always return 404.

Please, any suggestions.

One way to facilitate this is to use Taxonomy Views Integrator. You will be able to create views and set vocabulary or terms to use those views instead of the default taxonomy page from core Drupal.


Set value after unpublishing content I'm using drupal 8 and the scheduler module to automatically unpublish custom content after x days have passed.

While unpublishing a boolean field from the custom content needs to be enabled/disabled.

So far I tried rules module after_a_node_has_been_unpublished_by_scheduler with Condition: Entity has field with Action: Set a data value Unfortunatelly the action does nothing.

What else could I try?

You can create your custom code in a hook_cron, and you can handle your verifications following the date of publication.


drupal bootstrap theme working with superfish I hope this will not be too confusing, apology if it is

My situation:

I used superfish so that I can have a navigation menu with dropdown submenu when the mouse hovering the nav items.
I used bootstrap theme to make the whole site responsive
I use 'main menu' instead of 'navigation' as my navigation menu bar
I customised the menu style by changing 'default.css' in superfish, bootstrap.css and style.css in bootstrap theme.
I have unchecked main menu in appearance tab under the theme setting so that the main menu will not show up twice while I'm using superfish.
I am using drupal 7, superfish-7.x-1.8 and bootstrap-7.x-2.x-dev

When the screen size is reduced, the menu bar disappears and the small button in the corner will show up. When clicking this button, the main menu items should be shown as a drop down menu. My problem is: because I unchecked the main menu, the main menu items will not show up when clicking this small button. But the superfish menu (which is main menu, but set in superfish menu) will be there without changing style for small screen. How can I make the superfish menu items behave the same way as normal main menu + bootstrap?

I really don't know how to explain this more clearly and I am really frustrated by bootstrap theme now :(

Any help would be very much appreciated!

thx

Superfish allows you to add custom css classes to the menu items. If you prefer to do it that way

you might want to first select the classes from bootstrap that you want to use to style your superfish menu items. Second add those classes correspondingly in the superfish menu block settings(click configure next to the block).

I also added a html wrapper under advanced HTML settings around the main UL element which is simply , (comma denotes the beginning and ending wrapping elements).

Let me know if that helps!


Display node data in a blank page Is it possible to display a set of nodes and display it on a blank page without the default template around it? This node data is meant for printing and I want it to display on the screen as it would appear on a printout.

Sounds like you should look at the Printer, email and PDF versions module. It is designed to create alternate versions of your pages for print and documentation purposes. It allows you to specify different template files for the output, and you can customize it any way you wish.


How can i show only content type fields in block or how can i call a add content type page in a block How can i call a add node "content type" in a block.
I have upload an image below Image1.

I have a content type : Upload Resume ie upload_resume

Anomynous users can also only create this content type.

I want this fields in a block where user can upload resume not in page style bcos of below image shows other factors ie Image2

Updated Image after Oscar answer

here is your module: Form Block. And here is a quote about it from the module's project page):

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.


Custom Top Admin Menu: Intergrating Permissions Looking into build a top bar to be used for clients for quick access to edit/add pages. Big question I have is, how do you hook this into the Permissions module in core? Say if I want to allow another user to log in and assign this due to certain permissions.

Is this easily done? Or something a bit much?

function mymodule_preprocess_html(&$vars) {
  if (user_access('moderator')) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css');
    $my_links = array();
    if (in_array('manager', $vars['user']->roles)) {
      $my_links[] = array(
        'title' => t('Add new page'),
        'path' => '/location',
      )
      $my_links[] = array(
        'title' => t('Edit pages'),
        'path' => '/location',
      );
    }
  }
}

Seen some things used as below, but having issues...

function mymodule_permission() {
  return array(
    'moderator' => array(
      'title' => t('Use these top links'),
      'description' => t('Blah blah blah.'),
    ),
  );
}

First of all I assume that the Admin Menu module isn't suffient for your needs? If not then I think you're approaching the custom module in the incorrect way.

Basically all menu routes in Drupal (node/add for example) use access arguments to determine who can access the route in question. So if you're looking to build a custom admin bar, I would rather create a new custom Drupal menu, and then add all my links in there. Then if a user does not have sufficient access rights to a menu route, Drupal will not display that specific link within the menu to the user.

If your menu links are coming from a custom module that you've written, you could apply the following example to include your module's menu items into your custom menu. You would use this within your hook_menu declarations:

$items['my/custom/route'] = array(
  'title' => 'Custom module section',
  'page callback' => 'mymodule_custom_page',
  'access callback' => 'mymodule_custom_access',
  'weight' => 0,
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'my-custom-menu-id'
);

Using a custom menu instead of using your $my_links[] array you included above, will allow greater control over each menu item within the Drupal UI too.

*EDIT: provided further explanation based on comments*

Regarding your comments I still think your approach of implementing access controls within hook_preprocess_html is not the best way. We should always be looking to separate our application logic from our frontend logic, and using that hook to apply access control goes against that best practise.

I still recommend that you create a custom menu and then add your admin links and restructure as you want it to be. Then set which roles can create each content type within your system from here /admin/people/permissions, and Drupal will automatically exclude the link for content types the logged in user doesn't have access to.

With regards to displaying the menu, you can just assign the menu's block to a region within your theme, and use CSS to apply styling and positioning within the browser. You can also adjust the access permissions for the block, so only certain roles will ever see your custom menu. You can do this by editing the Visibility settings for menu's block.

Wow I didn't expect this to be such a long winded answer haha! :)


How to migrate multiple columns to single field in CSV Migrate In my CSV file, I am having columns by name summary_1,summary_2 and summary_3. I want all of it migrated to a field in Drupal field_summary. The field supports multiple values.

id: sections_tfr
migration_tags:
  - CSV
migration_group: tfr
label: 'Import sections'
source:
  plugin: csv
  path: /var/www/html/php/tfr/prepared/final/sections.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - s_id
  column_names:
    -
      s_id: Id
    -
      part_no: Part
    -
      sections: Section
    -
      summary_1: Summary
    -
      summary_2: Summary
    -
      summary_3: Summary

process:
  name: sections
  description: heading
  field_summary: summary_1
  field_summary: summary_2
  field_summary: summary_3
  weight: s_id
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: sections
  migration_dependencies: null

It took a while for me to solve the issue. However, I was able to manage the same without having to write additional plugin or module. I solved the issues in two steps:

First used the plugin concat to concatinate all 3 required fields to one.
Then used the plugin explode to pass the value to the same field.

Yaml Below:

id: sections_tfr
migration_tags:
  - CSV
migration_group: tfr
label: 'Import sections'
source:
  plugin: csv
  path: /var/www/html/php/tfr/prepared/final/sections.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - s_id
  column_names:
    -
      s_id: Id
    -
      part_no: Part
    -
      sections: Section
    -
      summary_1: Summary
    -
      summary_2: Summary
    -
      summary_3: Summary

process:
  name: sections
  description: heading
  field_summary:
    -
      plugin: concat
      source:
        - summary_1
        - summary_2
        - summary_3
      delimiter: ','
    -
      plugin: explode
      limit: 100
      delimiter: ','
  weight: s_id
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: sections
  migration_dependencies: null
migration_dependencies: null


Drupal 7 list all the nodes that match a specific tag is it possible to pass a specific url to Drupal7 that lists all the nodes that has a specific tag? i'm searching for something similar to "?tag=" used by wordpress.

I've already created tags and added the tag field to my nodes

Thanks

Tags are terms of a taxonomy vocabulary. Each term has its own page listing all the nodes for the term at taxonomy/term/<tid> where <tid> is the numaric term identifier. The Pathauto module allow automatic creations of cleaner aliases for these pages using patterns like <vocabulary-name>/<term-name>. So instead of being at taxonomy/term/42 the page for the "Foo Bar" tag will be at tags/foo-bar.


grouped paragraphs by field not filtering to current language I have a D8.9 multilingual site. I need to group paragraph elements, as well as filter them by page language and Content ID. But my language filter don't seem to work.
I have content type "services."
"services" contains a paragraph field, "components" with 3 fields inside.
One of the fields in "components" is a taxonomy reference "types" -  this is what I need to group the paragraphs by (sometimes)
I've created a View of 'Services', placed as a block on any "services" page.
The view has a contextual filter of Content:ID, pulled from URL.
It also has a relationship "field_components: Paragraph" so that I can access the specific paragraph fields.
It also has a filter "Content: Translation language (= Content language selected for page)" - because we have 5 translations of the site. (and translation is set within paragraph fields - not on larger paragraph field within "services" content type)
But when I view the service page, it pulls every single translated version paragraph - despite the translation filter.
Let me know if there are further details needed, and I'll edit the question accordingly.

Might've just found the answer to my own question.. there are TWO places that the language needed to be edited. At bottom of the center column in Views admin, there's another language option for the view itself. I had to set this "Rendering Language" to "Content language selected for page"
Then the other language paragraphs disappeared.


Display a taxonomy term every number of rows I have a view with Infinite Scroll Pager giving me the latest products of the website.

Every taxonomy term has an image attatched on it.

I want to display taxonomy terms every 3 rows of products.

I think you must alter the view.

Create the views normally, add taxo to every rows.
Use the Hook hook_views_pre_render(&$view)
Delete the term for every rows except 1/3.

For example something like this:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_myviewname') {
    $result = $view->result;
    $count = 0;
    foreach ($result as $i => $row) {
      if(!$count % 3){
        unset($view->result[$i]->field_MYTEXONOMYFIELD[0]);
      }
      $count++;
    }
  }
}

Example from : http://www.drupal8.ovh/en/tutoriels/238/alter-a-view-edit-view-result-programmatically


Create a menu pointing to # Using menu token I have created a menu as shown in figure

I also have sub-menu items for this menu. Whenever the user clicks on this menu, the page is being refreshed (which is the obvious behavior), but I don't want any sort of action on the menu. In simple HTML we can do my simply using href="#", but Drupal is not allowing to set the Path of the menu to #. Is there a way to do it?
I also tried Menu attributes to do it, but I seem to be missing something.

Yes drupal doesn't suppport # in menu_links, You might get some clues here - http://drupal.org/node/325533


Blocks is not showing up I am facing trouble while configuring a block. The block I configure is not showing up onmy website. I am using drupal 7 and the Touch theme. Here are the steps I do:
- in REGION SETTINGS i have selected "Highlighted"
- Visibility settings is:
 - pages (Only the listed pages) [http://example.com/news]
- Content types
 - Show block for specific content types> [Publish A News]
- Roles
 - I have made no changes here
- Users have not been set
Any ideas why the block is not showing up?

You need to specify your node name. for example: you want to display your block on www.yoursitename/news page. Then you need to specify only news in that box. Hope this will work.


Show block in /user/* page, not /user/*/edit From the Drupal 8 administration, I configured a block (block created from a custom module) for display it in /user/* pages.

It works; I see this block in /user/* and /user/*/edit pages.
Now, I want to display my block only from /user/* pages (the view mode), not from /user/*/edit pages (the edit mode).

Can I do that from the Drupal Administration page? I tested it adding "!/user/*/edit" but this has no effect.

If I can't, how can I do that from my custom module?

If you use this module then the exclamation prefix would work to exclude paths: https://www.drupal.org/project/block_exclude_pages


How can I upload multiple images all at once? Is there a way to upload multiple images all at the same time in Drupal 7?

See the Plupload integration module. From the project page:

  Provides integration between for the Plupload widget to upload
  multiple files and Drupal. Plupload is a GPL licensed multiple file
  uploading tool that can present widgets in Flash, Gears, HTML 5,
  Silverlight, BrowserPlus, and HTML4 depending on the capabilities of
  the client computer.


Fill Blocks from Ctools Page Manager I am using Panels 3 and Ctools to structure my pages and pass arguments both via context as well as inputs on pane settings (fixed text as well as keyword substitutions).  The "input on pane settings" is very important to me.

I need to fill some block regions from the theme, and if possible I would like to do this via the page manager in order to keep selections and variants in one place.

I am aware of mini-panels and that they can be placed in blocks.  But they would require to replicate all selection and context logic from the ctools page manager.

Panels Everywhere seems to go quite deep and I cannot predict whether it will actually allow me to modify the existing non-PE theme within a reasonable time.

Alternatively, I was thinking of modifying the theme's CSS and adding css-classes in page manager or to use javascript to replace the blocks with regular panes.  Unfortunately, this would require separate variants per theme.

Are there any suggested ways to fill blocks from the page manager?  I am using D6, but suggestions for D7 are good as well.

Clarification:
I am looking for ways for filling a themes' block regions (eg. sidebars, headers etc.) from the page manager, in contrast to eg. mini-panels added and configured on the blocks screen.  I am now trying to backport bricks, but ideally the block content should be defined within page manager.

If you are using Panels and Page Manager successfully (they share a common interface for many capabilities) you are well on your way to getting this together. Your question does not indicate if you are using views.  Adding its functionality to your setup in conjunction with Panels/Page Manager is important for gaining the control you need.

First, enable View Content Panes module in the Ctools Suite.  Content panes work similarly to blocks, but are 'smarter' and handle context information passed from Panels/Page Manager.  To define a content pane in views, select the add button in views and the content pane option will be available.  You define a content pane similarly to a views block (you can learn more by viewing 'Taming the Beast'). Once defined, your content panes will show up in Panels/Panel/variant/content/add-content menu just as blocks and other content types do already.

Mini Panels are also similar to blocks plus they accept contexts from Panels/Page Manager and they have the ability to subdivide the content of a block in a specific layout. LIke panel pages, they have access to a large variety opf content types including views and view content panes. They show up in admin/structure blocks for theme layouts and in a Panels/Page-Manager variant's content tab.  If you don't need the additional layout control, you should be able to accomplish what you need using the content panes from views.

Panels Everywhere provides a vehicle for taking control of the entire display layout, not just the content area.  I works the same as Panels for content control so really will not add anything new for your issue here.

For more on panels and mini-panels see this answer.


How to load content in a div with ajax? After validate with javascript that I'll be able to use the client location:

if (navigator.geolocation) {
...

I need to load the content of a view block with arguments (based in the position coords). I know how to obtain the HTML that I want to put inside the div, so at least I have this part.

I tried to follow the Simple Drupal AJAX load with jQuery and delivery callback article (that is write for Drupal 7 very different from Drupal 8) but I just arrived to load a page in a div (with headers and footer very far from my real objetive).

jQuery('#my-div').load('/admin/help');

Any ideas on how to load content in a div with ajax?

I've come up with a working solution. It might not be the best approach but it works.

You need to create your routing file:

my_module.routing.yml

diocese_core.path_with_data:
  path: 'path-with-data'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::Render'
  requirements:
    _access: 'TRUE'

Creating the controller for your page

src/Controller/MyController.php

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use \Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class MyController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function Render() {
    $build = array(
      '#type' => 'markup',
      '#markup' => t('Hello World!'),
    );
    // This is the important part, because will render only the TWIG template.
    return new Response(render($build));
  }

}

And you only need to call in javascript

jQuery('#my-div').load('path-with-data');

An this will be the output once the code is executed:

Hello World!

References:

Drupal 8 module - How to use AJAX?
Drupal8:Basic Jquery Ajax custom module controller


Database schema of comments I would like to clarify the database table relationship between comment & field_data_comment_body.

Questions are:

Is comment's body saved in field_data_comment_body table?
Is comment's cid = comment_body's entity_id ?
Is there any table other than these 2 contributed to comments?

Yes.
Combined with 'entity_type' = 'comment', yes. An entity (comment, node, term, user, ..) is always identified by their entity_type and entity_id.
Not directly, in this case. There is also field_revision_comment_body table, which is in this case not used because comments don't support revisions (but field always needs to create one because nothing stops you from adding that field to a node and create revisions of it). There are also the field_config and field_instance_config tables which contain information about which field is attached to which entity type/bundle.


Fill field value automatically So let's say I have a content type Product with two fields: name and date. I want to have another field called profit to be filled in automatically according to the name of the product.
Any ideas on how I can do that easily?

I suggest you to give to the Computed Field module a try. It seems that it does exactly what you need.

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!


Upload an image to filesystem, rename it and set it as Profile Picture for current user I have the external link of an image where I am trying to:

Upload the image to filesystem.
Rename the image.
Set the owner of the image to current user.
Set the image as Profile Picture for current user.

So far I have:

$full_name = "John Smith";
$picture_url = "https://scontent.fbey14-1.fna.fbcdn.net/v/t31.0-8/14054356_124897527960923_50194821455451882_o.jpg?_nc_cat=106&_nc_sid=09cbfe&_nc_ohc=P4i5oscJf0IAX_KFCfR&_nc_ht=scontent.fbey14-1.fna&oh=c13b6b2d8712db359f3be5e1ec835340&oe=5EF2B1A4";

// Download the picture to local filesystem.
$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

// Get the Profile Pic ID.
$profile_pic_id = $profile_pic->id();

// Load the image.
$picture = \Drupal\file\Entity\File::load($profile_pic_id);

// Rename the image.
$picture->setFilename("$full_name.jpg");
// Set the owner of the profile picture file.
$picture->setOwner($current_user);

// Save the image.
$picture->save();

$current_user->set('user_picture', $profile_pic_id);
$current_user->save();

The image is indeed uploaded to filesystem under public://profile-pictures, also is successfully set as profile picture of the current user.

and the filename of the image at /user/*/edit edit page is set to: john-smith.jpg, however, the filename of the image at public://profile-pictures is 14054356_124897527960923_50194821455451882_o.jpg while I am expecting it to be john-smith.png !

How to rename the image at the filesystem ?

and does $picture->setOwner($current_user) will set the owner of the image to the current user ?

I agree with @Clive you can do it that why, and also you can download the image directly with the full_name.
To do so just change the line:

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

by

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures/$full_name.jpg", TRUE, FILE_EXISTS_REPLACE);

and remove the line:

$picture->setFilename("$full_name.jpg");


textfield with #disabled = true, #input = false A textfield with #disabled = TRUE will appear greyed out, and be unchangeable.

A textfield with #input = FALSE will not send its value to $form_state['values'], and will be ignored by system_settings_form_submit().

Unfortunately, a textfield with #disabled = TRUE and #input = FALSE no longer appears greyed out.

I want to make a textfield that is purely for display purposes, so a person can copy a value from there. What is the best way to do this?

EDIT I: What I tried so far

To clarify, my starting point is code like this:

$form['thetext'] = [
  '#type' => 'textfield',
  '#title' => t('The text'),
  '#disabled' => true,  // This should make it greyed out - but it doesn't due to #input = false below.
  '#input' => false,  // This should make this field ignored in $form_state['values'].
  '#value' => 'xyz',  // Either #value or #default_value.
];

EDIT II:

If this wasn't clear before: I really want the html output to be a textfield element. I also want to use the regular form + theme API, so that the element gets a label and wrapper div and theming like other form elements in the same form. E.g. if I would just hardcode the textfield html, it would no longer have the same classes, wrappers etc.

Use a markup element instead.

$form['element'] = array(
    '#type' => 'markup',
    '#markup' => 'This is the thing you want people to see. You can use html, too.',
);

You don't actually have to specify #type => 'markup' because drupal defaults to that type if you don't specify, but I do anyway as it seems to be good practice.


How can my JavaScript-function access the Web Property ID from the Google Analytics module? I use the GoogleAnalytics module in most of my projects and have often the same issue:

Due to my countries policy requirements, every user has to be able to deactivate google-analytics cookies. To do so I need a little JavaScript to disable the cookie wich contains the UA/property ID, which is provided by the module.

Normaly such configs are set in the drupal-settings-json at the end of the page but there is no property-id in sight.

<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","current....

is there any way for my JS-function to access this infirmation, or do I need to write an extra function to read the property ID and parse it to the drupal-settings-json somehow?

The most popular Google Analytics module (google_analytics) relies on generating inline JavaScript snippets for initializing tracking, which can make altering its behaviour difficult - likely requiring patching the module.

Googalytics is a more flexible alternative for Google Analytics in Drupal 8

drupalSettings is used to pass data to the front end.  This removes the use of inline JS, also making  the module compitible with Content Security Policy.
The data structure isn't intended to be modified on the front-end by JS, but hopefully the improved control possible in the back-end makes it unnecessary.
There's an open issue (with a patch currently needing feedback) for integrating  with the EU Cookie Compliance module.  If this matches your use case you may not need to write any custom code, otherwise it may provide a template for how to override the module's JS library for your needs.


oderid sort not work correclty in number more than 1000 in commerce_orders views I look at the commerce_orders views, and I see some strange there, when I set sort record according by orderID it not work correctly for number more than 1000 ,it seems that only 3 first digit consider in sort, Is this a bug in views?
appreciate any help

and query is :

SELECT commerce_order.order_number AS commerce_order_order_number, commerce_order.order_id AS order_id, commerce_order.uid AS commerce_order_uid, commerce_order.created AS commerce_order_created, commerce_customer_profile_field_data_commerce_customer_billing.profile_id AS commerce_customer_profile_field_data_commerce_customer_billi, users_commerce_order.name AS users_commerce_order_name, users_commerce_order.uid AS users_commerce_order_uid, commerce_order.status AS commerce_order_status, 'commerce_customer_profile' AS field_data_commerce_customer_address_commerce_customer_profi, 'commerce_order' AS field_data_commerce_order_total_commerce_order_entity_type
FROM
{commerce_order} commerce_order
LEFT JOIN {users} users_commerce_order ON commerce_order.uid = users_commerce_order.uid
LEFT JOIN {field_data_commerce_customer_billing} field_data_commerce_customer_billing ON commerce_order.order_id = field_data_commerce_customer_billing.entity_id AND (field_data_commerce_customer_billing.entity_type = 'commerce_order' AND field_data_commerce_customer_billing.deleted = '0')
LEFT JOIN {commerce_customer_profile} commerce_customer_profile_field_data_commerce_customer_billing ON field_data_commerce_customer_billing.commerce_customer_billing_profile_id = commerce_customer_profile_field_data_commerce_customer_billing.profile_id
WHERE (( (commerce_order.status NOT IN  ('cart', 'checkout_checkout', 'checkout_shipping', 'checkout_review', 'checkout_payment', 'checkout_complete')) ))
ORDER BY commerce_order_order_number DESC
LIMIT 50 OFFSET 0

As you can see in commerce_order_schema, order number is not a number, it's a string:

'order_number' => array(
    'description' => 'The order number displayed to the customer.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ),

This means that your view works as designed, sorting this text field that accidentally contains numbers alphabetically. Which, again accidentally, gave you illusion of numeric sort when numbers was in [100-999] range.

If you need something that's guaranteed to be numeric and ordered the way orders was placed, use either order_id ('type' => 'serial') or created ('type' => 'int').


Customize a View 3 SQL query I've created a view that lists the content based on the first letter of that title matching an argument passed to the page. Now I'm trying to do the same, but with a 0-9 so when the user selects 0-9 the view gets all content types which begin with a number in the range 0-9.

I'm currently looking at hook_views_query_alter(), but I don't get back the results I am expecting. The function I've written is the following one:

function module_views_query_alter(&$view, &$query) {
  if ($view->name == 'custom_page' && $view->current_display == 'page_1') {
    if ($view->args[0] == '0-9') {
      $query->where[0]['conditions'][2]['field'] = 'SUBSTRING(node.title, 1, 1)';
      $query->where[0]['conditions'][2]['value'] = array('0','1','2','3','4','5','6','7','8','9');
      $query->where[0]['conditions'][2]['operator'] = 'in';
    }
  }
}

This is a bit of a cheat following the code that's used by the glossary view, but it works:

function module_views_query_alter(&$view, &$query) {
  if ($view->name == 'custom_page' && $view->current_display == 'page_1') {
    if ($view->args[0] == '0-9') {
      $query->where[0]['conditions'][2]['field'] =  "SUBSTRING(node.title, 1, :node_title) in ('0','1','2','3','4','5','6','7','8','9')";
      $query->where[0]['conditions'][2]['value'] = array(':node_title' => 1);
      $query->where[0]['conditions'][2]['operator'] = 'formula';
    }


Why doesn't my custom entity work in an entity reference field? I've got a custom entity with bundles that I want to be able to use in an entity reference field in a different entity.  So, I've got an the content entity for my entity type:

/**
 * Defines the Redacted teaser entity.
 *
 * @ingroup redacted
 *
 * @ContentEntityType(
 *   id = "redacted_teaser",
 *   label = @Translation("Redacted teaser"),
 *   bundle_entity_type = "redacted_teaser_bundle",
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\redacted\RedactedTeaserListBuilder",
 *     "views_data" = "Drupal\redacted\Entity\RedactedTeaserViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "add" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "edit" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "delete" = "Drupal\redacted\Entity\Form\RedactedTeaserDeleteForm",
 *     },
 *     "access" = "Drupal\redacted\RedactedTeaserAccessControlHandler",
 *     "translation" = "Drupal\node\NodeTranslationHandler",
 *   },
 *   base_table = "redacted_teaser",
 *   admin_permission = "administer RedactedTeaser entity",
 *   translatable = FALSE,
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "bundle" = "type",
 *     "langcode" = "langcode",
 *     "user_id" = "user_id",
 *     "created" = "created",
 *     "changed" = "changed",
 *   },
 *   links = {
 *     "canonical" = "/admin/redacted_teaser/{redacted_teaser}",
 *     "edit-form" = "/admin/redacted_teaser/{redacted_teaser}/edit",
 *     "delete-form" = "/admin/redacted_teaser/{redacted_teaser}/delete"
 *   },
 *   field_ui_base_route = "entity.redacted_teaser_bundle.edit_form",
 * )
 */

And the config entity for my bundles:

/**
 * Defines the Redacted teaser bundle entity.
 *
 * @ConfigEntityType(
 *   id = "redacted_teaser_bundle",
 *   label = @Translation("Redacted teaser bundle"),
 *   bundle_of = "redacted_teaser",
 *   handlers = {
 *     "list_builder" = "Drupal\redacted\RedactedTeaserBundleListBuilder",
 *     "form" = {
 *       "add" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "edit" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "delete" = "Drupal\redacted\Form\RedactedTeaserBundleDeleteForm",
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm"
 *     }
 *   },
 *   config_prefix = "redacted_teaser_bundle",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}",
 *     "edit-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/edit",
 *     "delete-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/delete",
 *     "collection" = "/admin/structure/visibility_group"
 *   }
 * )
 */

I then try to use that in an entity reference field in another entity:

->setSetting('target_type', 'redacted_teaser')

But when I go to create an instance of this entity, the reference field isn't getting any of my bundle instances.

I've also try adding an entity reference field to a content type in the UI.  The field settings recognize my defined bundles when I'm setting up the field, but when I go to create a node of that content type the entity reference field doesn't pick up any of my bundles instances there, either.  I've compared my annotations to those in Node and NodeType and don't see that I'm missing anything.  I've also stepped through with Xdebug, and I can see that when my create form loads, it's getting "redacted_teaser" as the expected type for the reference field.

Everything else about my entity and bundles works just as expected.

You have no label key, so autocomplete doesn't know what to search for.


During database updates the schema of any module could be out of date I try to well understand Update versions API functions.
I globally understand the concept, but I have some doubt.

In fact Drupal makes no verification about the N version number use in the name of a simplified function _update_N_mymodule_my_function(). N can be what ever we want (even a string) ?
More, even the whole name of function can be named in fact e.g "toto()" ? Drupal makes no verification, and names used for functions simplified are just for convenience. Correct ?

No, that is not correct. You cannot use a string as update version for a update hook, or Drupal will not recognize it as update hook.
For the other functions that aren't hook, Drupal doesn't check their name follow a schema, since Drupal is not going to call them. The only non-hook functions Drupal calls are those functions referred in some data structure returned to Drupal, or those functions whose names match a form ID followed by _validate or _submit, which could be used as form validation or submission handlers.

See the code executed from drupal_get_schema_versions(), in particular the following one.

// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

A function name like mymodule_update_toto() would not match /_\d+$/, so it would be discarded immediately; a function name like mymodule_test_001() would not match /^(?P<module>.+)_update_(?P<version>\d+)$/, so it would be discarded on the second round.
The same is true for a function name like _update_N_mymodule_my_function(): Since it doesn't end with a number, it would be discarded at the first round. _update_mymodule_my_function_N() would be discarded on the second round, since _update_ is no after the module name (so it doesn't match /^(?P<module>.+)_update_(?P<version>\d+)$/).


How hide from menu content type Basic Page and Landing page In Drupal 8,  I tried to remove default Basic page and Landing page content types, but it have content related to them. So, my quick fix will to only hide those one from some user. I tried with permissions but it didn't work .

/admin/people/permissions

Updated: Same issue

But users with role Content Publisher and/or Content Administrator still see those CTs in /node/add

There is any other way to hide those ones?

Thanks

Edit:
This option was the issue Create any content on assigned domains

SOLUTION:
I just removed for Content publisher or any other role

Create any content on assigned domains

I think this permission was added with the module Domain Access


How should jcarousel be installed and configured? To achieve a slider with 5 slides in sight and sliding 1 at a time, I thought https://www.drupal.org/project/views_slideshow_jcarousel would be a good choice. Also, because I already use views_slideshow.
However the installation instructions are a bit confusing. They seem to relate to Drupal 7 and/or combined with Drupal 8.

At first I installed through Composer and activated the module in Drupals' User Interface. This did not work.
Then I downloaded the zip and tried to place files in different locations. Because it is not clear to me where I should place files, this also failed.

Anybody knows how I could get this to work?

Update: as was noticed by Stefan, the dist folder should be in an other location than the docs (sites/all/libraries/jcarousel/dist) indicate. I moved the contents of the dist folder to that new location (/libraries/jcarousel/lib), this didn't make it work yet. I can see the carousel options in the view that I made, but it doesn't function yet.

I'm setting the view > slideshow settings > widgets > pager type to jcarousel pager. At that point there's a select list for skin without options to choose from. The output of the slider is an unformatted list with the slider below that.
Perhaps I'm still doing something wrong?

From looking at the code you need to put the jcarousel library here:

/libraries/jcarousel/lib/jquery.jcarousel.min.js

This means install the module as usual and then put the library like given above in the folder libraries

But it seems that there is truly a flaw in setup instructions: The module page states like this:

  Download and extract the jCarousel library to libraries folder of
  drupal root. The source code can be found here:

  https://github.com/jsor/jcarousel/releases

  the folder name you create for this will need to be "jcarousel". the
  full path should be: libraries/jcarousel

  and when you are done, the following path will need to be available:
  sites/all/libraries/jcarousel/dist

This is a mixup of D7 and D8 as TO already stated and in addition if you do it like so, the path given in views_slideshow_jcarousel.libraries.yml will not be available.

I created an issue to maybe get this fixed: https://www.drupal.org/project/views_slideshow_jcarousel/issues/3084864


Query to include if condition in addField How can I include an if condition to my drupal 7 query. This is my query.

$query = "SELECT N_en.nid AS en_nid,
  IF(N_lan.translate = 1, 'Outdated', 'New') as lan_translated,
  FROM node N_en
  LEFT JOIN node N_lan ON N_lan.tnid = N_en.nid "

I tried

$query = db_select('node', 'N_en')->extend('PagerDefault');
    $query->addField('N_en', 'nid', 'en_nid');
    $query->addField('N_lan', 'translate', 'lan_translated');
    $query->leftJoin('node', 'N_lan', 'N_en.nid=N_lan.tnid AND N_lan.language=:lang', array(':lang' => $userLan));

How can I give my if condition for N_lan.translate?

You can add an expression:

...
$query->addExpression("IF(N_lan.translate = 1, 'Outdated', 'New')", 'lan_translated');
....


Get nodes of specified content type with REST I want to retrieve all nodes of specified content type (as example'news') with GET method with REST,
How can I achieve it?
(first I want try it with firefox RESTClient and if it work implement it in my application)

The only way that core offers is building a view with a REST display. That is, in fact, the only way in core to have collections (a list of resources) for rest.

See https://www.drupal.org/project/graphql for another approach, that allows to execute a sort of query through services.


How to theme Panels properly? I am using Page Manager and Panels, providing custom node panels with selection rules by type (e.g. one panel variant for article-, one panel variant for blog-content type). This works smooth so far, styling is also neat. But, how can I get more power over the rendering of elements?

There are multiple ways to render specific elements: adding fields, using token, using a custom view only rendering specific fields, using rendered node entity with view mode. using custom panel content with placeholders etc.

What is the best approach here? It would be great to have the ability to add a custom (something) pane element that can be styled in a *.tpl.php.

My current approach would be using display suite, creating view modes for different parts / panel regions and using theme hook suggestions for adding custom node.tpl.php for each view mode. It would not need to invoke views, which is pretty much a overkill?! rendering, additional queries...) and can use already cached entities.

function mytheme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_left') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_left';
  }

  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'panel_region_right') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__panel_region_right';
  }
}

I am not sure how well this will be cached and how much resources it will consume. Any advice would be grateful.

As the official doc says you can do something like

  panels-pane_node-title.tpl.php

  panels-pane_panel_node_title.tpl.php

  panels-pane-node-title.tpl.php

  panels-pane-node_title.tpl.php

After some search i have found that the suggestions are not detecting by panels, and i end up in this preprocess function.

function MYTHEME_preprocess_panels_pane(&$vars) {
// get the subtype
$subtype = $vars['pane']->subtype;

// Add the subtype to the panel theme suggestions list
$vars['theme_hook_suggestions'][] = 'panels_pane__'.$subtype;

return $vars;
}

After a long search in forums i found this too,

<?php
function THEMENAME_preprocess_page(&$vars) {
    global $theme_path;
    if($panel_page = page_manager_get_current_page()){

        $target_menu = 'menu-sixth-form-college';
        $current_path = menu_get_item();

        $target_menu_links = menu_load_links($target_menu);
        foreach($target_menu_links as $links) {
            $link_paths[] = $links['link_path'];
        }
        $preferred_link_paths = $link_paths;
        // if the current link is inside menu_load_link
        if(in_array($current_path['href'], $preferred_link_paths)) {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
        if($panel_page['name'] == 'page-sixth_form_college') {
            $vars['theme_hook_suggestions'][] = 'page__sixthform';
        }
    }
?>

Theme and Cache.

When it comes to caching, i believe Drupal will handle template caching for you as normal page cache. If your dont think it work you can do something like

<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>


How to alter the value used to sort a view? I have properties that have a rental price. The rental price is a field collection with a value (price) and period (per month, per week). You can sort the properties by price (low to high, or high to low) using an exposed filter. The problem is that if someone enters 2000 per month it is being registered as more expensive than a property that is 600 per week (2400 per month). So I want to divide the monthly values by 4 in order to have equal calculation.

What hook do I need to use in order to process the value field just before it is used to sort the properties?

you can change query of view by this
hook_views_query_alter(&$view, &$query)

This hook is a core hook of views api but you can override it in you custom moduel like MYMODULENAME_views_query_alter

In this hook you can get parameters by exposed filter's and change views query based on these parameters.


How can I avoid the installation directory appears in the site URLs? I installed Drupal 7 through the hosting service tools, which installed Drupal inside the drupal1 folder. All the site URLs contain the folder name.

How can I avoid the URLs contain that folder name? For example, instead of http://example.org/drupal1/about-us, the page should be available as http://example.org/about-us.

I've been able to only set the default front page alias to the root.

Set server DocumentRoot to Drupal folder

As mentioned by @leymannx you have to configure your server virtual host to use the drupal1 as the DocumentRoot.

<VirtualHost *:80>
    ...
    DocumentRoot /path/to/drupal1/

    <Directory /path/to/drupal1>
      AllowOverride All
    </Directory>
    ...
</VirtualHost>

RewriteBase on a shared host (in Drupal .htaccess)

If you're on a shared host you won't have access to change DocumentRoot. Instead, you can adjust RewriteBase in Drupal .htaccess file (or $base_url in settings.php).

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
RewriteBase /drupal1


Extracting a specific data part of a Field Collection Item I've been playing around with this for the better part of a few days now with no luck. Here is my Collection data:

Collection name: field_video_collection

Within the collection there is a field called: field_video_file_col

My fields print fine in my custom field-collection-item--field_video_collection.tpl.php template, I followed the documentation according to this issue to get my template name and I simply print the fields as <?php print render($content['field_video_file_col']); ?> etc... within that template.

Now for the fun part, I'd like to extract the fid for each field_video_file_col item in the collection in any given node and render it as a printed variable. I followed the answer in this question here on Stack but it does not seem to work for me. if I do:

print '<pre>';
var_dump(get_defined_vars());
print '</pre>';

I see I have this as part of the data available to me for field_video_file_col

["field_video_file_col"]=>
          array(1) {
            ["und"]=>
            array(1) {
              [0]=>
              array(12) {
                ["fid"]=>
                string(3) "888"

So it looks to me that the FID is 888 in this case and I want to render that in my template. My node preprocess function is as such:

function MYTHEME_preprocess_node(&$vars, $hook) {

    $entity_type = 'field_collection_item';
    $bundle_name = 'field_field_video_collection'; // Field name the collection is attached to
    $field_name = 'field_video_file_col'; // Field name within the field collection
    $video_file_fid = field_info_instance($entity_type, $field_name, $bundle_name);
    if ($video_file_fid) {
      $my_fid = $video_file_fid['fid'];
    }
}

The end result needed is that I need to render the variable in my field-collection-item--field_video_collection.tpl.php template as:

<?php print $video_file_fid; ?>

... but this does not seem to work.  I've searched all over and tried many different incarnations of this code and combinations but still no joy.

I use Entity API when work with Field Collection Items. See: Programmatically create and update field collection with Entity API

To work with field collections can do smth like this:

// Wrap node with Entity API
$node_wrapper = entity_metadata_wrapper('node', $node);
// Get the first item from the muli-value field collection
$raw_collection = $node_wrapper->field_video_collection[0]->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
debug($collection->field_video_file_col->value());

If you already know your field_collection id you can just do:

$collection = entity_metadata_wrapper('field_collection_item', $fid);
//dsm the old value
debug($collection->field_video_file_col->value());

UPDATE:

use the code above in MYTHEME_preprocess_node

UPDATE 2:

So in your case it will be:

function MYTHEME_preprocess_node(&$vars, $hook) {
  if (empty($vars['nid'])) {
    return;
  }
  // Wrap node with Entity API
  $node_wrapper = entity_metadata_wrapper('node', $vars['nid']);
  // Get the first item from the muli-value field collection
  $raw_collection = $node_wrapper->field_video_collection[0]->value();
  // Wrap field collection with Entity API
  $collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
  // print value
  $fid = $collection->field_video_file_col->value();
  debug($fid);
}

Also you can find answer at Understanding Field Collection Values


Do I have to use Views to use all the behaviors of OpenLayers maps module? I just started using the http://drupal.org/project/openlayers module. There are plenty of tutorials to learn about it, but all of them make use of views to show the maps.

I need to show a simple map to show a single the location. I need this map to show a marker and a tooltip with some information (address, phone,...)

I tried showing a map in a node by adding the geofield field to a content type and then setting the OpenLayers Map Widget in manage display.

The map is shown up fine but as far as I see there no way to add a popup to the map.

Then my question is: Do I need to show the maps through a view to get all the behaviors provided by the module?

The learning curve is a little steep when first working with openlayers if you really want to use it you can create your map and add a geoJSON layer to it and just write the geoJSON code in the textarea provided to create the point and popup info. Checkout openlayers plus module for more behavior options.


How to put two form elements in a row using Drupal Form API? I am creating a form in Drupal 6 using form API.

I need to put a textfield and a select next to each other. they are for entering something like 'www.domainname.com' . www. is fixed. domainname section is given from user in a textfield and .com section is chosen from select element by user.

So they should be in a line. but as I see I can put these two form elements in a line, they are in their div container.

Would you help me? Thank you.

This is a CSS issue. All you need to do is limiting the width of both elements and then float them to the left; this will make them inline. Be sure to wrap them both in a div with the "clearfix" class to clear the float.