How to search for string in Drupal database and replace I am wondering what would be the safest way to search through the mysql database for a specific keyword and update.

More specifically here is what I am trying to do.

In many of the nodes we have videos embedded. Unfortunately, we didn't add preload="none" to our videos. Now the pages take a long time to fully load plus they download the whole video without the user clicking on it wasting bandwidth.

I want to search the nodes (mainly the body field) for:
video controls=""
and replace with
video controls="controls" preload="none"

I assume I can use something like this? update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');

Which table should I search?

I don't want to mess up the database so a second opinion is highly appreciated.

You don't say which version of Drupal you are using.  If it's D7, there is the scanner module which can probably do what you want.

If it is D8, I'd suggest writing a drush script to update the content.  The standardization of entities and methods makes that fairly easy. Here's a snippet of code from a script I used to grab all text from our site that needed to be translated.  You can modify it to do what you need.

use \Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;

$entity_type = 'node';
$bundle = 'article;
$fields = [
  'field_header' => 'paragraph',
  'field_summary' => 'text',
];

$entities = gen_i18n_get_entities($entity_type, $bundle);
foreach ( $entities as $vid => $id ) {
  $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id);

  gen_i18n_parse_entity($entity, $fields, $page);
}

/**
 * Find the entity ids for the specified type and bundle.
 *
 * @param string $entity_type
 * @param string $bundle
 * @return array
 */
function gen_i18n_get_entities( $entity_type, $bundle ) {
  $query = \Drupal::entityQuery($entity_type)
    ->condition('type', $bundle);
  if ( $entity_type == 'node' ) {
    $query->condition('status', 1);
  }
  $results = $query->execute();
  return $results;
}
/**
 * Walk thru the entity fields to get required information.
 *
 * @param EntityInterface $entity
 * @param array $fields
 * @param array $page
 */
function gen_i18n_parse_entity( EntityInterface $entity, array $fields, array &$page ) {
  global $field_num;

  $field_num = 0;
  foreach( $fields as $field => $field_type ) {
    if ( !in_array($field_type, array('alias', 'menu'))) {
      $field_def = $entity->getFieldDefinition($field);
      if ( $field_def != NULL ) {
        $label = $field_def->getLabel();
      }
      else {
        print "** Could not find field {$field} in {$entity->bundle()} {$entity->id()}\n";
        continue;
      }
    }
    else {
      $label = $field_type;
    }
    switch ( $field_type ) {
      case 'text':
        gen_i18n_parse_text( $entity, $field, $page, $label);
        break;
      case 'paragraph':
        gen_i18n_parse_paragraph($entity, $field, $page, $label);
        break;
      case 'metatags':
        gen_i18n_parse_metatags( $entity, $field, $page, $label);
        break;
      case 'alias':
        $field_num++;
        $page['en']["{$field_num} - URL"] =  $entity->toURL()->toString();
        break;
      case 'menu':
        gen_i18n_parse_menu($entity, $field, $page);
        break;

    }
  }
}


How to create a rule to send an email to a list of selected email addresses? I have a Content Type Named XYZ. This content Type has a field named Email Addresses, which contains the List of Email address of the users in the Portal.

Now when the user adds the Content of XYZ and selects the desired Email Address from the Email Addresses List, the email should be sent to all the selected Email Addresses.

I know the Rules module should be used to perform this, but guide me the steps, how to make such rule?

Assuming this question is about D7, you can use the Rules module to create a rule like so (in Rules export format):

{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about the above rule:

Rules Event: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
Rules Action: a "loop" for all selected values of a multi value select list (contain the eMail IDs), with machine name field_email_addresses (adapt the machine name to fit your needs). For each item (= current_email_id), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.

After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with drupal_message).

Video tutorial: have a look at the List and loops video which show a similar scenario.


Drupal Commerce custom Coupon Type not discounting I'm trying to create my own coupon type so that I can give it a name that will appear in the checkout and add features such as expiry date and product reference. I have been able to add the features to the "percentage amount" coupon type and if I only had one coupon type I'd just change the display name of that, but there will be many coupon types in my shop. Each is a one-time use coupon that a major client can give to their members so there would be types such as Ford-employee-discount and Toyota-employee-discount with individual coupons trackable to individual staff. So even the coupon code wouldn't be good enough to display because it will be something like "F_Emp-JH6d98"

So now that I have a new coupon type I have duplicated all the fields from percentage coupon type but when I get such a coupon added to a bill the "Granted amount" is blank. No discount is applied but the coupon is there on screen and listed as used by the database.

I'd prefer to be able to add a display name field to the coupon type and set it for each coupon I issue (which are made in batches by the Coupon Batch module), but without modifying the Coupon module I can't see how to display the value of that field in the right places.

You may need to implement

hook_commerce_coupon_granted_amount_alter

to add your granted amount to the display there.

e.g:

/**
 * Implements hook_commerce_coupon_granted_amount_alter
 */
function MYMODULE_commerce_coupon_granted_amount_alter(&$amount, $coupon, $values) {

  if ($coupon->type == 'my_coupon_type') {
    $order = commerce_order_load($values->order_id);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);

    // Do stuff to get amount from coupon...
    // ...
    // ...
    $amount = 1000; // example
    $currency_code = "USD";
    $amount = commerce_currency_format($amount, $currency_code, $coupon);
  }
}


determine which template file a contrib module is using? I'm using a contrib module. It doesn't seem to be using the right template file. I'm trying to triage whether the problem exists in my template or if it is just the hook template suggestion.

What is the cheapest way to debug which template file a particular contrib module is using?

FYI: i'm using the commerce export ftp module. It has it's own template inside the module but i'd like it to use the template file within my theme.

I would like an answer that would be a general debugging practice. Not one specific to this particular module: how do you dump the file path that the contrib module is using? Is the only way of doing so with devel_ui ? I'm looking for a programatic way of doing this.

I thing something like this could tell you what is going on :

$reg = theme_get_registry();
dpm($reg['commerce_order_ftp_export']);


How to add links to sidebar without using a block? does anyone know how to add links or HTML onto the left sidebar of a drupal theme without using a block? I am using drupal 7.14. Any help would be appreciated.

Can be done using the  _phptemplate_variables function in template.php in your theme directory.

function _phptemplate_variables($hook, $vars) {
  if ($hook == 'page') {
    foreach (array('left','right') as $region) {
      $vars[$region] = drupal_get_content($region);
      return $vars;
    }
  }
}

And just call this function below where you want to display the link.

$output = l('some link text','node/1234');
drupal_set_content('left', $output);


Rewrite user edit page url On my Drupal 7 website, I would like a uri like

folder/subfolder/preferences

to be an alias for the user edit page

user/<uid>/edit

for all users.  To be precise, when a user navigates to folder/subfolder/preferences, they should be at their own user/"uid"/edit page with the original folder/subfolder/preferences uri in the navigation bar.  If necessary, I wouldn't mind if the aliase contained the uid, so I'd be ok with folder/subfolder/preferences/"uid".

It seems like the pathauto won't do what I want, I'm experimenting with sub-path auto but so far no luck.  If there's a module that can help me do what I want that would be great, but wouldn't mind to do it through a hook if necessary (I haven't figured out how to do this by hooks either).  Thanks for any help.

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

For breadcrumbs you can use Path Breadcrumbs or Custom breadcrumbs.

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

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

Maybe someone can improve this code to be more transparent.

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


Administer Users permission too vague. How can I restrict functionality for this permission? Is there a way to allow some admin users (with administer role) to create other users but limit their access to 'people' related admin area? It seems there's only one option under permissions - Administer users - which seems to dictate either full package (create all different profile2 users, access admin people list view etc) or nothing.

I have a 'sales person' role on the system. This user has to be able to create other profile2 based users but not to access user configuration or even general listing (not to mention that depending on number of profile2 profiles, multiple Add People links appear)

I believe the Role Delegation module does what you need to do. Here is a quote about it (from the module's project page):

... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions in the Permissions page.
If an administrator has the administer users permission, a role assignment widget gets displayed in the account creation or editing form, and bulk add/remove role operations become available on the user administration page. Otherwise, if s/he has at least the access user profiles permission, the module adds its own Roles tab to the user profile so that roles can be assigned.


How to create username with firstname and lastname using feeds and tamper? On Feeds tamper module page (amazing module btw), it says that the module permits to [...]

Examples:
[...]

  Combine separate 'firstname' and 'lastname' fields into one 'name'
  field.

But I don't find any documentation on how to do this. Any help?

Depending on your source data, you want to use the "Rewrite" plugin of Tamper to combine the fields. More described in: https://drupal.org/node/1973776


Get site name config value in page.html.twig template Is there a way to get the site name config value as a variable in the page.html.twig template? I am only able to get null values when I try to get the value in the preprocess function.

I am only able to get null values when I try to get the value in the preprocess function.

Null values based on doing what exactly?

The site name, logo etc. was moved to a block, that's why it's no longer available out of the box. However, you can always add it back yourself and make it available in twig:

$variables['site_name'] = \Drupal::config('system.site')->get('name');


How do I install a patch file? I was trying to google the method to install a patch file, but the results keep returning as "issues encountered while patching", which isn't what I am looking for.

I was wondering how to use drush to install a patch file?

More specifically, I'm currently encountering a Drupal for Facebook module issue, about the q variable.

One of the answers suggests installing a patch file. How do i install this patch file from the command line?

The instructions on how to apply a patch are given, for that module, on http://drupal.org/project/fb/git-instructions.

First off, git patches can be applied to a git repository you need to locally clone, which means you need to execute the following command:

git clone --recursive --branch master http://git.drupal.org/project/fb.git

Then you copy the patch in the fb directory created from the previous command, and execute the following one:

cd fb
git apply -v fb_stream.admin_.inc_.patch

Once the patch is applied, you delete it.

rm  fb_stream.admin_.inc_.patch

This assume the patch is applied to the development snapshot. If this is not the case, then somebody needs to provide a patch for the development snapshot.

Anyway, the patch doesn't apply. If you try applying it, you will get the following error:

  Checking patch Users/johnrobens/Downloads/fb/fb_stream.admin.inc...
  error: Users/johnrobens/Downloads/fb/fb_stream.admin.inc: No such file or directory

You need to change the patch to the following one, to avoid that error.

--- fb_stream.admin.inc
+++ fb_stream.admin.inc
@@ -1,5 +1,6 @@
 <?php

+
 /**
  * Form callback for general settings.
  */
@@ -19,7 +20,8 @@
             '%user_name' => $from['name'],
             '%token' => $token,
           )));
-    } catch (Exception $e) {
+    }
+    catch (Exception $e) {
       fb_log_exception($e, t('Unable to query graph with fb_stream token.'));
       drupal_set_message(t('There was an error using the current access token, %token.  Consider generating a new token.', array(
             '%token' => $token,
@@ -29,7 +31,7 @@

   if (!empty($_REQUEST['code']) && empty($_POST)) {
     // Send user to this URL after token is generated.
-    $redirect_uri = url(request_path(), array(
+    $redirect_uri = url($_REQUEST['q'], array(
       'absolute' => TRUE,
       'query' => array(
         'client_id' => $_REQUEST['client_id'],
@@ -59,7 +61,7 @@
   );
   foreach (fb_get_all_apps() as $fb_app) {
     // Send user to this URL after token is generated.
-    $redirect_uri = url(request_path(), array(
+    $redirect_uri = url($_REQUEST['q'], array(
       'absolute' => TRUE,
       'query' => array(
         'client_id' => $fb_app->id,
@@ -92,7 +94,7 @@
       'client_id' => $app_id,
       'client_secret' => $fb_app->secret,
       'code' => $code,
-      'redirect_uri' => $redirect_uri,
+                  'redirect_uri' =>$redirect_uri,
     ),
       ));
   $http = drupal_http_request($path);

Even if you do that, you would get the error, "patch doesn't apply." I tried applying it to the development snapshot 7.x-3.x (the master branch for git).


Get "File Upload Error" when I try to upload any images to Node This was and is working fine in my local environment, but when its on the server (hosted by Justhostme) I get this error whenever I try to upload a new image to a node. I've seen advice that it could be my temp directory so I've changed this and set 777 permissions on it. I'm very stuck with this now. I'm not getting any more error message so nothing to hint at what else it could be.

heres hoping.

Edit. I've checked the logs, and these 3 messages appears when I try to upload.
The refered to folder has 777 access too.
Msg 1.

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access public://field/image/leaflet_front.jpg in file_save_upload() (line 1541 of /home/xxx/public_html/includes/file.inc).

msg2

Upload error. Could not move uploaded file leaflet_front.jpg to destination public://field/image/leaflet_front.jpg.

msg 3

The file upload failed. field_image_und_0

There is a long thread in the Drupal.org site surrounding this issue, I didnt locate it at first due to my error message being masked. After many hops around the net I did finally locate it, and it seems to effect quite a few people.

See this link

http://drupal.org/node/1002048

post #154 has a link to the patch for both version 7 and 8 of Drupal.


When setting up the Drupal 7 database (mySql/mariadb) what database user accounts should be created? When installing the database (mariadb) for use with Drupal 7 on Centos 7, what database admin and user accounts should be created and with what permissions?

Do specific directory permissions or file ownerships need to be provisioned for these database user accounts?  -Thanks

You just need one user allowed to create, drop tables, and mysql basic operations (INSERT, SELECT, UPDATE, DELTE, ALTER, INDEX...). In drupal installation tutorial you have more info.


How to change url for a page? We have a production system xxx.org and a test system at test.xxx.org. We copy production to test.  Some of the URL's on the test system keep pointing to production where we want them to point to test.xxx.org.

The production URL looks like they are hard coded in the menu.

We want to easily move production to test so we can test the next version.

Look at the value of $base_url value on /sites/default/settings.php. It may help. Also don't forget to clear the cache on your test site.

If the absolute URL in the menus is not specified directly on the menu items (through Structure / Menus) maybe it was embedded within the template and you'll have to search for the code on the .tpl files of your theme.


Error when using LDAP Views within Rules My objective is to pick a user from an ldap and then create his drupal account.

In order to do this,

1) a user picks a name (dn) from an LDAP server using the LDAP Entry Reference module (which offers autocomplete search)

2) after the user has completed his input, I use a Rule to create the drupal account :
 - dn enables me to search the LDAP with a "View Loop" and get the email
 - with the name and the email, the rules can create the drupal account.

I use LDAP Query and LDAP Views to build the view.

The problem is that the View Loop returns empty results although the views results are correct if I use the views from UI.

I have tested the view with no parameter, no filter, simple LDAP Query, minimalistic ldap (3 users in the LDAP).
My connection to the LDAP is OK : new users can log in with LDAP before drupal account creation : all this is OK.

Do you know of such an error using LDAP Views as a Rules View Loop ? or could you advice how to debugg ?

Or do you know another way to achieve my goal ? (pick a user from ldap then programmatically create the drupal account ?)

my need is exactly what is described here : https://drupal.asu.edu/resources/docs/modules/asu_userpicker . But the module is not available at this url and is designed to be used with other tools.

Thanks

I solved the problem by another way :

Within Rules :
First action : create a new entity (user) set the account name, set the account email with a fake value in the email.
Second action : unblock user (if blocked, the user account will not be synchronized from LDAP)

Then , when the account is created, the Drupal account is automatically synchronized from LDAP and get the good email.

(In LDAP configuration , be sure to configre LDAP User / BASIC PROVISIONING TO DRUPAL ACCOUNT SETTINGS/ Drupal Account Provisioning Events to  "Create or Synch to Drupal user anytime a Drupal user account is created or updated."


If $db_prefix is "assumed to be a string", then does Drupal automatically sort what is a sharable table in the DB? $db_prefix = 'drupal_';

I've found many examples of installations which pick through the tables and place these in an array. And then there is the example of the site I am migrating where it only contained the above string. So, does Drupal sort it all out in the case of this simple string?

What is the big idea I feel I am missing about multi-sites?
(haha the mysteries of the D framework!)

$db_prefix can either be a string or an array, have a look at the documentation: Share a single database across multiple sites, the db_prefix_tables function take care of this job.


Add text after input field with form api (field-suffix) I'm creating a form with a textfield. After the input field I'd like to have some text. Like this:

Label *
|________| some text
Field description

The code I use is:

$form['a_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('A Label'),
    '#size' => 10,
    '#maxlength' => 15,
    '#description' => t('A Field description'),
    '#required' => TRUE,
);

Is there a way do add "some text" after the input field in this way? Do I have do output the HTML code manually via #markup? Is there some way to do this via form alter? Or a theming function?

You can use the #field_suffix property for exactly that:

  Text or code that is placed directly after a textfield. This can be used to add a unit to a textfield.

For example:

$form['a_textfield'] = array(
  '#type' => 'textfield',
  '#title' => t('A Label'),
  '#size' => 10,
  '#maxlength' => 15,
  '#description' => t('A Field description'),
  '#required' => TRUE,
  '#field_suffix' => 'Suffix'
);


How to get body value (drupal 7) I would access to the description of node in body value, so I try this :

// ----------------------------
// Acesseur de la descrition d'un noeud
// ---------------------------
function dfsi_GetBodyOf( $node )
{
    $wrapper = entity_metadata_wrapper('node', $node);
    return $wrapper->body->value();
}
// ----------------------------
// Acesseur de la criticite d'un noeud
// ---------------------------
function dfsi_GetCriticiteOf( $node )
{
    $wrapper = entity_metadata_wrapper('node', $node);
    $wrapper-> field_criticite->value();
return $wrapper;
}

I have no problems to access criticite value, but when I try to access body value, it return "array" and I don't know why, can you help me?

The value of a formated text field is a structure with a value and a format property. Because the body is a formatted text, you likely need to use its value property. Tho get the formatted body value, you will need to use

$wrapper->body->value->value(array('sanitize' => TRUE))


Remove a content type from search results How do I go about removing a content type such as webforms from the site search results?

Drupal's contrib module Search Restrict is a lightweight module that just does the basics - it allows administrators to restrict by role who can search for each content type. It may be a better option than Search configuration in that it only does what you're asking for - restrict content types from search results based on a user's permissions. If you're looking for something more configurable, Search configuration may be the way to go.

From the module's page:

  Approach of this module is to re-write the search query, so that
  content is indexed and available as search results to users in role(s)
  that have permissions to view it, but not displayed to other roles.
  Integrates with Apache Solr to exclude results based on the role of
  the person searching.

Simply download, install, and enable the module. Then to restrict (by role) which users can search which content types, edit each Content Type individually and there will now be a 'Search Restrict' section option (below the Display Settings). It allows you to specific, for each content type, which roles can search nodes of that content type.


Fetching user account additional field in views global php I want to fetch the additional account field by using global php in Views.
The additional account is shown below:

The code I use in Global PHP output:

<?php
global $user;
$namepsm = strtoupper(str_replace("_"," ",$row->value));
print ($namepsm .  ' ' . $user->field_id_number) ;
?>

I have an error

  Notice: Undefined property: stdClass::$field_id_number in __lambda_func() (line 4

I can use other standard account fields, for example $user->name or $user->$mail.

How can I print the additional account field (field_id_number)?

Use user_load function to load your account, like so:

$logged_in_user = user_load($user->uid);

Then dpm($logged_in_user) or print_r($logged_in_user) you will see you have access to the field you added.


Commenting option for each paragraph of a node body I want to provide this option that users be able to put comment on each paragraph of an article that a user has posted in Drupal.

I have applied some changes to node.tpl.php file, like

$paragraphs = explode("<p>",render($content));

so I can render each paragraph with a for loop, like:

 $number=count($paragraphs);
 for ($i=1;$i<$number;$i++)
 print render($paragraphs[$i]);

Now, I want to write a module to provide the commenting option for each paragraph. I will use hook_node_view function to define a new field like:

 $node->content['paragraphcomment']

which is similar to

   $node->content['comments']

but the new one I am defining is a 2 dimensional array. so after

   print render($paragraphs[$i]);  // in node.tpl.php

I can write

   print render($content['paragraphcommnet'].

But I need to know in which file $node->content['comments'] is defined. If anybody can help me with I would really appreciate it. Also if you think my solution is wrong, please let me know.

Thank you

Have you looked at modules that may provide similar functionality like:

https://drupal.org/project/annotator
https://drupal.org/project/annotate

Other links:

https://groups.drupal.org/node/72748
https://github.com/patrickmj/Open-Review
https://groups.drupal.org/node/10875

They may not solve the problem you have but they may have code solutions that can help you go down the correct track


Difference between 2 methods of adding a CSS files in theme.info? What is the different between these 2 methods of loading a CSS files?

; Method 1
css[typography.css][name] = Typography
css[typography.css][description] = Typography
css[typography.css][options][weight] = 99

; Method 2
stylesheets[all][] = css/typography.css

Method 1 means the CSS file is loaded further down the page head, which I need for my theme. However from looking at the documentation it seems Method 2 is more standard?

Method 2 is provided by core (probably why it seems more standard, it'll be used more often).

Method 1 is something specifically provided by the Omega theme.

I think the only reason to use Method 1 is if you want to be able to control the use of the stylesheet through the optional stylesheets setting in the UI.


Help theming hook_theme in Drupal 7 I created a module with a hook_theme(). It works fine but when I copy my-custom-template.tpl.php file into my theme folder to customize the override doesn't work. I  don't understand what I am doing wrong.

function foo_bar_theme() {
  return array(
    'something' => array(
      'template' => 'my-custom-template',
      'variables' => array(
        'zone' => null,
        'location' => null,
        'class' => null),
    ),
  );
}

Can someone help me please? I've checked everything, cleared the cache, checked the spelling, made sure the names are original to not have name clashes.

The file outside your module should be named (in your example) something.tpl.php.


Load CSS and JS using absolute paths on select pages I've got a page (menu callback) which serves as a template for an external service. As the HTML of the page is consumed by the external service and rewritten then served from their server, all the CSS and JS paths must be absolute. Elsewhere on my site I use relative paths via AdvAgg, but here I need to rewrite all the link elements to be of the type file, rather than type external.

How can I do this? I have tried doing a hook_css_alter or hook_js_alter and changing type to external and prefixing the data value with my site's base URL but it doesn't seem to be making my AdvAgg aggregate files absolute, their paths stay relative.

Another idea I had was iterating through all the site's CSS files and unsetting the local entries and instead calling drupal_add_js or drupal_add_css but referencing the files as external with an absolute path, but I don't know where I would do this.

I'm using Drupal 7 with CSS and JS aggregation turned on and with the AdvAgg module enabled.

I had a look at how the web_widgets module was making CSS/JS paths absolute and it looks like a valid solution is just to alter $GLOBALS['base_path'] to add the URL of my site. An easy way to do this is with url():

  $GLOBALS['base_path'] = url('', array(
    'absolute' => TRUE,
  ));


Two different editor in one content typ is there a way in drupal 8 to use two different editors (CKeditor with two different buttonpanels or two differently allowed html tags) in one content type?

I have created a content type of a text field (body) and with the module paragraph other text fields are created. the user should use the possibilities in the body field of pictures and tables but in the text fields of paragraph the user should not be allowed to do so.

I have now created two different editors but the user can always switch between the editors. How can I determine that only one editor can be used in the body field and only the other one in the remaining text fields?
many thanks for your help!
s-webz

You probably need the module https://www.drupal.org/project/allowed_formats.

  Limit which text formats are available for each field instance.


Which view do I have to use to make the order of the images random in Node Gallery Slideshow? I'm currently using Node Gallery Slideshow module for displaying a gallery with a slideshow. It works correctly, but when displaying the images, the order of them is sequential, and I haven't found a way to make it random - at least on the admin interface...
So which view do I have to use to get a random order.

Thanks!

Under admin/build/views/list, look for node_gallery_gallery_image_views. Your probably looking for the 'view all image thumbnails' display here to have it randomize a full gallery. The current display order is based on your node gallery image weight so you'll want to remove these under 'Sort Criteria' (click the up down arrow icon to remove these settings).

After that, you want to add a sort order criteria, 'Global: Random' to have the results of the view sorted randomly.

Note: this will apply to all of your galleries since it is accepting an argument of the parent gallery node object. If you want this just to apply to one specific node_gallery, you'll need to clone the display first and adjust this argument.


sitemap for users not search engines I used simple XML sitemap module to create a sitemap for search engines but now I need one sitemap for visitors.
Can I create this manually instead of using a module because the site already has too many modules?
I was thinking to create a basic page and just add the links there one by one.
Is this a good way?

There is a module that does what you want, and it isn't XML Sitemap but just Sitemap:

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

  This module provides a site map that gives visitors an overview of
  your site. It can also display the RSS feeds for all blogs and
  categories.

  Drupal generates the RSS feeds automatically but few seems to be aware
  that they exist.

  The site map can display the following items:

  A message to be displayed above the site map.
  Any books.
  Any menus that will be displayed fully expanded.
  Any vocabularies, with all the terms expanded. Optionally with term depth, node counts, and RSS feeds.
  A syndication block, the "more" link goes to the site map.

Then:

  because the site already has too many modules?

There is really no way to quantify this for you. There isn't necessarily a module limit, your limit is defined by the limits of your hosting space. The performance impact of adding the Sitemap module, vs spending hours doing it yourself (to reach the same point but with 10x the maintenance) is negligible, especially since you can cache it in Drupal and use things like Varnish or Memcache if your host supports it (if not, find an updated host!). You will be fine.


Creating two entities at once using entity metadata wrappers I'm currently facing a situation where I need to create a new instance of a certain entity and attach a file to it.

Since the main entity should 'reference' the file (the same way a node references a user, by an entity property) there are several things I can do.

Method 1

Save the main entity
Save the file
Update the main entity with the file id.

Method 2

Save the file with temporary status
Save the main entity with the file id.
Update the file to a permanent status.

Since both methods would require me to perform 3 operations in a row I thought it might be simpler to do this with an entity metadata wrapper like this:

// Create the file entity.
$f = entity_create('file', array(
  'uid'               => $data->uid,
  'filename'          => $data->filename,
  'url'               => $data->uri,
  'filemime'          => $data->filemime,
  'filesize'          => $data->filesize,
  'status'            => 1,
));

// Create the main entity.
$e = entity_create('main_entity', array());
$entity= entity_metadata_wrapper('main_entity', $e);

$entity->title       = $data->title;
$entity->...         = $data->...
$entity->file        = $f;

$entity->save();

This however saves the main entity with $entity->file = 0, and the file does not show up in file_managed. Which conflicts with the answer to "How to set value of file field with entity_metadata_wrapper" that implies I can use a new stdClass().

Is there some other error in my entity metadata implementation, or is it not possible to save (create) two entities at once like this?

Update

Apparently my understanding on entity metadata wrappers was completely wrong; While reading the comments on the Entity metadata wrappers documentation page I assumed I could do things like this:

// Changing the author's email.
$wrapped_node->author->mail->set('foo@bar.baz');
// Adding to the answer of @Zakaria Elhariri.
$wrapped_node->field_page->status->set(0);
// Save the changes.
$wrapped_node->save();

I thought saving the main entity would update the nested entities, so I'd expect the email of my account to be changed and the linked node of Zakaria Elhariri's answer to be unpublished. But none of this is true. Why is this is the examples?

  To update the user's mail address one could use

  <?php
  $wrapper->author->mail->set('sepp@example.com');
  ?>

Or is entity metadata wrapper broken somehow?

Without saving the first entity i dont think its possible.

This is KO :

  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  //$entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article without reference KO';
  $entity->field_paage = $paage;
  $entity->save();

This is OK :

  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  $entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article with reference OK';
  $entity->field_paage = $paage;
  $entity->save();

with the second code you have 2 entity (article and page) with the first node page is a reference for the content article.

What you need is save in the first time your file object.

To Update some fields (tested) :

  $wrapper = entity_metadata_wrapper('user', $user);
  $wrapper->mail->set('sepp@example.com');
  $wrapper->field_first_name->set('First name');
  $wrapper->save();


Clearing cache takes "long time" I am absolutely new in Drupal. I am trying to set up my first "Hello world" module and I am playing with it.
Every time I clear cache using Drupal Console, it takes 15 seconds, which is an eternity for me.

Is this normal, or did I need to change setting?

This is the output of drupal site:status.

 Drupal                         8.3.2
 Access to update.php           Protected
 Configuration files            Protected
 Cron maintenance tasks         Last run 41 minutes 54 seconds ago
 Database system                MySQL, MariaDB, Percona Server, or equivalent
 Database system version        5.5.5-10.1.21-MariaDB
 Database updates               Up to date
 Drupal core update status      Not secure! (version 8.7.0 available)
 Entity/field definitions       Up to date
 File system                    Writable (public download method)
 GD library                     bundled (2.1.0 compatible)
 GD library PNG support         bundled (2.1.0 compatible)
 Image toolkit                  gd

 Module and theme update status Out of date

 Node Access Permissions        Disabled
 PHP                            7.1.1 (more information)
 PHP extensions                 Enabled
 PHP memory limit               128M
 PHP OPcode caching             Enabled
 Random number generation       Successful
 Search index progress          100% (0 remaining)

 Trusted Host Settings          Not enabled
 Unicode library                PHP Mbstring Extension
 Update notifications           Enabled
 Upload progress                Not enabled

Web server
 Hash salt                      6X0M4mm-6Ui1Sgovc-emqgqvm2nJ1Ug-fYQYnJfxPniHHwdYMMcBHRBt1xwRtGMRRg7XbK1G3A
 Drupal Console                 1.8.0

 Database connection
 Driver              mysql
 Host                localhost
 Database connection dru
 Port                3306
 Username            root
 Connection          mysql//root:@localhost:3306/dru

 Themes
 commands.site.status.messages.theme_default bartik
 commands.site.status.messages.theme_admin   seven

 Directories
 Site root directory      C:\xampp\htdocs\dru
 Site temporary directory C:\xampp\tmp
 Default theme directory  /core/themes/bartik
 Admin theme directory    /core/themes/seven

Yes, WAMP is not a good environment for Drupal 8. Use a different OS in a virtual machine. Either a Linux VM built from scratch or by a tool like Drupal VM, or a docker based tool like DDEV, Docksal, and Lando.

Which one to choose would be opinion based. Consider not only performance, but also that debugging is most effective, when the dev environment is as close to production as possible.


How to bypass node_access when using EntityFieldQuery? With the following code, if the current user does not have 'bypass node access' (see _node_query_node_access_alter() for exact verifications), then the query checks for node_access, even though I do not use the "node_access" tag.

How can I avoid the node_access check with the following query for a non-admin user?

I'm using this code from a module, so I can verify permissions myself, no need for node_access checks.

  $query = new EntityFieldQuery;
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'foo')
    ->fieldCondition('custom_id', 'value', $custom_id)
    ->execute();

Drupal 7.15 allows you to bypass the access on the node.

See DANGEROUS_ACCESS_CHECK_OPT_OUT query tag added to EntityFieldQuery for more information.

  A "DANGEROUS_ACCESS_CHECK_OPT_OUT" query tag has been added to EntityFieldQuery to allow bypassing access checks. Previously, queries executed through EntityFieldQuery would always be altered by the node access system, potentially causing unexpected behaviour and data loss.

  If you need to bypass access checks in an internal query within your module's API, you may add this tag, but you should only do so if it is necessary. If this query tag is added to a query whose results will be displayed to the user, it will bypass all access checks, potentially exposing sensitive information.

function MYMODULE_field_query($field) {
  $query = new EntityFieldQuery();
  return $query
    ->fieldCondition($field)
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
    ->execute();
}


Filter views on Current user OR Administrator I have a total of 770 users, 760 with the custom role of "certified provider", 10 with the role of "certified administrator".

Using views, and relationships I am able to allow the certified provider to each see only their own created nodes. But I need the "certified administrator" to see ALL nodes from ALL providers.
I have a relationship of Content:Author, and filter of User:Current.
I have read everything I can get my hands on to figure out what to do  and where to go next.

Have tried to follow https://stackoverflow.com/questions/20840490/drupal7-filter-view-based-on-current-users-roles
But haven't been able to get the filter values to work.

Any help would be greatly appreciated.

When dealing with multiple roles, make sure the access control module has all the correct control settings. In Admin->structure->Content Type->Access Control I had the "View any **Content Type** content" checked. As soon as I removed that, the suggestion by @Jimmy Ko, worked, Thanks Jimmy.
 Easy to overlook when you have 3 different places where the content type is limited.


Unable to generate og:image I have installed the Metatag module, along with ImageCache Token, but it just does not work.

I have tried many of the different available tokens in the Open Graph image field for my node, and none of them generate a og:image tag. For instance, I have tried:

[node:my_image]
[node:my_image:large:path]
[node:my_image:large]
[node:my_image:thumbnail]

if I hard-code a URL rather than use a token then it works, but that rather defeats the purpose. My logs contain no errors, and I remember to clear the cache each time. This is driving me nuts. Anyone know what might be wrong?

Check that your image has at least 200x200 as defined in the error provided by Facebook debugger.
Also use Ctrl+U in your browser to check that the og:image tag print the correct url


How do I add the content type token in the page title? I have installed the Page Title module. What I want to achieve is to add the content type token as page title. I tried to change the pattern in the configuration of the Page Title module, but the tokens appear as they are: "[current-page:page-title], [field_glossary_transliterations] - [field_glossary_meaning] | [site:name]."

How do I do it?

Short answer: Simply insert the [node:content-type] token.

Longer answer:

The Page Title module modifies the title that appears in the <title> tag (which also displays in your browser's title bar. Just to clarify, this is separate from an individual node's title.

In the module configuration page, you will only see the raw token names displayed. The Page Title module will convert those tokens to human readable values on an actual node or "page". View the source of one of your nodes and check the <title> tag to see the actual values.

This module relies on the Token module in order to operate.

You can also get the Entity API module (and enable the Entity Tokens submodule) to get even more tokens that weren't picked up before.

Also: Be aware that the project maintainer has identified an issue with Fusion based themes. If your site falls into that category, temporarily switch to another theme such as Bartik to test out the page title module.


How to clone menus in Drupal? I want to implement conditional menus, where different options appear depending on the user's role.

In Display Different Menu links an content depending upon user role or user logged in, user "nevets" suggested making multiple menus each with the appropriate links, and then restricting the visibility of a particular menu by user role.

In my case, the different menus might share a lot of links, so I thought of cloning the links to avoid having to re-enter them when making the second and subsequent menus.

I found the Menu clone? module, but the project page warns:

  D7: This module is still in beta and is a complete rewrite of the original port. It is never recommended to use beta versions on a production environment. Please keep a backup of your database to avoid problems later on.

How can I achieve this? any suggestions?

If you want to be professional, use  Menu clone module all right. Simply do it on development copy of client's site.

It's never a good idea to use beta modules on production site without testing them on devel and stage, but if you do test and they work for your particular site, it's usually safe*. And if all you need are cloned menus, you can use it and then uninstall before stage -> production migration so it will never even appear on your production server.

* As safe as your tests were good.


Drush ignoring `$options['config']` statement in drushrc file from the 'drush' folder at the root of the current git repository I'm a long-time browser, first-time poster.

I have a Drupal 7 site set-up using Drupal-Boilerplate structure in a Git repository. I defined some settings in the drush/drushrc.php file. The documentation indicates:

  “Drush doesn't by default know to search this directory. To work around that we need to add this awesome snippet to our local drushrc.php file.”

I added the provided snippet to docroot/sites/all/drush/drushrc.php. But the $options['config'] statement seems to be ignored. The settings defined in drush/drushrc.php are not taking effect.

I believe that the code is correctly defining the root of the Git repository. The $options['alias-path'] statement seems to take effect as the “example” aliases appear when I run drush site-alias. The $options['include'] statement also seems to take effect as the devify command defined in drush/commands/build.drush.inc is available.

The configuration options I have specified in drush/drushrc.php are not taking effect. When I run drush status, the “Drush configuration” lists docroot/sites/all/drush/drushrc.php and my user-specific drushrc.php from my home directory. I would expect to also see the drush/drushrc.php file listed.

I have tried executing git rev-parse --show-toplevel. That returns the correct path to the root of the Git repository. I tried explicitly adding the drush/drushrc.php file by adding the full path in an $options['config'] statement in docroot/sites/all/drush/drushrc.php. None of that seems to have been effective.

I’m at my wits end with this. Please help me StackExchange!

I’m using

Drush 6.3.0
Drupal 7.28
PHP 5.5.11
Windows 8

As Clive said, the snipped goes in $HOME/.drush/drushrc.php, not in the drushrc.php file in your site folder.  The drushrc.php in your site folder does not get parsed until Drush bootstraps your site; by that time, it's too late to add items to the 'config' list, as it has already been processed.

Also, in place of:

$repo_dir = drush_get_option('root') ? drush_get_option('root') : getcwd();

... it would probably be better if the snippet used:

$repo_dir = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') ? drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') : getcwd();

Finally, rather than setting the 'config' option, which is gitchy and a little high-strung, you could just include your drushrc.php directly.

Replace:

$options['config'] = $repo . '/drush/drushrc.php';

with:

include $repo . '/drush/drushrc.php';

Then you could go back to putting this snippet in your sites/all/drush/drushrc.php, if that's working better for you.


Adding a field with an automatic link in a content type from entity registration module I'm using Drupal to create a website which allows an "employer_role" user to create a "Post Job" content type that has a field type of registration from entity registration module and inside that registration should contains information about an "applicant_role" user EX: Name, Job, Letter, and a automatic link generator where it will link it to the "Applicant's" resume content.

I'm quite new to Drupal and the only thing I can manage is a textbox where the applicant should mannually link his resume content path, which I also don't want the applicant's to put a link from another website.

Any suggestions to help me?

Content type: "Post Job"

  fields:

  Title : text

  company name: text

  job title : text

  body: text //job description

  register: registration // apply form

registration form fields

  Applicant Name: Text

  Applicant Job: Text

  letter: long text

  my profile/resume: auto link field which will direct to the
  applicant's resume content

Not sure if I correctly understand the question, but it sounds to me that using the Entity Reference module might be the solution you are looking for. Here's a quote from the module's project page:

  Provides a field type that can reference arbitrary entities

If that's not what you're looking for, then consider editing your question to rephrase it somehow or to add more details to it.


How to add fields with number values I need to add some fields than can take numeric values and enable Drupal to calculate it. I chose an integer field, tried to do some simple math, but Drupal 7 treats values of integer field as text. Moreover, integer field type widget can be only set up as text. Can anybody help me, and tell me how to add field with number values?

The reason why the widget for an Integer field is a text field is that the form element used from a browser is a text field. This means the browser is always returning text for an integer field.

This should not be a problem, since:

When you add an Integer field to an entity, the field value is validated to be an integer; an input containing characters that are not digits (e.g. 2A, Q3, 2.0) is not accepted, and the users get an error message requiring them to enter only numbers for that field.
PHP generally accepts a string containing only digits instead of an integer without to report errors. If you execute the following code, you would get 15 as result. (It requires the Devel module.)

$a = "3";
$b = "6";
$c = "2";

dpm($a + $b * $c);

You would get the same result if $a is set to "3A".


Conditionally load JS based on whether or not a field has data? I'd like to load a javascript file only if a specific field has data. Can this be done with a preprocess function in template.php? Something like:

if this field is not empty
  add the js to the page footer
else do nothing

Is there a more efficient way?

If a field within a specific content type has some content, load some javascript, if there's nothing in the field, do nothing.

function THEME_NAME_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "CONTENT_TYPE") {
    if(!empty($variables['node']->FIELD_NAME)) {
      drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . 'PATH-TO-JS.js', array('type' => 'file', 'scope' => 'footer'));

    }
  }
}


Adding alt/title attributes to uploaded images I've created a galley using fields and views thanks to this tutorial: http://jamestombs.co.uk/2011-05-26/create-album-based-image-gallery-drupal-7-using-fields-and-views

But now I can't figure how to add the usual ALT and TITLE attributes to the gallery images. The only option available is to delete the images.

Thank you.

The tutorial you are referencing states this, "On the next screen just press Save field settings."  This is where the issue starts. You have to edit the image field he tells you to create and, instead of hitting 'just save' you have to enable the options for ALT and TITLE fields, about 3/4 down the page.

Then, when you upload image, each image will display a place where you can fill these out.

Then, in views, you will have two more options - Content: Image (some_field) ALT, and Content: Image (some_field) Title. You can then select these as fields and theme them as needed to be part of your image gallery


Add content type to body class I want to add a body class for the content type of each node. Drupal already provides this, but it isn't always consistent between the Node view, the Node/Add view and the Node/Edit view. This makes theming difficult.

Here is my code in template.php

function MYTHEME_preprocess_html(&$variables) {

    // Add Content type name to classes
    $content_type = $variables['page']['content']['system_main']['type']['#value'];
    $content_type_class = 'content-type-'.drupal_html_class($content_type);
    $variables['classes_array'][] = $content_type_class;

}

It works but I get this error message:

  Notice: Undefined index: type in wintheme_preprocess_html()

On Stack Exchange, it says the best approach is to use Isset().

If I do this, the error message goes away, but so does the class.

How can I keep my class working without the error message.

The problem is you're trying to use the same system_main content type variable that's not always defined. Try this instead:

$node = menu_get_object();
$type = isset($node->type) ? $node->type : 'none';
$type = ($type == 'none' && arg(0) == 'node' && arg(1) == 'add') ? arg(2) : $type;
$content_type_class = 'content-type-'.$type;
$variables['classes_array'][] = $content_type_class;

That should give you a $classes_array var with either "content-type-TYPE" or "content-type-none" for pages that aren't associated with nodes.


Block cache not clearing on save? I have some custom block types that display in a region in my site. I have noticed that when changing the contents of these blocks, like an image, text, or title, that when you save and visit the page, the block data is cached and doesn't show the new changes. This is problematic because the client keeps reporting this as a bug, but I can't see where or why it won't update.

Is there a way to have it invalidate when saving a block so that a cache clear isn't necessary? I figured this would be normal behavior, but I have to clear it (while logged in as UID 1 even), and I don't think I am doing anything weird or have a contrib module installed that would interfere with this.

Edit: I am not using Panels or anything - this is core block.

The problem is, that the cache tag block_content:[id] does not bubble up and the tag is missing in the cache entry. Without this cache tag the cache entry can't be invalidated when saving a modified custom block.

Here are two workarounds:

Twig template (Workaround 1)

If you theme a block template and you render single fields

{{ content.field_field1 }}
{{ content.field_field2 }}

then you also need to render the rest of content:

{{ content|without('field_field1', 'field_field2') }}

That's because content contains the cache tag of the block content entity, which otherwise won't bubble up.

Preprocess (Workaround 2)

As an alternative option for rendering {{ content }} you can add the cache tag at the top of variables in preprocess.

mytheme.theme

function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }
}

Then you no longer depend on the twig template to render all of content.

You'll find in Drupal\block\BlockViewBuilder::preRender() more workarounds for issues with bubbling up data from the content render array. You could use this code, which there is only applied in special circumstances, for all cache data from block content to bubble up to the top level:

use Drupal\Core\Cache\CacheableMetadata;

function mytheme_preprocess_block(&$variables) {
  $content = $variables['content'];
  CacheableMetadata::createFromRenderArray($variables)
          ->merge(CacheableMetadata::createFromRenderArray($content))
          ->applyTo($variables);
}

But I don't know which side effects that would have in other places. If it would be that easy the block view builder would do this already. So it's better to tackle only that specific problem with the one missing tag and use the first version of the preprocess function.


Rewrite id of a exposed filter block? Hi there I'm trying learn how to rewrite a #id of an exposed filter block (ie. a searchbar filtering a list view. Is there an easy way to do this?

Isn't something that is possible to do with rules?

(i would like to get an answer with an example of how to do the rewrite inc. an example of a syntax as I'm no guru on php or rules either for that matter :)

To rewrite the ID of the block (if you really want to), you would either use a preprocess function or a custom template file.

Looking at the preprocess function for blocks template_preprocess_block() found here.

https://api.drupal.org/api/drupal/modules!block!block.module/function/template_preprocess_block/7

You can see how the ID is created: $variables['block_id'] and what the theme suggestions are: $variables['theme_hook_suggestions']

You should be able to create a function in you themes template.php as follows:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block_id'] == 'old_id') {
    $variables['block_id'] = 'new_id';
  }
}

However, with a filterblock, there might be some special relationship to the view that might be damaged, I'm not sure, but either way, you do not need to use Rules.


Php Access User Data from external script Currently my Drupal installation is at www.example.com/wiki/

I was wondering if it is possible in Drupal 8.2.4 to access the current user uid from an external php script.

The script is located at www.example.com/someScript.php

I've tried this before

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

global $user;

if ($user->uid) {
    print "Logged in";
} else {
   print "Logged out";
}

You can following file authorize.php to do it like this:

<?php
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

$autoloader = require_once 'autoload.php';

function authorize_access_allowed(Request $request) {
  $account = \Drupal::service('authentication')->authenticate($request);
  if ($account) {
    \Drupal::currentUser()->setAccount($account);
  }
  return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
}

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

authorize_access_allowed($request);
$user = Drupal::currentUser();

if ($user->id()) {
    print "Logged in";
} else {
   print "Logged out";
}


How to add title of the image in manage display section or display it in node view page I want to display title property of an image in node view page.
How can I display title of an image along with image in node page?

Custom Formatters

Try the Custom Formatters module to create a custom formatter, Tokens may help. There are some examples for inspiration: Custom Formatter Examples.

Or implement through your own custom solution in a module or a theme: Create a custom field formatter.

Views Block

Another way of doing it is hiding the Image field on Manage Display, and creating a Views Block instead with a contextual node ID filter that outputs that image field along with the title. If you don't see the title available as a field in content views out of the box you can add a Relationship to that field to get it.


Why the commit is not shown in the issue after it is closed as fixed? Yesterday I saw that I forget to commit a change in a 8.x branch of a project, so I search for the commit message in the 7.x branch and I commit the changes and push my code to drupal.org, but today I see that the commit appears in the project page but not in the issue.

If you go to see the commit you will see the issue number and reference:

https://www.drupal.org/commitlog/commit/43654/082f754b0f3780979663afea014df3cb84d0eeec

  Issue #2846726 by ...

But in the issue page the commit not appears, this can be because the issue have the Closed (fixed) status?

It is more likely the case that the service that handles the issue updates was down for some period of time. Under normal circumstances pushing a commit to D.O. will update the issue referenced in the commit message no matter what the issue status is set to...


What is exactly access arguments used for in hook_menu? I have read the link : hook_menu

Snippet from the page

  "access callback": A function returning TRUE if the user has access
  rights to this menu item, and FALSE if not. It can also be a boolean
  constant instead of a function, and you can also use numeric values
  (will be cast to boolean). Defaults to user_access() unless a value is
  inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
  items can inherit access callbacks. To use the user_access() default
  callback, you must specify the permission to check as 'access
  arguments' (see below).

  "access arguments": An array of arguments to
  pass to the access callback function, with path component substitution
  as described above. If the access callback is inherited (see above),
  the access arguments will be inherited with it, unless overridden in
  the child menu item.

But Still unclear about what access arguments are actually used for ?
Are the access arguments the permissions ?

Access arguments is the key for an array which contains the user permission. This means that current user must have this permission to access this page.

We can use already defined user permision or can create new permission for our menu item.

If you go to permission page (Administer >> User Management >> Permissions), you can see the list of string you might use for access arguments.

If you want to create new permission for your menu item, you can implement hook_permission in your module.


How to make friends ajax with dynamically created links? I created leaflet map, when you hover the marker in popup window is a reference to the content.

I wrote module that loads ajax content in the custom region. For dynamic links added class use-ajax, but Drupal does not process them as I needed.
I check and found that static links with class use-ajax have additional class ajax-processing.
My dynamic link looks like:

засорение реки

Static link looks like:

node

As I understand Ajax Drupal does not work with dynamic links.
I found issue in what asks in what need to change the href attribute of a link and make the ajax call to the new url.  Change 'href' attribute in AJAX enabled links
Wrote JS code but it doesn't work for me.

(function ($) {
  Drupal.behaviors.test_module = {
    attach: function (context, settings) {
        $("#jslink").click(function(){
            var href = $("#jslink").attr("href");
            Drupal.ajax['jslink'].options.url = href;

        });
    }
  };
})(jQuery);

Is it possible to somehow make Drupal to work with dynamic links?
What am I doing wrong?

I found solution, for loading balloons I use module IP Geolocation Views & Maps it has js file ip_geoloc_leaflet_goto_content_on_click.js
where I add line Drupal.attachBehaviors();
Now it works as designed.

jQuery(document).bind('leaflet.feature', function(event, marker, feature) {
  // marker is the feature just added to the map, it could be a polygon too.
  // feature.feature_id is the node ID, as set by ip_geoloc_plugin_style_leaflet.inc
  // Need to set this up for code below.
  // The same code is used for cross-highlighting. See ip_geoloc_leaflet_sync_content.js
  if (feature.feature_id) {
    marker.feature_id = feature.feature_id;
  }
});

jQuery(document).bind('leaflet.map', function(event, map, lMap) {

  if (map.settings.gotoContentOnClick) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('click', function(e) {
        var id = e.target ? e.target.feature_id : null;
        if (!id && e.layer) id = e.layer.feature_id;
        if (id) {
            //document.location.href = Drupal.settings.basePath + 'node/' + id;
            document.location.href = Drupal.settings.basePath + 'load_node/' + id;
        }
      });
    }
  }
  if (map.settings.openBalloonsOnHover) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('mouseover', function(e) {
        this.openPopup();
         Drupal.attachBehaviors(); <<<<--------ADDED LINE
      });
    }
  }

});


How to revoke edit access to the node's author after publishing a node? I am trying to build a new rule on Drupal 7 with both the Rules and Content Access modules (and its sub module Content Access Rules integration). Thus, I get new actions like "grant or revoke an access" for specific role.

An authenticated user can add a content on the website but it is unpublished by default (like a draft).

When the user is ready, he/she can publish the content (different modules can do that, Save Draft, Publish content).

After the content is published (which event?), I need to revoke the modification access for the node author.

I have tried to build the rule as this tutorial shows but without Flag.

It does not work, the author can still edit the content after publication and no modifications have been made on access control for this node (I have checked the "Per content node access control settings" box in the content type settings).

I guess the problem is the non-published state of my node and thus the lack of access settings, since Content Access needs published nodes to operate. Then, I ask Rules to modify content access that does not exist ...

A custom module is available here but I would rather use the Rules module since, theoretically, it could be done.

Here is an export of my rule code :

{ "rules_revoke_edit_access_after_publication" : {
    "LABEL" : "Revoke edit access after publication",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "content_access_rules" ],
    "ON" : { "node_update--manuscript_submission" : { "bundle" : "manuscript_submission" } },
    "IF" : [ { "data_is" : { "data" : [ "node:status" ], "value" : "1" } } ],
    "DO" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node" ],
          "permissions" : { "value" : [
              "view:3",
              "view_own:3",
              "update:3",
              "update_own:2",
              "update_own:3",
              "delete:3",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }
}

Default access for authenticated user : view/modify own content (+ view any unpublished content (of the content type needed) thanks to the View unpublished module)

Access needed after publication : view own content only.

Approach 1:

Here is the rule (in Rules export format) that I think is what you are looking for:

{ "rules_disallow_edit_own_content_after_node_is_published" : {
    "LABEL" : "Disallow edit own content after node is published",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "content_access_rules" ],
    "ON" : { "node_update--manuscript_submission" : { "bundle" : "manuscript_submission" } },
    "IF" : [
      { "data_is" : { "data" : [ "node-unchanged:status" ], "value" : "0" } },
      { "data_is" : { "data" : [ "node:status" ], "value" : "1" } }
    ],
    "DO" : [
      { "content_access_action_revoke_node_permissions" : {
          "node" : [ "node" ],
          "permissions" : { "value" : [
              "view:3",
              "view_own:3",
              "update:3",
              "update_own:2",
              "update_own:3",
              "delete:3",
              "delete_own:3"
            ]
          }
        }
      }
    ]
  }
}

Just import this rule in your own environment to review/qa-test it.

Some more details about the "clue" (magic?) of this rule:

The Rules Event is related to "Updating a node of content type manuscript_submission.
The Rules Condition is to ensure that the Rules Action is only triggered the moment that the node changes from unpublished to published.
The Rules Action simply REMOVES the permission for the author of the node (cfr. "own" in Content Access terminology) to edit that node for rome "authenticated user".

Note: The above rule is "tuned" to content type with machine name manuscript_submission. Change that machine name to any other content type (eg: article). Make sure to perform such change before you actually import this rule (because the Rules UI do not allow you to change that "event" after importing anymore).

Approach 2:

You can also use a work-around to implement "... revoke the modification access for the node author..." that you are asking for, as detailed below.

Have a look at my answer to the question about "How to specify a Rules condition like 'Before creating new content'?". Here is a quote from it, which I also recommend in your case here:

  Try using Rules (System) event "Drupal is initializing" (= init), which is actually BEFORE your edit form is shown.

With that, you actually don't (have to) "revoke access", instead you just the Rules module to capture the Rules event that somebody is about to start an edit session of a node. And then, depending on the extra Rules conditions you want to check (in your case: 'is the current user the author of this node?' AND 'is the status of this node published?'), you just use a Rules action to redirect a user to "somewhere else" (instead of showing them the edit form they asked for).

Note: If you want to use my proto-type Rules example in my answer I mentioned above, it's obvious that you'll have to adapt the Rules conditions and/or Rules actions to make it fit for you case (like the URL of your edit form?).


How to add template suggestion for user--VIEW-MODE--ROLE.html.twig I used hook_theme_suggestions_HOOK_alter:

function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

Now I can work with user--full.html.twig and user--compact.html.twig

But I have a role editor and I want to user--compact--editor.html.twig to be picked up. How can I add a template suggestion based on user roles?

All you need to do is to get the current user object, get its roles, and then add the suggestion like in the following snippet. The current user also already is available in the $variables.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {

  // Define the view mode.
  $mode = $variables['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;

  // Get current user.
  $current_user = $variables['elements']['#user'];

  // Get current user's roles.
  $roles = $current_user->getRoles();

  // Add suggestion per role.
  foreach ($roles as $role) {
    $suggestions[] = 'user__' . $mode . '__' . $role;
  }
}

This will give you:

<!-- FILE NAME SUGGESTIONS:
   * user--full--administrator.html.twig
   * user--full--authenticated.html.twig
   * user--full.html.twig
   x user.html.twig
-->


Profile image goes over the text on advance forum in drupal 7 I'm fairly new to Drupal and I'm testing out Advanced Forum module on my site.

The problem I'm facing is that when photo which is uploaded is bigger than user info layout, then it goes over the text. Is there any way to force image to stretch and fit into the user info block?

I tried changing css, but I'm not really sure which one to change and in what manner. I'm using silver bells...

Can anyone guide me through this?

Thanks in advance!

It might not be exactly the answer you're looking for, but using CSS only, you can add this rule to your theme's main css file:

img{
max-width: 100%;
}


How to override  ad_adapi() in custom module Currently, in my custom module that depends from the Advertisement module, I have permissions case, and I want to add statics_increament in my custom module.

How can I override ad_adapi()?

As the Advertisement module invokes that hook using module_invoke_all('adapi', 'permissions'), and it doesn't use drupal_alter('adapi'), your module could override that implementation of hook_adapi() using code similar to the following one. (I assume the short name of your custom module is "custom_module"; change it to the short name you are using for your module.)

function custom_module_adapi($op, $node = NULL) {
  switch ($op) {
    case 'permissions':
      return array(
        'access statistics' => TRUE,
        'access click history' => TRUE,
        'access activity log' => TRUE,
        'set status as pending' => FALSE,
        'set status as denied' => FALSE,
        'set status from pending to approved' => FALSE,
        'set status from pending to denied' => FALSE,
        'set status from approved to active' => TRUE,
        'set status from approved to offline' => TRUE,
        'set status from active to offline' => TRUE,
        'set status from active to expired' => FALSE,
        'set status from offline to active' => TRUE,
        'set status from offline to expired' => FALSE,
        // Add your permissions.
      );
      break;
  }
}

function custom_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'adapi') {
    // Move custom_module_module_adapi() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['custom_module'];
    unset($implementations['custom_module']);
    $implementations['custom_module'] = $group;
  }
}

custom_module_adapi() is completely overriding the values returned from ad_adapi(); for this reason, it cannot simply add the extra values it needs.
The code I wrote is a kind of hack; the correct way would be for the Advertisement module to use drupal_alter() to allow third-party modules to override the values set from other modules. The code I wrote works, but you need to keep update the code for custom_module_adapi() with the code used in ad_adapi(), in the case it is changes.
Only the branch 7.x-1 has ad_adapi(); the branch 7.x-2 doesn't have that function anymore. If you are planning to use that branch, the code for your custom module should be changed.


Multiple primary keys I have defined a new content type, statetype and a CCK field, state.
I need to use the CCK field as primary key in this table because I have another table and I need use that field as foreign key. (This code and table is not Drupal and i wrote it myself, but it uses a Drupal table.) I should change state field to primary key in the "statetype" table but Drupal already defines vid as primary key. Is there any problem if I define multiple primary keys (vid, state) or if I remove vid as primary key?

A database table can have at most one primary key, but it can have multiple unique keys.
Replacing the primary key in that table is not a good idea, because Drupal code rely on the fact the primary key is vid. You cannot set any field as primary key: it must a field that contains unique values for each row; if the field you choose can have the same value for multiple rows, then it's not a candidate for primary key.


Drush up error - unable to untar - Destination already exsists I have verified that the directory does not exist before attempting an update. The error I get is as follows.

Do you really want to continue? (y/n): y
Executing: svn info /home/sites/lg/public_html/drupal-7.26
Executing: bzr root /home/sites/lg/public_html/drupal-7.26
Executing: wget -q --timeout=30 -O /tmp/download_filexptX5V http://ftp.drupal.org /files/projects/drupal-7.26.tar.gz
Downloading drupal-7.26.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-7.26.tar.gz verified.                                                                                [notice]
Mime type for /home/sites/lg/public_html/drupal-7.26.tar.gz is application/x-gzip                                                                 [notice]
Executing: tar -C /home/sites/lg/public_html -xzf drupal-7.26.tar.gz
Unable to untar /home/sites/lg/public_html/drupal-7.26.tar.gz.                                                                                [error]
Destination directory /home/sites/lg/public_html/drupal-7.26 already exists.                                                                   [error]
Project drupal was updated successfully. Installed version is now 7.26.

I am on a vps using CentOS 6.5
Drush version 5.9
Currently installed version of Drupal is 7.23

I've had a similar problem in the past.  It looks like there's already a /home/sites/lg/public_html/drupal-7.26 (at least based on your post).  Make sure you have read / write access to it.  Better yet, run drush as root or under sudo.


JQuery hoverIntent / Drupal contrib hoverIntent module not working I'm trying to get the jquery plugin hoverIntent to work on my Drupal 7 installation.
No luck.

1st, I tried the logical approach; simply the following to the theme .info file.
scripts[] = js/jquery.hoverintent.js
Doesn't work, and causes other problems.

Then I tried the contrib hoverIntent module. I can see that the script is loaded on the page, but calling  .hoverIntent from within Drupal results in nothing happening.

$(function() {
  $(".views-field-field-profile-picture").hoverIntent(teamIn);
  $(".team-name-info").mouseleave(teamOut);
});

Anyone with success in getting hoverIntent to work? Why is this so difficult?

Found it. First, you will most likely see an error in the logs like this
 TypeError: cfg.out is undefined

The problem in my code is not that .hoverIntent wasn't loaded, it was that that method requires two parameters. (Obvious error)

Solution:

$(function() {
  $(".views-field-field-profile-picture").hoverIntent(teamIn, function(){});
  $(".team-name-info").mouseleave(teamOut);
});


Set value of file field using entity_metadata_wrapper non working I have a custom entity with a file field accepting multiple values.
I would like to set file values according to
https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers#example-value-set-save but none of the two methods are working here.
I always get this error

error  php  Error: Call to a member function set() on null in include().

I am running Drupal 7, file_entity module enabled. Here follows the code:

$file = file_load(8172);
$wrapper = entity_metadata_wrapper('sys_ind', 13718);
$wrapper->field_allegati->file->set( $file );
$wrapper->save();

Fixed! Thanks to this post Save a new value with entity_metadata_wrapper to an entity field which is an array

$file = file_load(8172);
$node = entity_load('sys_ind', array(13718));
$wrapper = entity_metadata_wrapper('sys_ind', '13718');

$wrapper->field_allegati[NULL]->file->set( $file ); # This worked

$wrapper->save();

so the fix is using NULL (at least in multivalue field like mine is), not 0 or any other index nor [].


Domain Access separate home page per domain does not work I have 3 domains set up on my dev machine.
1)drupalx
2)drupaly
3)localhost

Hello, I am using:

Domain Access 7.x-3.11 (with at domain configuration and domain setting enabled)
Internationalization 7.x-1.10.

I JUST enabled domain configuration/domain settings modules to try and get a separate home page per domain. Before I was using domain access without these 2 helper modules.

I am attempting to set my home page per domain.  There appear to be 3 ways to do this and none of them are working correctly.

Option 1) setting the values in /config/system/site-information

With this approach and Domain Access there is a domain access section at the bottom of the site-information page. You are supposed to set the home page and then choose which domain it is for and then save. In this domain access section it is supposed to show all the domains you have created, but mine says "localhost" for all of them.  Looking at domain access options for my content types (related side topic) shows that now the options for the other domains are missing there as well. It ONLY says "localhost".  It used to say localhost, drupalx, drupaly, but as I saved the front page for each of those domains the save process changed the machine name for drupalx and drupaly to "localhost" I am able to go back to each domain individually and change back it's machine name (but weird that it changes that).
After saving I get a message
"The configuration options have been saved for localhost. These settings will be inherited unless overridden per domain." Meaning it is saving that front page for every domain available (checking confirms this)

Option 2) First setting section in "admin/structure/domain/view/2/config"
Here you can set a separate home page per domain but when you go to the home page of those domains there is no front page defined (it just doesn't work).

Option 3) Second settings section in "admin/structure/domain/view/1/variables"
Here you just set the front page per domain.  Anytime I put any value in here after the page saves and reloads that value is gone, re-replaced by "node".  This does not work either.

I only enabled domain configuration and domain setting modules to try and get some extra configuration options to set my front pages per domain.  Didn't get me anywhere.
I of course tried to set the home page before enabling domain configuration and domain setting modules, and that didn't get me anywhere either.

Anyone have any front page advice for any of these front page configuration settings I tried?

If you are using panels, you can create one homepage, but with separate variants for each domain. We use this approach for ~12 sites running on one drupal instance.


"Process 'Apache web server' failed to start. Port 8083 didn't open" I'm trying to install Acquia Deve Desktop 2 for my windows 10 PC. When it's finished installing and I run the program, an error pop up message shows up saying Process 'Apache web server' failed to start. Port 8083 didn't open.

I should point out that I do have XAMPP installed in my PC, but I also read in the documentation that even if you have XAMPP installed, it won't interfere.
What am I doing wrong here?
I just want my Drupal websites to load faster because on XAMPP they're pretty slow.

Sounds like there is a port conflict or a hiccup in Acquia Dev Desktop.

Try a reboot. This might fix an Acquia hiccup.
Since you already have XAMPP configured and working the way you want change, I'd suggest changing the Acquia Dev Desktop port.

Here's how:

Open Acquia Dev Deskop
On the menu bar, click "Acquia Dev Desktop", then "Preferences...."
Click on the "Ports" tab (2nd tab)
Change the "Apache port" to another another number. Eg. "8087"
Click "OK"
You will need to restart the Apache server. You could click the "Stop" -> "Start" button. I prefer to close and re-open Acquia Dev Desktop.

No need to learn/install another DEV environment or change an already setup one (XAMPP)


Manage display not updating user account display This is a new D7.14 site started only 3 days ago. There is no use of organic groups in this site. I added several fields (i.e. First Name, Last Name, City, State, Zip - as text and list fields). I set these to show on user registration form and to display publicly. I came back about a day later and changed the display settings on User Account to hide the labels and to change the display order. I also hid one of the fields completely on User Account. I opened a new browser and navigated to the user account for a random user - the labels still appear and the order has not been updated. I cleared cache - no difference. I ran cron - no difference. I subsequently updated a few modules and had to run update.php - no difference.

Any suggestions?

Are you sure you edited the right viewmode? Have a look at the viewmodes which are enabled. Probably you moved the fields not on the viewmode "Full Content" (or "Full Profile") but on the "Default" instead. Or maybe the "Full Profile" is not activated?


drush failure on error in drupal 7 My initial installation of Drush couldn't even recognize commands such as "drush migrate-status", therefore I reinstalled drush and followed the steps in the included README.

After reinstallation, drush now recognizes the command "drush migrate-status", hwoever it is throwing an error and crashing. I am confused as I have not even enabled the migrate_example module included with the Migrate module, however drush is throwing the error message below:

require_once(/var/www/drupal7/sites/all/modules/migrate_example/beer.inc):[warning]
failed to open stream: No such file or directory bootstrap.inc:3024
PHP Fatal error:  require_once(): Failed opening required '/var/www/drupal7/sites/all/modules/migrate_example/beer.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/drupal7/includes/bootstrap.inc on line 3024
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: require_once(): Failed opening required
'/var/www/drupal7/sites/all/modules/migrate_example/beer.inc'
(include_path='.:/usr/share/php:/usr/share/pear') in
/var/www/drupal7/includes/bootstrap.inc, line 3024

This all seems very cryptic to me, especially when I have not enabled the migrate_example module and I have the migrate_example directory under migrate.

Could someone please explain why drush might be throwing this error?

It sounds like the file /var/www/drupal7/sites/all/modules/migrate_example/beer.inc is missing.


EntityRegistration: How do I show who is registered to other registrants/members Actually I am relatively new to Drupal - so maybe for a Drupal-Crack this is chicken-food - but not yet for me :-)

I'm building a new Drupal 7 (7.14) site using "Views" and "Entity Registration" (Beta1) to build a event system where members can join events and leave some comments. Therefore I've set up the "Event" entity using Drupal fields and the Views module. Then I've created registrations for the events and added them to the "Events" as a field. No problem so far - works great and users can join events incl providing their additional registration information (Events are "Scuba Dives" and additional information is the Equipment Configuration, Gasmixes, Body-Team, etc).

As an event organizer (creator) I can see a tab with the list of registrants (divers) but I don't see this tab/information as a normal member/registrant.

This is where I got stuck: How can I show the list of participants to all members (role)? I like to show them on the same "page" as the eventdetails are. Maybe creating a block or so? Maybe create a view for a block (with fields, sorting and grouping) and show this as block on the events.

I already know that I can customize a nod by adding a theme-template for a specific content-type. Don't know if that would work to bring the list of participants to my events...

As you see I am not really sure what way I should go with this and what make most sense. Any help/hint would be great!

Cheers,
Marc

I've got it work by creating a View with a contextual filter for the event-id. Then in the event-page (using Panels) if added the event-id to the arguments when rendering the view into a pane.


Load Media File in Webform Mail Handler I want to use a single webform to send download links with specific media files to visitors that fill out that form. For example on an URL like this:

https://example.com/downloads?media=1234

The media parameter will be the ID of an media entity type like "Download".  Now I want to send the mail with the name of the media entity and a link to the file of that entity.

How could I get this done? Mail handler and a custom Twig template is what I think about, but how do I get the data of the media entity? Any ideas? Thanks for every helpful comment ;)

$media_id = \Drupal::request()->get('media'); // get value of media query param

$media = Drupal\media\Entity\Media::load($media_id); // load the Media entity

$media_name = $media->getName(); // get the media item name

$media_field = $media->get('field_media_image')->first()->getValue(); // get media field

$file_id = $media_field['target_id']; // get the File ID

$file =  Drupal\file\Entity\File::load($file_id); // load File entity

$image_url = $file->url(); // get image url

You could take this shortcut instead of writing the last 4 lines.

$image_url = $media->get('field_media_image')->entity->url();


How do I hide/remove a views menu tab from some pages? I created a page view with Page Settings for the path being equal to:
node/%/content/recentnews

I also set the Page Settings menu to have a menu tab.

How does that system decide what pages will display the menu tab?

I have one page where the menu tab is displayed, but I don't want it to be shown on that page. Is there some way to remove/hide it?

Thanks,
Greg

There are two factors to consider when determining whether the tab is displayed:

The parent menu item
The result of the access callback

You probably cannot do much about the parent menu item, because this points to the generic node/%node.

You can, however, influence the result of the access callback by configuring how to validate the argument. This allows you for example to display the tab only for nodes of a certain content type. Of course you will have to configure the view to hide the view/display 404 if the argument does not validate.

A fancier validation would be possible if the validation configuration dialog would allow you to enter PHP code. I don't know if this is the case, so you might have to look for a different solution.


Trying to display a views list with order based upon current node being viewed I have a view block which shows lists of content type "news" which displays in a sidebar showing only the node title for users to peruse.

There are about 150 such "news" nodes and so I use pagitation.

These "news" nodes are completely linear. You always want to read them in order. So if you read node/20, you must read node/21 next, then node/22 etc.

I would like the view block in the sidebar to display the titles of 2 nodes BEFORE and AFTER the current node. So, if I went to node/20, I would like the view block to display:

Title of node/18
Title of node/19
Title of node/20 (current node being viewed)
Title of node/21
Title of node/22

I was hoping for some pointers as to how I might achieve this. All things that I've tried thus far have proved futile.

Thanks.

In your View, under Block Display, go to:

Advanced-> Contextual filters (Add)->Content: NID

In the "When the filter value is NOT available" option select:

Provide default value-> PHP Code

and add the following code:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nodeid = arg(1);
  $result = strval($nodeid-2) . "+" . strval($nodeid-1) . "+" . strval($nodeid) . "+" . strval($nodeid+1) . "+" . strval($nodeid+2);
  return $result;
}

Last but not least, under "More", select the option: "Allow multiple values"


Token to show only first term in Page Title module I am using Page Title module and patterns to auto create them. One of the tokens for Page Title when creating content is taxonomy term.

Since users can add as many terms in content i would like to limit Page Title to only use first term added by the user.

Is there a way to do this with tokens ?

Delta values for field are available in token

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


Problem with drush and site alias (Drupal 8.8.6 / Drush 10.3.1) I've installed two drupal sites on a share hosting (OVH), in two folders :

dev.www
www

I've installed drush 10.3.1 and create two alias, but when I try use alias (drush @dev status), I have the follow error :
[warning] Drush command terminated abnormally.

I don't know if my drush configuration or aliases are good or bad. Here is my configuration in .drush/sites/the-choices.site.yml:
'@the-choice.dev':
  remote-host: ...
  user: ...
  root: /home/thechoc/dev.www
  uri: 'http://dev.the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/dev.www/insecure_private_key'
'@the-choice.prod':
  host: ...
  user: ...
  root: /home/thechoc/www
  uri: 'https://the-choice.org'
  ssh:
    options: '-o PasswordAuthentication=no -i /home/thechoc/www/insecure_private_key'

If someone can help me. Thank in advance.

There is no need for the leading @name and try adding the full path to drush for all remote environments:
dev:
  ...
  paths:
    drush-script: /example/path/www/vendor/drush/drush/drush
prod:
  ...
  paths:
    drush-script: /foo/bar/www/vendor/drush/drush/drush


Views, find content types with field NOT IN other content type Content Type A
-Nid A
-Field A

Content Type B
-Nid B
-Reference Nid A

How can I find in a view all As that have no reference in B ?

in sql this is

select A.field
FROM TABLE A
LEFT JOIN TABLE B
ON A.KEY = B.KEY
WHERE B.key IS NULL

I have tried Views reference filter, but it is very slow and consume a lot of memory (the trick with this modules is not a join but a SELECT... NOT IN (...).

Which is very inefficient, because, i have 16.000 As and 14.000 Bs.

Is there any efficient solutions with views?

Thanks.

Well, maybe it is idiotic, but finally I understood the issue with the relationships and the "referenced vs referencing"

So, what I did was:

relationships : "Content referenCING Content from A_REFERENCE_IN_B"
Fields A (the fields you want)
Filter type = Type A
Filter NID (using the relationship) , is null.

Amazing, and super fast.

The important part is REFERENCING not referenced.

Thanks.


Alter language select on a node add/edit form Wonder if anyone has had any experience altering the options presented to a user from the language select on a node add/edit form. I have some custom access control ont the site and basically I'm looking to remove options based on a individual editors access to approved locales. If they haven't been approved to make edits for a certain locale then they shouldn't see an option to add a translation for that locale in the dropdown.

See http://cgit.drupalcode.org/redirect/tree/src/Form/RedirectForm.php#n70

The language widget/form element is designed so that when you explicitly provide some options, then it doesn't add the default.


Chosen working on one select but not other selects I'm facing a strange problem with the Chosen module. I've have 3 term-reference fields added to a content-type.

While editing & adding any nodes of this content-type, Chosen UI interface is applied & working with all 3 fields.

Now, I created a view and exposed the filters for all these three term-reference fields. In the view, Chosen UI interface is applied only to one field and not applied to the rest.

In the settings of chosen module (admin/config/user-interface/chosen)
Apply Chosen to the following elements is set to select

These are the Drupal settings outputed by Drupal into javascript:

"chosen":{
  "selector":"select",
  "minimum_single":"20",
  "minimum_multiple":"20",
  "minimum_width":"300",
  "search_contains":true,
  "disable_search":false,
  "disable_search_threshold":"Never Apply",
  "placeholder_text_multiple":"Choose some options",
  "placeholder_text_single":"Choose an option",
  "no_results_text":"No results match",
  "multiple":{
     "field_tags_tid[]":true,
     "field_working_area_tid":false,
     "field_published_in_tid[]":true
  },
  "max_selected_options":{
     "field_tags_tid[]":false,
     "field_working_area_tid":false,
     "field_published_in_tid[]":false
  }
   }
}

What might be the problem? How can I rectify it?

EDIT: Here is something interesting. When I manually enter jQuery('select').chosen() into the browser console, then other two exposed filters (select elements) which were not rendered as Chosen UI elements are now rendered.

Any idea, about what might be wrong with it?

It looks like you have a 'Minimum number of options' setting of 20. I'm guessing the ones that don't display have less than 20 available options. Try setting this to 'always apply' on the Chosen settings form (admin/config/user-interface/chosen).