How to get only the first value of a field in a Views template I'm using Views 3.0 and I'm trying to access a field which allows users to upload 3 photos. When I type print $fields['field_productshots']->content; it displays all 3 product photos. Is there a way to limit it to just the first image?

When editing the view, there's an option for Multiple field settings. By default view is going to set it up to Display All starting at zero.

You can easily change it to display 1 starting at zero. This will only show the 1st image now.

Hope this helps.


Perform "Add to cart" through web services I am working with Drupal 7 web services.  I created few services on my project but now stuck in the commerce's services.

I could not understand how can I add an item to cart with some line item values through web services.  What will be the json structure ?

The commerce's cart, checkout, review perform many functions through rules and hooks, so are we going to write code for all of those steps in our custom services module?

I have found a similar post on stackexchange, which is little bit helpful.
Click here!

But there, they have used commerce line item's ids which will not available in my case because how could we know the lineitem's id before submitting it to cart ?.

Found the below solution for my above query.  But I am not sure, what are the standard way to implement this.

1) First I have to create an cart order using commerce services module.
http://localhost:8080/drupal7/serviceendpoint/cart

2) Second I have to create new line item and attach it to the order created above using the same module.
http://localhost:8080/drupal7/serviceendpoint/line-item

In that way I am able to create a new order with line items.  But I will appreciate if anyone could suggest me a clean, better and a proper way.


How to render formatted text field from paragraphs as is in twig? I need to render a text (formatted long) field using twig. At this time i am doing the following below. However, i am finding that if i were to add a line break in the text field or apply adding spacing or a horizontal line, the twig filter "raw" removes those attributes. I need assistance to see what I am missing.

I have already set the view mode for field on the content type to default

Twig template (filter used)

{% for item in items %}
    {{ item.field_body.value|raw }}
{% endfor %}

Expecting

Actual result

This is the code I'm using inside one of my field templates to output a text field, which is used as an HTML/JS widget input box

{% for item in items %}
  <div{{ item.attributes }}>{{ item.content['#context'].value|raw }}</div>
{% endfor %}

Should work for you, I guess you'll have to remove the |raw filter for your case. (But usually it is not the recommended way to output fields this way.)


Why would drush sql-sync fail to work? I have a development server set up in my drush aliases as @dev, and a UAT server set up as @uat.  I can successfully execute drush commands locally on both servers, and I can execute remote commands from UAT to the development server (e.g. drush @dev cc all or drush @dev upc or whatever).  However, when from the UAT server I execute

drush sql-sync @uat @dev

it appears to work, but when I first make a change on UAT and then sync and then check the same page on dev is has not changed.   I have tried drush @dev cc all afterward to make sure there is no caching problem, but this doesn't help.

What could I be missing?  Or what could be failing?  How can I troubleshoot this?

UPDATE (corrected): If I log into @dev and execute the same command (in other words, having @dev pull data from @uat rather than having @uat push data to @dev) it works.   But I'd still like to get it working when executed from @uat.

There's not enough here to tell what's wrong, but there are a couple of things you can do to isolate the problem. Start with drush @uat sql-conf and drush @dev sql-conf; this is what Drush will use to look up the database records for the two sites.  If one of these fails to print the right information, that could cause sql-sync to fail.  Next, try drush sa --with-db @uat and again for @dev, and see if the database record matches what you saw with sql-conf.  If, for example, you copied a database record into your @dev alias and specified the wrong database (one different than the one specified in settings.php), then sql-sync might be successfully copying your production database to some other db on the dev machine.

If neither of these things work, you can try adding first -v (verbose output) and then -d (debug mode -- really a lot of output) and see if there is anything there that might help you find the problem.

Update: Did you make a typo in your update?  drush sql-sync @dev @uat pushes dev to uat, which seems like the opposite operation.  If drush sql-sync @uat @dev works on dev and not on uat, I would recommend carefully comparing your alias files on the two machines and see if there are any differences.  Especially check your 'databases' record in your alias definition, if you have any, and run the diagnostic tests I recommend above.  As a workaround, from uat you could run drush @dev sql-sync @uat @dev, which would remotely run drush sql-sync @uat @dev on the dev machine.


How to disallow users with certain emails form posting? On a Drupal 6 site, I struggle with some persistent spammer who uses different tricks to escape any regexp spam filters. Whenever I delete him, he always uses certain email provider (e.g. somerandomname@blablamail.com) to register again.

So I am wondering how can I disalow blablamail.com altogether so that either users can not register with this email provider, or better, they can not post anything after registration?

You can create an access rule and deny creating an account or logging in with an account that matches certain criteria.

Go to admin/user/rules and add a new rule. In your case, the access type should be deny, rule type should be e-mail, and the mask can be '%@blablamail.com' for instance. You can test your new access rule by clicking on the Check rules tab afterwards.


How to download programmatically a module? I need to programmatically download projects from drupal.org, and then eventually enable it with modules_enable. Anyone knows how to do it?

Here's the final solution :
I'm sharing the code i used for those who'll face the same problem.

    /**
     *
     * Function downloading the last version of the module in MY_MODULE_MODULE_DIRECTORY
     * $modulename correspond au nom system du module
     *
     * @param string $modulename
     */
    function MY_MODULE_download_module($modulename) {
      // DEBUT CODE TELECHARGEMENT

      $base_url = 'http://updates.drupal.org/release-history/' . $modulename . '/7.x';
      // @TODO MODULE NAME

      $xml = drupal_http_request($base_url);
      if (!isset($xml->error) && isset($xml->data)) {
        $data = $xml->data;
      }
      try {
        $xml = new SimpleXMLElement($data);
      }
      catch (Exception $e) {
        // SimpleXMLElement::__construct produces an E_WARNING error message for
        // each error found in the XML data and throws an exception if errors
        // were detected. Catch any exception and return failure (NULL).
        return;
      }
      $json = json_encode($xml);
      $array = json_decode($json, TRUE);
      $download_link = $array['releases']['release'][0]['download_link'];

      $path = MY_MODULE_contrib_dowload($download_link);
      MY_MODULE_archive_extract($path, MY_MODULE_MODULE_DIRECTORY);

      // FIN CODE TELECHARGEMENT
    }

    /**
     * Fonction downloading a file
     * Inspired from update_manager_file_get($url).
     * Upload the file in the temporary folder
     *
     * @param url $url
     */
    function MY_MODULE_contrib_dowload($url) {
      $parsed_url = parse_url($url);
      $remote_schemes = array(
        'http',
        'https',
        'ftp',
        'ftps',
        'smb',
        'nfs'
      );
      if (!in_array($parsed_url['scheme'], $remote_schemes)) {
        // This is a local file, just return the path.
        return drupal_realpath($url);
      }

      $cache_directory = _update_manager_cache_directory();
      $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
      // load the file in the right directory

      return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
    }

    /**
     * Function inspired from update_manager_archive_extract($file, $directory)
     * extracts a file to a directory
     *
     * @param path_to_file $file
     * @param path_to_directory $directory
     * @throws Exception
     * @return A path
     */
    function MY_MODULE_archive_extract($file, $directory) {
      $archiver = archiver_get_archiver($file);
      if (!$archiver) {
        throw new Exception(t('Cannot extract %file, not a valid archive.', array(
          '%file' => $file
        )));
      }

      // Remove the directory if it exists, otherwise it might contain a mixture of
      // old files mixed with the new files (e.g. in cases where files were removed
      // from a later release).
      $files = $archiver->listContents();

      // Unfortunately, we can only use the directory name to determine the project
      // name. Some archivers list the first file as the directory (i.e., MODULE/)
      // and others list an actual file (i.e., MODULE/README.TXT).
      $project = strtok($files[0], '/\\');

      $extract_location = $directory . '/' . $project;
      if (file_exists($extract_location)) {
        file_unmanaged_delete_recursive($extract_location);
      }

      $archiver->extract($directory);
      return $archiver;
    }

Normally you want to use drush, e.g.

drush -y en module_name

which would download, install and enable your module of interest.

Check drush.api.php to use appropriate API hooks which could be useful.

If you don't want to use Drush, check how Update Manager does that in update/update.manager.inc, e.g.

update_manager_file_get
update_manager_archive_extract
etc.

To get the list of available files to download for specific project you've to fetch and parse the release history which is available at:

https://updates.drupal.org/release-history/project_name/7.x

the same as drush does that (check by drush -vd dl foo) and get the links from there.


Is there a way to Embed Facebook Videos? D7.37:

I am Trying to embed Facebook Videos and cannot find a way to do it.  Points:    Have already installed: Media-Module, Oembed, Media-YouTube, but cannot get Oembed to actually embed anything.  The Media-YouTube works; I can embed YouTube Videos.  I can embed SoundCloud Audio.  I can embed Flickr Images.  I cannot get anything Facebook related to embed.  Is this even possible in D7?   I tried downloading the Video-Lightbox software, but it would not take URL's from Facebook.

When I try to “cut & paste” the Facebook URL into the Video-Light-Box software, the URL seems to be loading then just terminates producing nothing.  If I do the same thing with a YouTube-Video an actual file is embedded.

When I try to embed the Facebook URL via the Media-Module-Browser, I get an error “SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'oembed://https%3A//www.facebook.com/AnimalsAustralia/videos/1015' for key 'uri'”; however the file brokenly loads and then is only available as a Link to Facebook NOT an Embed.

When I try to embed the Facebook URL via the WYSIWYG-Editor-AddMedia Button, either as a new Facebook URL or an entry from the Media-Library, a small Icon appears which is also only a Link and not an Embed.

When I try to embed the Facebook URL via the WYSIWYG-Editor-AddMedia Button, but wrapped in [embed] {Facebook URL} [/embed] tags, I receive an “Unable to handle the provided embed string or URL” error message.

BTW I have scoured the settings to be sure that "Rendered-File" is selected in the Media-Display settings of this Content-Type.  I have a Content-Type set up specifically for handing Media and configured to allow Remote Media Types of Video.

What might I be missing?

I was able to embed facebook, youtube and vimeo videos in a view using just the following:

Drupal version:  7.54
Media Module version:  7.x-2.0-rc5
Media: oEmbed Module version:  7.x-2.7
Entity view modes module: 7.x-1.0-rc1 // optional

Facebook URL:  https://www.facebook.com/video.php?v=10153231379946729

Try the above URL format.  If the video still won't embed, then it's probably the configuration.

My media field in the content type is setup as follows:

Field Type:  File
Widget:  Media Browser
Enabled browser plugins:  Upload and Web
Allowed file types: Image and Video
Allowed URI schemes: oEmbed resources and Public files
Allowed file extensions for uploaded files:  png, gif, jpg, jpeg

Note this field supports both images and videos.

Then you need to setup your file display for videos here:

/admin/structure/file-types/manage/video/file-display

I used the Entity view modes module to create a a new view mode for this field.  Then I selected the oEmbed formatter for my view mode.

Then in the view, select the Rendered file formatter and the view mode you created.

Then when creating the node, try the above url.


Trouble adding modules with Composer I created a Drupal 8 site through the manual install process and configured the site through the admin UI for a while. However, I quickly discovered how critical it was to use Composer to add modules due to the prevalence of third-party libraries. But I am getting the following error whenever I try to add any new module, and I will use Drupal Commerce module as an example (note that my production site is currently housed in the /public_html/main directory):

username@mydomain.com [~/public_html/main]# php
/home3/username/public_html/composer require drupal/commerce
Using version ^2.7 for drupal/commerce
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 14 installs, 1 update, 0 removals
 - Installing drupal/coder (8.2.12): Cloning 984c54a7b1 from cache

[RuntimeException]
Failed to execute git clone --no-checkout
'/home3/username/.composer/cache/
vcs/https---git.drupal.org-project-coder.git/'
'/home3/username/public_html
/main/vendor/drupal/coder' --dissociate --reference
'/home3/username/.compo
ser/cache/vcs/https---git.drupal.org-project-coder.git/' && cd
'/home3/username/public_html/main/vendor/drupal/coder' && git remote
set-url origin
'https://git.drupal.org/project/coder.git' && git remote add composer
'https://git.drupal.org/project/coder.git'

Cloning into '/home3/username/public_html/main/vendor/drupal/coder'...
done.
fatal: unable to create thread: Resource temporarily unavailable
fatal: cannot repack to clean up

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--
no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-
with-dependencies] [--update-with-all-dependencies] [--ignore-platform-
reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--
optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader]
[--] [<packages>]...

Thanks for any help.

I have successfully battled this error into submission over the past six hours.
I pieced together what I believe were the contributing problems and found a way for things to work correctly in a remote hosted (Bluehost) Drupal installation.

You must be able to use composer commands.  If composer is not installed on your remote host, you will need to install ssh and then install composer.  SSH lets you use command line typing so you can interact/execute composer commands
login to composer (I opened up Windows powershell and used SSH from there).  You will be challenged to put in your password for ssh the first time you use it.  If you have it configured tightly, you will be asked everytime.
cd www/your-drupal-directory If you don't start off in the drupal directory, you will not get code dropped into modules/contrib which means nothing will show up in your administration 'install' link from your site. Specifically, you login into composer and then just type the command and hit enter.  You'll then see your composer line now has your drupal path showing.  My path was www/d8 because Bluehost serves pages from www and I installed drupal in the d8 subdirectory. I'm sure public_html would have worked as well.
Commerce requires more than one module to run properly.  When you visit the Commerce installation page, pay careful attention to the Ludwig installation information.  The list of seven dependent modules is there.  You will need to be sure each dependent module is installed (some may already be installed).
--update-no-dev is the key to success.  Adding this option on your composer command will stop the addition of development packages during your module install.  A composer command for the general commerce package would be composer require drupal/commerce --update-no-dev then hit enter
Your next problem will be inconsistent 'stability' releases.  I used the default settings when I installed composer.  You can get around that problem by explicitly referencing the module version you want to install.  For example, Commerce requires the Entity module.  I used composer require drupal/entity:1.0-beta4 --update-no-dev

The issue of coder not being found seems to come from a difference between what is found in the composer.json file and the composer.lock file.  The update-no-dev is telling composer not to require the drupal/coder (and other things)

I am no expert on composer or drupal development.  I'm sure others can provide a more technical explanation.  It is always a good idea to check for updates periodically for all installed modules and themes.  You should have a report in your administration link on your site that gives you an idea of available updates.


What is rss category format in manage dislay? Anybody please explain what is the rss-category format, in the manage display settings of term referense field.

When I check this format, nothing is displayed on the node page.

Thanks.

This display setting hides taxonomy links on the node page and adds category elements into Drupal's RSS feed (http://example.com/rss.xml). Go to your site's RSS feed and you can see it in action.


Programmatically updating a node I can create a node using the following code:

$node = \Drupal::entityTypeManager()->getStorage('node')->create($array);

But if I have the node ID, how can I edit a node?

You can try this code

<?php
use Drupal\node\Entity\Node;

$node = Node::load($nid);
//set value for field
$node->body->value = 'body';
$node->body->format = 'full_html';
//field tag
$node->field_tags = [1];
//field image
$field_image = array(
    'target_id' => $fileID,
    'alt' => "My 'alt'",
    'title' => "My 'title'",
);
$node->field_image = $field_image;

//save to update node
$node->save();


Bulk import images & create nodes Is there a way to bulk import images from server and auto create nodes for each image? this is for Drupal 7

The module Bulk Media Upload is the one that I have used in the past for that matter. From the module page:

  With Bulk Media Upload you can upload a bunch of files and a new node, taxonomy term, or other entity will be created for every file. The files are selected via a browser file upload dialog and can be stored in a file or image field.
  Also default values can be chosen for the other fields assigned to the new node.

I believe you will not have any difficulties, it is pretty straightforward. Also, if you come across some minor bugs, I have a couple of patches commited in its issue queue awaiting community review.

Alternatively, one can use the Feeds module to import nodes. That would be more helpful with existing files. It might require to list the files into a CSV file (for *nix systems copy/paste from terminal the output of ls /path/to/files).


Link field to node content only with Colorbox I would like to show all "content type A" pop up in Colorbox, with "main content" only. Meaning no header, sidebar or footer.

So In my Drupal 7, I installed Colorbox and Colorbox node modules. And created a Views that list all of the "content type A". Then I added a "Content: Title" field with "link this field to the original piece of content" and "display the content inside of a colorbox" are checked. However, the link did pop up with colorbox but it come with full page, which is including the header, menus, footer and everything else. How can I just show the main content?

Go to admin/config/media/colorbox and at the bottom there is a settings called 'Colorbox Node Integration' uncheck Enable Regions and save it.
After that colorbox shows only main content of node.


Facebook like photo gallery with comments, tag photo, share etc Is there any Facebook like photo gallery module with comments, tag photo, share option.
Please help in this.

To annotate images in Drupal 7: Imagefield Marker
http://drupal.org/project/imagemarker

See also: Image Annotations in Drupal 7

Very good multiple image uploader in Drupal 7:
Media module
http://drupal.org/project/media
(Quick way to get this is to create a free drupalgardens.com account and export the whole Drupal 7 code)

Comments are built-in in Drupal 7 for many content types.

Consider also:
http://drupal.org/project/disqus
(Drupal support for DISQUS a discussion comment system for integration with various social networking sites)

Also: Facebook Comments module:
http://beacon9.ca/labs/drupal-7-facebook-comments

I would suggest integrating comments with an existing social network as their authentication policies (particuarly Facebook's for example) can discourage trolls, spam and provide you with a centralised means of managing the comments, as well as spreading awareness of your site as their comments on your site are seen by their friends in their feeds).


Rule to redirect to registration page after adding new product to cart Rule to redirect to registration page after adding new product to cart. I am using ubercart module for this and working with drupal 7

Yes, the options is given by default in ubercart. Go to admin->store->configuration->cart
Please check the attached image for more clarification.


Module an permission issues I have a custom module called 'products'

I set the access options like so:

function products_permission() {
  return array(
    'access products' => array(
      'title' => t('TBYT Products'),
      'description' => t('Administer TBYT Products'),
    )
  );
}

In the admin I have enabled the module and gave everyone this permission.

Then I defined:

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

  $items['products/list'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping',

    'page callback' => 'html_list_products',

    'access arguments' => array('access products')
  );

   return $items;
}

This works fine, however I need to now make the URI dynamic, so I added something like:

  $items['products/list/%/%'] = array(

I also added the appropriate page arguments:

'page arguments' => array(2, 3),

However when I rebuild the cache and I access:

products/list/23

it works fine but when I access

products/list

I get:

The requested page "/products/list" could not be found.

Addressing the (correct) conclusions you've come to in the comments...

Yes, you'll see some repetition in Drupal 6/7. Drupal 8 uses Symfony routes so things get better, but it's not stable yet.

For your specific case you don't have to have 3 separate menu items (although for the sake of clarity it might make sense). You can define a single list page like so

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

  $items['products/list'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Enjoy shopping',
    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

And define your page callback like so

function html_list_products($arg1 = NULL, $arg2 = NULL) {
  if ($arg1 && arg2) {
    // Both args were provided.
  }
  elseif ($arg1) {
    // Just the first arg was provided.
  }
  else {
    // No args were provided.
  }
}

Drupal will always pass along the remaining slash-separated parts of the request URL to the callback function, so with the above method if you visit /products/list/1/2, $arg1 and $arg2 will be populated respectively. Similarly if you visit /products/list/1 just $arg1 will be populated, and for /products/list, neither will be.


Entities in Drupal 7 What are Drupal Entities in Drupal 7? I understand that Drupal Commerce built Products as an Entity. I know now there is a core Entity API and an contrib add on for Entity API.

I have a few projects this year where I would like to use Drupal 7, NoSQL and possibly the Entity API if it calls for it- but I am having trouble seeing where it would be needed.

Assuming you were building a job listing site- a job isn't necessarily like node content, could/would you make that an Entity?

Additionally, can you still get the ability to talk to modules with the Entity and how is that done? Like, a Job Posting entity getting aliased with Pathauto and exposed in Views as well as appear in XML Sitemap.

A entity is data structure defined by hook_entity_info() and can be fieldable, which means that you can add fields to them.

In Drupal 7 Core, Nodes, Users, Comments, Vocabularies and Terms are entities.

In Contrib, there are many more, for example private messages and commerce as like a dozen of them ;)

However, I think job postings are perfectly fine as nodes :) Entities don't automatically have Pathauto (Tokens), Views etc. integration.


How can I select a set of nodes directly linked to a node using views and wikitools I'm a newbie with Drupal so I apologize if my question is not presented appropriately, I'll try to be as specific as possible.

So I am developing an academic wiki using Wikitools (gathering academic information such as papers, economic data, etc.). The two types of content I will mention here are (i) Articles - each article presents an academic paper written by one or several authors; and (ii) Authors - a page presenting a particular author/researcher and providing internal and external links related to the researcher (e.g. his website, videos, etc.).

What I would like to do is to select all the Article pages for which a researcher is categorized as an author and display them in the Author page corresponding to that person.

I tried to do that with Views: I created a view, filtered using 'Content type' (i.e. Articles) and 'Links to' as criteria. The view has been integrated into the Author page and links have been established between Article pages and the Author page using Wikitool link format ([[name|name]]).

However, no article pages get displayed in the Author page. I removed the 'Links to' criterion to see what would happen, and all article pages created get displayed. So the view is working correctly but it seems that the links created using the Wikitool format are not recognized as actual links. It's the only explanation I could think of so far, and I could not find any hint in other forums.

So if you guys have any idea, I would really appreciate some help... I'll stay posted to provide additional details if needed.

Thanks a lot for the awesome work you're all doing. I've just discovered Drupal and I still can't believe how innovative and well-designed the whole project is.

Cheers,
Igor

So I found a very simple solution to my problem: I used a contextual filter (in Views) and a Node Reference. Each Article page is linked to corresponding Author page(s) using a node reference. Then using a Contextual Filter in Views, I was able to select all articles written by a given author and display them in the author's page.

I'll give additional details on how to set up the contextual filter, even though it might seem simple to experienced users, new users like me might find the information useful. To set up the contextual filter for the task I described, I selected: 'Provide default value' ('Content ID from URL'), then 'Override title' (and I entered "Articles mentioning %1" in the blank space), 'Specify validation criteria' ('Content', 'Author pages') and 'Node ID' as filter value format.

I don't know whether it can be helpful to someone else but I would have saved a lot of time if I had found that information earlier... :)


Can't access private files I have implemented a private file system for users to upload files. This appears to be working as I can see that the file is uploaded into the proper directory. The problem I have is that no one has permission to view the file (including user 1 which seems odd to me). The error message is:

You are not authorized to access this page.

From what I have read in the documentation, I believe I have everything set up correctly. The file path is outside of the web root directory and accessible by Drupal (as evidenced by the successful file upload). The page that displays the link to the file is in the form of:

/system/files/private/test.pdf

Which is the correct link.

The file permissions set on the directory is: drwxrwxr-x

Which looks right to me as well.

So I am completely stumped. I followed the Drupal 7 documentation page on setting up private directories so I am not sure what I missed. I have obviously overlooked something and hope that someone can tell me what it is or what I should be looking for or what I need to implement to get this working. This is for Drupal 7 by the way.

Thanks

After digging around some more I have found the solution. In your module you need to implement the hook_file_download() function. This function determines whether a user has the permission to view the file. It should look something similar to this:

function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.
  $can_access_file = check user permission function

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1; // return that user does not have access
}

Hopefully this will help others with similar problems.


full html and ckeditor strip some meta tags I have this code in the field_data_body table in Drupal 7 in the database:

 <meta itemprop="url" content="http://sitename.com/images/picture01/art-cinema1.jpg" />
 <meta itemprop="width" content="252" />
 <meta itemprop="height" content="190" />

But when I edit the content I have just this code in the body field:

When I copy the code from database and paste it again into the editor, it shows the correct form of code but when I click the source key in CKEditor the code will change to the short form again.

In addition, when I save the content and use inspect element of Chrome browser it shows me the complete form of the code!!

So the problem is just the edit node page which just shows me a short form of code and removes all the meta tags!! How can I fix this problem?

Please add following code in Ckeditor Javascript Settings,

config.allowedContent = true

Thanks


Theme and subtheme basics I am a newbie to Drupal, and I really don't understand the difference between sub-theme and base theme. Why can't I directly edit the base theme?

I am working on a website which is live and has bartik as default theme. I don't know where to start.

You haven't really asked a question. But i'll assume that you want to know what a base and sub-theme is in drupal.
TLDR version
A drupal subtheme inherits the template files (*.tpl.php) and assets (javascript, css, images) of the base theme. If you need to modify or change the template files.
More on subthemes
I think your best bet is to google it. I googled, "drupal subtheme" and found you  drupal documentation regarding subthemes:

Sub-themes are just like any other theme, with one difference: They
inherit the parent theme's resources. There are no limits on the
chaining capabilities connecting sub-themes to their parents. A
sub-theme can be a child of another sub-theme, and it can be branched
and organized however you see fit. This is what gives sub-themes great
potential.

Source: Creating a sub-theme (drupal.org)
In addition to the node page, if you're more inclined to watch a video this is probably a good bet: Drupal Subthemes (youtube.com)
Why should you avoid modifying a base theme

Flexibility: Base themes maintain flexibility. If there is an update, your child theme inherit these changes
Losing your changes: Modifying your base theme means that when an update to the theme comes along your modifications could potentially be lost
Maintain simpler code base: The base theme allows you to abstract a lot of functionality and reduce the code base. This means less maintenance in the long run.

Best Practices with subthemes:

Copy files from the base theme or use the drush command (when available)
Utilize subtheme theme hooks to override your theme


Preprocess Panels or Panelizer content I am trying to change output of some of the fields used inside my panelizer content, i.e node pages, but hook_preprocess_page( &$vars) is showing the output as rendered #markup and i just cant get hold of the render-able array for my content?any help please?

There is a template_preprocess_panels_pane

/**
 * Implements preprocess_panels_pane().
 */
function YOURTHEME_preprocess_panels_pane(&$vars) {
}

Documentation

If you want to change the output of a field you have:

/**
 * Implements hook_panels_pane_content_alter().
 */
 function YOUR_MODULE_panels_pane_content_alter($content, $pane, $args, $contexts) {
  $content ...
}


How can I change a page's title for each page individually? I am wondering if there is a way that I can change the page titles so that users can see a nice title but that at the same time, the internal title of that same page be different?

You can use a module that allows you to change it each time or use a different pattern than default Drupal:

Metatag

This module allows you to control a lot more than just the Page title.


Create view without content I would like to create a Home view (the principal page of the site) without any type of content like news. The problem is that when I create a view, I don't see any way to hide the content.

I have tried to put the number of items to 0, but this loads all contents. How can I create a home page without any content?

My Drupal version is 7

Instead of dealing with Views just copy the page.tpl.php file of your theme to page--front.tpl.php and do whatever you want with it. In particular you can comment out the <?php print render($page['content']); ?> and replace with any code you need.


Get nodes by content type when type key is not in root of nodes array I am trying to get all nodes by content type. When the key is in the root of nodes array, like [type] I can easily retrieve it by, for example:

$nodes = node_load_multiple(array(), array('type' => 'page'));

But how do I do it when the key is not in the root, like:

    [title] => Test 1
    [status] => 1
    [comment] => 0
    [promote] => 0
    [sticky] => 0
    [nid] => 24
    [type] => page
    ...
    [field_worktype] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => some_value
                            )

                    )

            )
   ...

So, in the above example, how do I get nodes which [field_worktype][und][0][value] equals "some_value"?

With an EntityFieldQuery:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'page')
  ->fieldCondition('field_worktype', 'value', 'foo');

$result = $query->execute();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

As an aside, the method in your OP (using the $conditions array) is deprecated in favour of EntityFieldQuery anyway, which can perform the same filters.


Drupal search based on content type I have two type of content lets say News and Article.
Now, I want search over these two content types(option is given to user). I am using default search module of drupal.
I am able to search both by www.example.com/search/node/ but unable to filter out because I don't know how to provide content type here.

My question is :

How to provide search parameters (like content type) to URL so that my search works correctly according to content type?

I try to provide www.example.com/search/node/[content type]/[search pattern] then         "[content type]/[search pattern]" become actual search pattern.
   What are the options I have.

If URL change is not the solution what are the options I have to resolve the issue.

Regards,
Yatendra.

You could make the same search with a view and add contextual filter to achieve the specific URL pattern and normal field filters to apply other filtration if needed. The view could render the node with the same display that you was going to use for the default search so if you have already built the markup - you don't have to do it again.

Edit:
Also if you want to use the default search api - you could make a facet to filter with the help of the Facet API Module


How can I change the value of a field in node / [id] / edit? I should change the value of a field before it is rendered. I tried with [NAME_MODULE]_node_view but it is not invoked when I edit the node.

Thank you so much.

I alter my forms with the following:

function mymodule_form_test_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // code here...
}


How do I create a rule to prevent a user from sending a message via the Privatemsg module? As a courtesy to registered users on my website, I require all users who send private messages to have a profile picture.

I already have system messages throughout the site to encourage them to upload such a picture (for example, when they log in, or visit a user's profile) with a link to their account edit page where they can upload such a picture.

But how do I block them (without banning them of course) from sending a private message if they do not have a picture (in other words BEFORE the message is sent?)

Fall back scenario: If I cannot stop the action before it happens, how do I prevent the message from being delivered, with the appropriate warning to the sender of course?

The message is sent by the Privatemsg module, not the Rules module.

Any idea?

UPDATE

I have tried both solutions proposed below (jeroen and Pierre Vriens) and both did the job.

Pierre's solution below works well and is easiest to implement.

For those who need guidance in implementing it, here are the steps:

1 - Create a new role. I called mine "can send private messages"

2 - Give this new role the "send privatemsg permission" only. Remove the same permission from the authenticated user permission (and other roles that have it and shouldn't.) At this stage, only those users who have the new role will be able to send private messages. The others will be sent to a "you do not have permission to access..." page.

3 - Create the first rule: Give it a name and select, under User, "an account is created." Save it. Create a second event and, still under User, select when an "account is updated." You now have two events in the same rule.

4 - Create the condition: Select "Data value is empty." Then drill down and select the name of the field that should contain the main picture (in my case, it is "site:current-user:field-user-image".) Below that, check the Negate box. This means the rule will check if the field is NOT empty.

5 - Create the action: You want the role to be granted if the field is not empty. So select "Add user role" under User. Data selector is "account" and select the value of the role (it's the name you gave to the new role.)

And that's it. To make the user lose the role if he removes the picture, you need to create a new rule, albeit a little less complicated. I called mine "disable private messages send." It only has one event: "After updating an existing user account" The condition is, again, "Data value is empty" but DO NOT check the Negate box. For the action, it's pretty straightforward. Like for the first rule but select the remove role instead.

For this rule to work the user must go into his account and click the save button. This is ok with new accounts but it may be a drawback if your site already has many users. But eventually, they will all update their account one way or another and the rules will be implemented then. If only a few users, the administrator (user #1) can go into their accounts and click on the new role box to grant the role.

See my second update below.

Again, thank you to Pierre for his insightful approach.

I don't think you can use the Rules module directly for this, because the only action that is provided by Privatemsg is called when a message has been sent. Therefore, I suggest you write an easy piece of code.

When a user hasn't set a profile picture yet, the field is empty or displays the default picture if you picked one in your configuration. In both cases, $user->picture has value 0. You could use this fact by hiding the sending form for a private message with the following code in a custom module:

function MYMODULE_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($user->picture==0) {
    hide($form);
  }
}

As suggested in the comment below, you can also use $form['#access'] = FALSE; instead of hide($form);. You can add a line of code that, for example, displays a message Please add a profile picture! or whatever you want in the if statement.


How to add a translation to an existing node/entity using REST? I have a headless Drupal 8 and want to create a translation for an existing NODE using a POST request but cannot figure how to.
I know how to create, edit and delete a node but am unsure on how to add a translation to an existing node. If I add the langcode it creates a new node in that specified language but I want a translation for an existing node ID.
Please advise.

You have to load the node first and than addTranslation. You can check if exists or not. This way I was able to do it.
    $transNode = Node::load($nid);
    $transNode = $transNode->addTranslation("en");
    $transNode->title = $title_EN;
    $transNode->body= $body_EN;
    $transNode->field_1 = $field_1_EN;
    $transNode->save();


Read and write files from external FTP server I'm looking for a way to add (S)FTP support to my Drupal Commerce website.

It's rather simple. Once every night, a cron job should get all the files from the (S)FTP, process them and place other files back on the server. That's it :)

It's a store and all the products, customers and other data come from a different system. So the Feeds module should connect to the FTP and process the files.
But it looks like there is no decent FTP module around. I've looked into the Backup and Migrate, Storage API, Order FTP Export and Save to FTP, but nothing really met my requirements.

So is there an easy way to connect to an (S)FTP server and exchange files?

I think you better face this problem using system commands that adding FTP support to the Drupal stack.

For this you can use:

1) standard FTP. You can read here how to automate FTP commands from a bash script:
http://www.stratigery.com/scripting.ftp.html

2) SFTP, FTP over SSH. If you can use SSH public key authentication this is the best way as you only will have to exec this command every day:

scp your-remote-user@your-remote-server:/path/to/files/* /local/dir/for/files

Once your files are copied locally you only have to process them with Feeds.

You can even use PHP exec and launch the script that retrieves your data from the Drupal Cron.


How to render a menu_block in a specific language (i18n) I have a special menu that is part of the page. I include it in the template like

$block = module_invoke('menu_block', 'block_view', DEF_BOOKLETS_MBID);
print render($block['content']);

Menu's are part of the interface, not of the content. If I use i18n, the translated menu will appear fine if the interface language switches.

However, the client does not want that. The interface is supposed to be one language, but the content can switch languages. That works too - apart from the menu block inside the content.

Is there a way to render a menu_block inside a template in the current content language ?

ok - this is extremely ugly, but seems to work

global $language,$language_content;
$org_language = $language;
$language = $language_content;
$block = module_invoke('menu_block', 'block_view', IAF_BOOKLETS_MBID);
$language = $org_language;

print render($block['content']);

Feel free to boo me on this one :-D


Show related nodes of a specific type when looking at a node of a different type I have a custom content type Topic, another custom content type Sub-Topic, and a taxonomy Topic Tags.  I'd like to be able to display the sub-topics on the page for each topic that has any of the same topic tags.

I'm using panels to define how pages look topics, and I was trying to use a view for the sub-topics.  I can make a view that filters by a specific tag, but I can't figure out how to pass the tags that the topic node has to the sub-topic view.

Thanks!

I would look into using the "context" module for this.

With it you would be able to set "conditions" and "reactions". The condition, being if your topic node is visited, react by showing a view block of the sub-topics. You can configure said block view to show the taxonomy tags based on certain criteria.


Edit content if (taxonomy) Country = United Kingdom I have created a user, now I want to give him permissions so that, when he is logged in, he can view/see all the contents, but can't edit/publish/unpublish/delete them.

Of all the contents, he can view/edit/publish/unpublish/delete only those contents, that has United Kingdom as taxonomy term, for example something like.

Logged in user can see all the contents, but If any content has Country -> "United Kingdom", then give permission to edit/publish/unpublish that particular content?

I have already tried Taxonomy Access Control, but didn't help me. Either I couldn't see any content, or I could edit all of them.

I want to give permission based on Taxonomy term.

I think I will probably need to do bit of coding.

Help?

I have used the Taxonomy Access module before and it should work for what you need to do here.

I'm making some assumptions here:

1) You have a vocabulary called "Country" and "United Kingdom" is a term in that list.

2) You have a field of type "Term Reference" on your content type(s) and it using the "Country" vocabulary.

3) You have a field of type "Term Reference" on your account settings - /admin/config/people/accounts/fields and it using the "Country" vocabulary.

Now, make sure your permissions are set properly:

1) go to /admin/config/people/taxonomy_access

2) "edit access rules" for the "authenticated user" to get to this page:

3) Under "New" you need to select the term you want to manage access for. Hit the "Add" button.

4) Once added, the term with show under the "Tags" heading in the table. I am using the "Tags" vocabulary here, but yours will say "Country".

5) Now you can modify the permissions for View, Update, Delete, Add Tag and View Tag. There is an explanation of these fields as well as how to manage the permission on the bottom of that page, so I wont include it here.

After you have done this, you can login as an authenticated user and the permissions configured above will control the access to your content.


Pending approval mail not sent Am using the register module to create an alternate registration page which requires admin approval. The pending approval mail is not sent to the user registering through the page.

Wish someone could help me here. I've also created an issue in the module page. Thanks

The problem is not with the module. The pending approval mails are not sent even registering with default drupal path while rest of the mails are delivered.

Check these variables:

user_mail_register_admin_created_notify
user_mail_register_no_approval_required_notify
user_mail_register_pending_approval_notify
user_mail_status_blocked_notify
user_mail_cancel_confirm_notify
user_mail_status_canceled_notify

Use drush (drush vget user_mail_register_no_approval_required_notify) or install Mail Control; This module provide only interface modifications. The underlying functionality is already there by default in Drupal 7.

You can also drop in settings.php:

$conf['user_mail_register_admin_created_notify'] = FALSE;
$conf['user_mail_register_no_approval_required_notify'] = FALSE;
$conf['user_mail_register_pending_approval_notify'] = FALSE;
$conf['user_mail_status_activated_notify'] = FALSE;
$conf['user_mail_status_blocked_notify'] = FALSE;
$conf['user_mail_cancel_confirm_notify'] = FALSE;
$conf['user_mail_status_canceled_notify'] = FALSE;


Cache warming for logged in user roles I have 2 pages that are highly customized per user, and I happen to know exactly when certain users are going to log in (this site is used by students during classtime). I have APC and memcache helping, but they are basically worthless here since my users hit these pages once or twice right at the beginning of their session and don't often return, but may spend over 10 seconds waiting for the page to generate when 40 users all log in at once and try to get the different versions of the same page.

I plan on significantly redoing these pages to make them less resource intensive, but for the moment, I'd love to be able to schedule a cron job to do a cache warm 10 minutes before class starts so they have a better experience sooner. Is there any way to do a cache warm for pages that are custom per user when I don't have their password?

You can use drush user-login together with curl (or wget) like this:

drush --uri=http://your-site.com/drupal-dir-if-any/ user-login --browser=0 username path/to/heavy/site | xargs curl -L

The drush user-login command prints a one-time login link of the following form:

http://your-site.com/drupal-dir-if-any/user/reset/1/1390809497/hzqAmTzHMdBIXDIrkbDsmLIyPQtcDnjAufz9Fd5OUJk/login?destination=path/to/heavy/site

Then xargs will pick it up from stdin and passes it as last command line argument to curl. Finally the -L flag instructs curl to follow redirects. You might want to also supply -o /dev/null in order to discard the output of curl.


How do I download an image/file to a specified location on the disk? I want to provide the functionality to the users to download the images/files to their system but not with direct download but with a dialog where they tell the location where they want to download the image.

I have tried the download_file and file_force modules. Both modules provide the field formatter to download the image. but when the user click on the download link the the image directly downloads, it does not provide the option to the user to specify a location for the image to be downloaded in.

Is there any other module or any other method?

This behavior is largely up to browser itself, and this can't be controlled over how the browser has been configured.

Above settings are from Google Chrome browser. If user has checked "Ask where to save each file before downloading" checkbox, then browser will prompt to choose location else download to default location set in "Download Location".

Instead try educating the user before they download. That's the best way.

Ref : Prompt user to save file to a specific location


How to theme nodes in views based on the author's role? I have a view listing all recent blog posts that have been published on the website.
These blog posts can be created either by regular authentified users or by staff members.

I need nodes published by staff members to be themed differentely to be highlighted.

Luckily, Views allows you to add custom row classes through its admin interface, so you can style your view rows according to any field in that row.

Here is what I'd do, in your case, to add a 'staff-author' or 'user-author' class to your view row, depending on who wrote the blog (I'm just assuming those are the roles associated with your two user groups - they may be something else ;-)).  Once you've added such a class, you can add css in your custom theme to style those differently.

Add a 'user' relationship to your blog view.  Under the "Advanced" section of your view, add the following relationship: "User: Content authored".  Now you'll be able to add fields from the node author to your view (even if you don't display them)
Now you can add the 'User: Roles' field to your view - just make sure to select to use the User relationship you've added when configuring the field. You can check to not have it display too!

Finally, now you can edit your format settings to fill in a custom css class, based on any field you choose (from the 'Replacement Pattern' options for your view).  In your case, it would be [rid-role].

Now, inspect the html of your view using Firebug (or something similar), and your view rows should have the new css class filled in, depending on the role of the node author.  Use that to style the entries differently!


Including call to drupal_get_form('user_login') causes seemingly endless loop in Firefox One of the features that I've tried to include in my Drupal site is a persistent login form in the page's footer. After doing some searching around, I found that the best way to call the login in Drupal 7 is the following:

print drupal_render(drupal_get_form('user_login'));

So, I put this in a simple if/then statement that looks like this:

<?php
global $user;

    if ( $user->uid ) {
        echo "Go to Admin area.";
    }
    else {
        print drupal_render(drupal_get_form('user_login'));
    }
?>

I then tucked this away in a jQuery accordion, and it was working just wonderfully in Chrome.

Then came Firefox. It loaded fine the first time, but then once I clicked on the accordion to view the login, it never loaded correctly again. I know that this is the culprit, because once commented out, the page loads fine in Firefox. Am I doing this call wrong?

Here's what ended up working. After debugging, Firefox (and my mountains of code) was having an issue with the core module OpenID. I assume that since it only recently became an issue that it's a particular problem for my particular framework.


Drupal configuration on non root url (how to change $base_url)? sorry for my english, I'm french

ok, that's I want to do is to install my drupal site on a url like :
www.mymachine.fr/mydrupal/

and the problem is that when I go this url,
he dispatch me to www.mymachine.fr/core/install.php
instead of www.mymachine.fr/mydrupal/core/install.php

so the install doesn't work

My conf is like this : debian server

in drupal file "sites.php", I have this :

$sites['mymachine.fr.mydrupal'] = 'mydrupal';

on /etc/hosts, I add this line  :
    127.0.0.1    mymachine.fr.mydrupal

on /etc/apache2/sites-available/000-default.conf :

<VirtualHost *:80>
    ServerName mymachine.fr.mydrupal
    DocumentRoot /var/www/mydrupal/CORE-DRUPAL8-WEB/web

    ServerAdmin webmaster@localhost

    # Log configuration
    ErrorLog ${APACHE_LOG_DIR}/drupal-error.log
    CustomLog ${APACHE_LOG_DIR}/drupal-access.log combined

    <Directory "/var/www/mydrupal/CORE-DRUPAL8-WEB/web">
            Options FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>

</VirtualHost>

SO I don't know if it's drupal configuration or apache configuration to change $base_url from drupal site ...
thanks a lot

If your drupal installation resides on the webserver in a subfolder of the webroot for www.mymachine.fr, you can set the base path in the drupal site's .htaccess file.

Find the line that reads # RewriteBase /drupal
Uncomment it by deleting the "#" RewriteBase /drupal
Edit it to reflect your subpath/subfolder # RewriteBase /mydrupal

That block should look like this after the edits.

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

Then, reset your .conf (vhost entry) to reflect just the top level website (code sample below resets to default .conf setup):

<VirtualHost *:80>
  ServerName mymachine.fr.mydrupal
  DocumentRoot /var/www

  ServerAdmin webmaster@localhost

  # Log configuration
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  <Directory "/var/www">
      Options FollowSymLinks
      AllowOverride All
      Require all granted
  </Directory>
</VirtualHost>

This setup presumes that your top level domain does not have any redirection rules that forward/process all requests (such as the rules in an out-of-the-box Drupal or Wordpress .htaccess for processing requests with index.php)  If your top level domain has such a redirect rule in place, you may need to add another rule to exclude your mydrupal subdirectory.


How to remove tag from SelectQuery object I process SelectQuery object using hook_query_TAG_after() or hook_query_alter().

I want to remove 'mytag' tag, which has been added as $query->addTag('mytag') somewhere else. Apparently, neither SelectQuery, nor QueryAlterableInterface has appropriate interface method.

Is there any means (besides SelectQuery subclassing) that I can use to remove a tag?

The reason may be the following (thanks Clive for asking):

I want to make a decision based on (expected) record set size inside hook_query_TAG_after()

I could do $countQuery = $query->countQuery(); $total = $countQuery->execute()->fetchField()

But, the cloned query will have same tag as original one and execute() will invoke the same hook ad infinitum.

I still can not find a way to remove a tag from query, but I found solution for my case of count query. The idea is to use another tag to stop endless recursion:

function mymodule_query_mytag_alter(QueryAlterableInterface $query) {

  if ($query->hasTag('counted')) {
    return;
  }

  // Prepare count query
  $countQuery = $query->countQuery();
  $countQuery->addTag('counted'); // Abort hook recursion

  $tables =& $countQuery->getTables(); // Query may have sub-queries

  foreach ($tables as &$table) { // Tag all subqueries
    if ($table['table'] instanceof SelectQueryInterface) {
      $table['table']->addTag('counted'); // Abort hook recursion
    }
  }

  $total = $countQuery->execute()->fetchField(); // execute() will initiate recursion!

 // Rest of processing

}


Rule action to remove a product from the cart? (using the commerce module) I'm using the commerce module to show product in a site.

I need to create a rule on the event of Calculating the sell price of a product which should involve removing products from the cart in a given condition.

I see that there is an action to Add a product to the Cart. But how do I remove a product from the cart?

Should I use the Remove from list action?

Check what rszrama, the Drupal Commerce leader, says about this:

  If you find and delete the line item, it should work just fine. You can do this with the "Delete entity" action. You could also just unset the price of the line item you want deleted during "Calculating the sell price of a product." That's what the "Unset the price of disabled products in the cart" default rule does, so you can refer to it for an example. Unsetting the price just involves setting the amount to NULL (i.e. no value, not 0).

http://drupal.org/node/1267156#comment-4937288


How to display node number in content items that only show up to administrators on ALL content items? Evertime I need to node number I need to go to content items and hover over it, memorize and use it after...

Is there a way to have the node number displayed on the content item, but only to administrator.

Is there a module for this? Or would I have to create a custom field with a token and add it to every display...?

I need it to create links on menu items, to assign blocks to specific
nodes, to create links to content items in articles ect...many
reasons!

You're going the wrong way about this. Having your urls named node/1, node/2 etc.. looks ugly and it's bad for SEO.
What you need to do is give your Content Types an url alias. You don't want your How To Use Drupal article url to be node/1. You want it to be /articles/how-to-use-drupal
You should use the Pathauto module. This module allows you to automatically create an url alias using tokens.
Then when you assign a block, you can use articles/* this will make the block show up on all articles urls.
Pathauto Video Tutorial

I knew about path auto, I just thought it was better practice to use
node items for links and so on, in case I change the page name later,
node number never changes...

You can use the redirect module which will auto redirect the old path to the new path if you change the path name. Thus, you don't have to worry about updating links.
To make life easier, I would also recommend
CKEditor Link - A plugin to easily create links to Drupal internal paths


How do I explain the large difference between page execution time and reasonable query execution time? I believe that one of my websites is running rather slowly.  I have done nothing different than I have on other Drupal websites that I have done that are running on different servers and that are running much faster.

Would this "slowness" be somehow described by the fact that the page takes 4 times longer to load than it does to actually execute the SQL queries?

  Page execution time was 2251.03 ms. Executed 342 queries in 477.02 milliseconds.

If you see above, you can see that it takes more than 4 times longer to execute the page than it does to actually get the data it needs to show on the page.

I have another site that is nearly identical and I have much faster load times:

  Executed 241 queries in 108.32 milliseconds. Page execution time was 1065.35 ms.

What explains the difference between the two sites, and how could I go about fixing the slow site?

Here is an easy calculation:

page_execution_time = query_time + php_time;

So basically you seem to do quite a lot of stuff in php.
Same basic stuff you could do

Use some opcode cache, for example apc
Find out what needs a lot of time using xhprof


Why is the programmatically removed paragraph item still showing after adding a new paragraph to the node? I have a paragraph field in a node with unlimited add paragraph. I am removing these paragraph programatically. Its removing but when I am adding a new paragraph its adding blank paragraph along with.

I am using this code to remove paragraph

use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\Entity\Paragraph;

$ids = \Drupal::entityQuery('paragraph')->execute();
foreach ($ids as $id) {
  $paragraph = Paragraph::load($id);
  if ($paragraph instanceof ParagraphInterface) {
    $paragraph->delete();
  }
}

You have 3 tables doing the job: a table which stores node data, a table which stores paragraphs data, and a table which stores relation about node and paragraphs. Now you emptied the table which stores the paragraphs data, but the node-paragraph relation table is still there. So if you have added 4 paragraphs to a node and deleted that 4 paragraphs, still drupal assumes there should be 4 paragraphs attached to that node.

so if you want to delete them entirely you have to fetch node data which has "paragraph" field value, delete field value from each node and save it.

so here are steps :
you can run a database query on field table, and get all node-paragraph relations. now you have a list of all nodes that have a paragraphs, so having node ids and paragraph ids you can first remove paragraphs from node using a code like this:

$node = Node::load($nid);
$node->FIELD_NAME->setValue(array());
$node->save();

and then delete correspond paragraphs using a code like the one you mentioned. of course you don't need another query as you have paragraph ids.

if you don't mind removing all paragraph values from database and only don't like them to be shown in your node, then you can write an entityquery like this :

$query = \Drupal::entityQuery('node');
$query->exists('field_to_check');//Check A field value is NOT NULL
$ids = $query->execute();

so it gives you all nodes which has value for that field, then you only can run :

foreach($ids as $nid) {
  $node = Node::load($nid);
  $node->FIELD_NAME->setValue(array());
  $node->save();
}


How to scedule a reminder mail for nodes with date field in an oganic group? I would like to enable all members of an organic group to subscribe to a reminder, that sends an e-mail depending on a date field.
To be more specific: The group has a group content with a date field. Now I would like a mail being sent a specific time before this date becomes actual.
Would would the best way to do this?

When it comes to right on schedule or specific time, you need to have crontab on server. Role of cron tab will be none other than calling your cron.php file which in turn allows all modules to set the cron. But this is half of the process since with core drupal cron process you can not have much control on setting schedule time, so you can use elysia cron module to extend drupal core cron.This was cron part

Now inorder to trigger email you can implement hook_cronapi() as an example,

function mymodule_cron_cronapi($op, $job = NULL) {

  $items['send_email'] = array(
    'description' => 'Send email to group users',
    'rule' => '0 * * * *', // Every Hour at **:00
    'callback' => 'mymodule_email_group_callback',
  );
  return $items;
}

cron callback

function mymodule_email_group_callback() {
  // load all group content from that content type.
  // loop through all nodes check date
  // if true
  // get all subscribers and loop through them
  // send email
}


Need to center images in wyswyg block I am trying to center 3 images in a block I have created in my footer but
the images just won't center. I tried the wysiwyg editor's center button, but that did not work. I then tried to put in manual css which failed. I can't seem to get these images to center. I would appreciate any help.

Using:
    CKEditor    7.x-1.13

I tried adding a Bootstrap 3 "center-block" css class, but this does not work either.

© 2014 Environmental Law Alliance Worldwide (ELAW)

U.S. Office: 1877 Garden Avenue, Eugene, OR 97403 USA

Phone: +1 541 687 8454

Fax: +1 541 687 0535

Here is what displays:

Add the "center-block" class to the img tag.


JSON through Services View- Authenticating through Parameters when accessing JSON through external app My Drupal site is generating JSON through Views. I am using Services for that.

It is something like this:-

http://www.asite.com/api/views/all-date.json

Now the problem is that I want to restrict anyone from writing that URL in the any browser and retrieving all data.

Do you think there is a way to authenticate it?

Probably, in my external app, when I am accessing the data, I can add parameters to it so that it can only send data when it has right authentication.

Something like this:-

http://www.asite.com/api/views/all-date.json/?username=me&password=mine

I'll be grateful if you could help.

There exit many ways of authentication through services module.

The easiest is to use session authentication by authenticating the user using his username & password, Then let the app send the cookie header in each request with the session id like COOKIE: SESS_ID:SESS_name.

Or use that module that seems matching your approach a lot services_basic_auth

Another way is to authenticate the app itself by letting the app get an access token using a secret app id and password created on the website.   using oauth2

Examples for auth methods


Best practice for using location names as part of taxonomy? I'm setting up my taxonomy vocabularies for describing my node content. Most of it's fairly straight-forward, but I'm stuck on how to describe the location data for my nodes.

I have a small hierarchy of place names for a limited geographic region that my site covers. Should I continue to use taxonomy to create a vocabulary, or should I be using the location module? I will be having location-specific content in the node, such as a Google Map to show the location of venues etc. Can location module content be tied up to a taxonomy vocabulary?

It depends of your goal:

If you want to cover large areas like cities, it's better to use Taxonomy as it will be easier to build (for example) a view (or map) of all node from this city.
If you want very precise geolocation (like the position of a store in a map), then go for location. Regarding Location module, it may be overkill for simple Lat./Long. positioning and a simple CCK field for each should be enough.
You can of course have both Taxonomy and Lat./Long. for your nodes and use the one appropriates regarding your context.

If you have time, I'll recommend the listening of Acquia Podcast 22: DevSeed On Mapping in Drupal.

  Being able to display maps in Drupal is a powerful feature, and can
  also be confusing to implement. Join us as we talk with Ian Cairns,
  Tom MacWright, and Robert Soden from Development Seed about how it is
  done and the different options available for displaying great maps.


Transition plan for PHP5 abomination to Drupal Background

A year from now my clients are going to port a relatively complex intranet portal service (scheduling, actual tracking and reporting, and more) to Drupal because the head office says so. Very little effort has been made to determine if this is the right technical choice and it is beyond the control of my client's or even their bosses.

The current portal is an abomination that is in the process of being re-factored and I believe the most cost effective plan will be to bring in a domain model layer via Doctrine 2 and put 99.9% of all business & input validation logic into the models, gutting out the abomination until it is a skeletal view & authentication logic layer.

Question

For any Drupal specialist out there, does this seem like a viable approach? Could Doctrine2 play nice with Drupal or does Drupal higher level logic need a much tighter integration to the data?

We have done a few sites where we have connected outside systems to Drupal where the data had to be kept in the outside system.  This is what I spend most of my time working with.

When we do this, we typically create a content type to "stub out" the content in the other system.  The content type only contains the node title and a CCK field for the unique identifier in the other system.  Along with this are a lot of hook_nodeapi functions.  For example, the load hook will call out to the remote system and add the data to the node.  You also need to devise a method for getting the outside data into search results.  There are a few methods for this, but those are too lengthy to get into here.

While there are some downsides, we find this works well and allows normal Drupal stuff like comments, tags, etc.


How to get block instance id in block plugin? I have block plugin that renders lazy builder placeholder. In my lazy builder I need to get to the block's settings so I wanted to set the block id as lazy builder argument but it turned out the block instance info is not available to the block plugin itself.

Is there some proper Drupal way how to get to this information beside serializing the configuration as lazy builder argument or storing the configuration elsewhere?

No there isn't.

Block plugins can also be used in e.g. page manager and then there's no block entity, it stores configurations for multiple block plugins in a single config entity.

So you shouldn't be relying on the existence of that and instead pass in the relevant configuration to your lazy builder.


Get web image url from real path As part of some other functionality I am generating an image in temp folder and But unforunately I'm not able get the web url of image.

$path = \Drupal::service('file_system')->realpath(file_default_scheme() . "://");
$image_path = $path . rand() . '.png';
echo $image_path;

I am getting following as path

C:\wamp\www\www_d8test1_com\sites\default\files30605.png

How can I add slash before image name and get actual weburl of image like below?

http://www.d8test1.com/sites/default/files/30605.png

You can check out the file_create_url() function that creates a URL for your file.

So, based on the code in your question, it would look like:

// Generate or get the image uri.
$image_uri = file_default_scheme() . "://";
// Create the url from the uri.
$image_path = file_create_url($image_uri);


View of nodes and all their taxonomy terms There is a vocabulary which has an additional field 'field_icon'
I have a view that displays nodes of a certain content type.

I am looking to display all the term's field_icon associated with each node.

I have then added the relationship of Content: Taxonomy terms on node and added the field_icon using this relationship. But it is only displaying 1 icon. Not all.

When you look to configure that field, there is no MULTIPLE FIELD SETTINGS option.

How do I display all terms associated with a node in views.

EDIT
See screenshot attached
The vocabulary the field_icon is in is call 'Key Elements'

It would help if you could include a screenshot of your view. But based on your post (I am assuming each term only has one icon), it seems like you may need to aggregate your view. If this is a Drupal 7 site, I also recommend using the module Views Merge Rows, which allows you to choose a separator for when there are multiples after grouping.


DeployAuthenticationException: Authentication error when try to push the content I have two sites on my localhost registration and testing. I want to push the content (node having type article) from testing to registration.I am using Deploy module to do this, by following this procedure.
"https://www.drupal.org/node/1406134"

Everything is OK until I click "Deploy" on testing. When I do I get the following error:

my path to endpoint is "/services/rest. and I also visit here
Authentication error when deploying site's content

but my issue still open.

I was having the same issue and I solving applying this patch: https://www.drupal.org/node/2017767#comment-7773329

Hope it helps!


Root term in Pathauto only works for child terms? My taxonomy structure looks like this:

Film
- Short film
- Special film

Using Pathauto, I would like the url to always include the root term.

So for nodes tagged with 'film' the path is: film/node-title. For nodes tagged with 'short film' the path is also: film/node-title

I thought the 'root term' token would do the trick, setting pathauto pattern to: [node:field-category:root:name]/[node:title]

But it only works for children. If a film is tagged 'film', the token isn't used for some reason. Perhaps I am misunderstanding the meaning of 'root'?

I encountered the same problem and wrote the patch for token module
Here is patch https://drupal.org/node/2050421#comment-7806099


how to alter exposed form values before submit for filters in drupal7 view I want to do left and right trim when end user enters data in textbox for filter list of rows in drupal 7 views

function example_form_alter(&$form, &$form_state, $form_id) {
 array_unshift($form['#validate'], 'example_request_validate');
}

function example_request_validate(&$form, &$form_state) {
  if (isset($form_state['values']['text_field']) && !empty($form_state['values']['text_field'])) {
    $request_id = $form_state['values']['field_request_id_value'];
    if (strchr($request_id,''))) {
      $request_id = ltrim(strchr($request_id,''), '');
    }
    form_set_value($form['text_field'], $request_id, $form_state);
  }
}


What governs view access? I just built a view to display user information.  I can see this view just fine as a root admin but when I log in as a different user, the view is restricted.

What governs view access?

Is it a compost of all the permissions involved in the data that is being viewed?
If I want to block a user from looking at a view, do I restrict some or all of the content?
Is there a way to set up a permission directly one a view?

There are two things which govern access to views and their results.

The access settings for the view. These are found on the view page and can be based on permissions or roles. This is a base rule for who can see this view.
The access settings for the content being displayed by the view. This is definitely where things get a bit funky. Essentially, views doesn't collaborate with Drupal permissions or hook_node_access(). It will show content users might not have the permission to see or content that has been safeguarded by hook_node_access(). That makes these two methods pretty useless for protecting content.

What actually happens is that views queries the {node}, {user} or other entity table and retrieves nid's, uid's or other entity id's. At no stage does it check permissions or hook_node_access(). However, when checking nodes it does join with the {node_access} table to determine if that system has any rules about the content. Note that hook_node_access() doesn't really have anything to do with the node_access system.

By default you probably aren't using the node_access() system, but if you are using a module like content_access then you are using this system and it may be restricting views results.

If you have devel module installed, you can use the block with the title Devel node access and place it on a node page. Now when you visit that page, it will show the roles and their access level. Note that you need to access that nodes page with a user with that role before it will show in the block. This is the access record which will determine if the node can show in a views result.


Do not translate the admin area / How can I set the language of the admin area to English? I am building a multilingual site with 3 languages. Lets say English, Italian and German. English is the default language. Is it possible to leave the admin area untranslatable, even I am currently seeing the actual site in different language other than the default one, just for the administrator of the site, using a module or custom code?

You could try the Administration Language module. There's only a dev version for the Drupal 7.x branch out currently, but it seems to work well enough (used it in a project myself).


How to use the same EntityListBuilder for entity A and an extended version B I have used the content entity example coming from the example project.

This example define a Contact entity.

Next I have extended this Contact class in an Artist class with some added fields (let say a Bio and a Cv field).

class Artist extends Contact  {

My Idea was to share the list_builder defined in the Contact class in order to get an administrative list showing the Contacts and the Artists at the same place.

To do so, I have those annotations in the Artist class:

 * @ContentEntityType(
  * id = "mymodule_artist",
  * label = @Translation("Artist entity"),
  * handlers = {
  * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
  * "list_builder" = "Drupal\mymodule\Entity\Controller\ContactListBuilder",
  * ...

As you can see, ContactListBuilder is the list builder of the Contact entity... in other words, it is used in Contact and in Artist.

In the routing.yml I have the following

entity.mymodule_artist.collection:
  path: '/mymodule_contact/list'
  defaults:
    _entity_list: 'mymodule_contact'
    _title: 'Contact List'
  requirements:
    _permission: 'view contact entity'

Unfortunately, this is not working at all... the ContactListBuilder shows only the Contact entities; not the Artists. (I couldn't understand why)

After many tries, I drop this idea... My new plan was now to create a view that will show all Contacts and all Artists.

Thus, I added this line in the annotations of the Contact and the Artist classes (in the "handlers" section):

 * "views_data" = "Drupal\mymodule\ContactViewsData",

And here is my ContactViewsData class definition

class ContactViewsData extends EntityViewsData  {
}

As you can see it is empty: it only extends EntityViewsData. In fact I really don't understand what to do in the getViewsData() function. I couldn't find any doc on it (But this is maybe something I should ask in another question)

Anyway, this does the job, and I could create a view (in the UI) for the Contacts and another view for the Artists. But I have no clue on how to create a view that are showing both.

To summarize, my questions are:

Is extending the Contact class (for the Artists) a good idea? Maybe it is much simpler to just add the Artist's fields in the Contact Class.
What is the best way to list a Mix of 2 entities that are sharing some common fields (Ex: Name, Surname, ID,...): Is it a view?
Is it a good Idea to try to use the same ListBuilder for 2 entities (Of course, this Listbuilder will only list the common fields)
Where to find some doc on the getViewsData()` function, or at least, what is the purpose of this function.

Your questions cover quite a few unrelated concepts, but here's an attempt at answering nonetheless.

Create a 'Person' base class and extend that into 'Contact' and 'Artist' classes. This approach will isolate your Artist entity type form changes you need to make to the Contact class and vice versa. Adding a company-field would, as an example, probably not apply to your artists.
I would use a content-view with a filter, only showing contacts and artists types. Re-using common fields on the 2 entities will make creating such a view a no-brainer.
Afaik the parent list-builder class does not support multiple entity types. The constructor for the list-builder class, accepts $entity_type as one of its arguments, so unless you write your own list-builder, you are limited to 1 type per list.
The getViewsData() method exposes properties from your entity type to the views api. Extending the EntityViewsData class, like you did, auto-generates the view-data through the inherited methods. Core provides some usage examples; e.g. UserViewsData. Use your IDE to search for "extends getViewsData()" for more examples.


No error messages from validate? I'm creating a simple contact form and it works flawlessly, besides the validation.

When I try to exercise the validate function, no error messages are shown. The text in the correspondent field turns red, so that works, but where is the messages?

If I fill in the form correctly and the mail gets sent, messages are shown just like they should.

Here's my code:

function mymodule_buysell_contact_form($form, &$form_state) {
    // The form

    $form['contact'] = array(

        '#title' => t('Skicka ett meddelande till säljaren'),

        '#type' => 'fieldset'

    );
    $form['contact']['message'] = array(

        '#type' => 'textarea',

        '#title' => t('Meddelande:'),

        '#cols' => 35,

        '#rows' => 6,

        '#resizable' => FALSE

    );
    $form['contact']['name'] = array(

        '#type' => 'textfield',

        '#title' => t('Ditt Namn:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['compname'] = array(

        '#type' => 'textfield',

        '#title' => t('Företag:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['phone'] = array(

        '#type' => 'textfield',

        '#title' => t('Telefon:'),

        '#size' => 35,

        '#maxlength' => 30

    );
    $form['contact']['cellphone'] = array(

        '#type' => 'textfield',

        '#title' => t('Mobiltelefon:'),

        '#size' => 35,

        '#maxlength' => 30

    );

    $form['contact']['mail'] = array(

        '#type' => 'textfield',

        '#title' => t('Din E-mail:'),

        '#size' => 35,

        '#maxlength' => 30

    );

    $form['contact']['captcha'] = array (
        '#type' => 'captcha',
        '#captcha_type' => 'image_captcha/Image',
    );

    $form['contact']['submit'] = array(

        '#type' => 'submit',

        '#value' => t('Skicka')

    );

    return $form;
    }

    function mymodule_buysell_contact_form_validate($form, &$form_state) {
    // Validate message

    $valid_message = $form_state['values']['message'];

        if (empty($valid_message)) {

        form_set_error('message', 'Du har inte skrivit något meddelande');

        }
    // Validate if a name is submitted

    $valid_name = $form_state['values']['name'];

        if (empty($valid_name)) {

        form_set_error('name', 'Du har inte fyllt i ett namn');

        }

    // Validate if a company name is submitted

    $valid_compname = $form_state['values']['compname'];

        if (empty($valid_compname)) {

        form_set_error('compname', 'Du har inte fyllt i ditt företagsnamn');

        }
    // Validate phone by look for numbers

    $valid_phone = $form_state['values']['phone'];

        if (!is_numeric($valid_phone)) {

        form_set_error('phone', 'Ditt nummer verkar inte vara korrekt ifyllt (endast siffror)');

        }
    // Validate cellphone by look for numbers

    $valid_cellphone = $form_state['values']['cellphone'];

        if (!is_numeric($valid_cellphone)) {

        form_set_error('cellphone', 'Ditt mobilnummer verkar inte vara korrekt ifyllt (endast siffror)');

        }

    // Validate the mail, using Drupals own function

    $valid_email = $form_state['values']['mail'];

        if (!valid_email_address($valid_email)) {

        form_set_error('mail', 'Din Epost verkar inte vara korrekt ifylld');

        }
}

For fieldsets I think you have to include the parent as well.

Try changing

form_set_error('phone', 'Ditt nummer v....
to

form_set_error('contact][phone', 'Ditt nummer v....

You can read more here: http://drupal.org/node/678816


Theme hook not found I have a custom module that implements a webform handler. I'm seeing this error in my Watchdog log when I navigate to admin/structure/webform/manage/myform/handlers:

  Theme hook webform_handler_myform_form_handler_summary not found.

I must have missed something when creating my module, but what? What needs to be added? Searches for "webform handler theme hook" haven't been fruitful.

As seen in webform_example_handler

You need to add:

mymodule/mymodule.module

<?php

/**
 * @file
 * Provides a custom webform handler.
 */

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'webform_handler_myform_form_handler_summary' => [
      'variables' => ['settings' => NULL, 'handler' => []],
    ],
  ];
}

mymodule/templates/webform-handler-myform-form-handler-summary.html.twig

{#
/**
 * @file
 * Default theme implementation for a summary of an example webform handler.
 *
 * Available variables:
 * - settings: The current configuration for this email handler:
 *   - message: The message.
 *   - debug: Debugging flag.
 * - handler: The handler information, including:
 *   - id: The handler plugin id.
 *   - handler_id: The handler id.
 *   - label: The handler label.
 *   - description: The handler description.
 *
 * @ingroup themeable
 */
#}
{% if settings.debug %}{{ 'Debugging is enabled'|t }}
{% endif %}
Message: {{ settings.message }}

Clear/flush the cache so your new hook & template file gets picked up.


How to access database table with drupal 7 I am quite new to Drupal. I am creating custom module which connects to the database table. I have gone through the API documentation and created a test function and tried db connect, but there seems to be an error. This is my code:

function first_db_insert() {
  db_insert('imports')
    ->fields(array(
      'name' => 'Groucho',
      'address' => '123 Casablanca Ave.',
      'phone' => '555-1212',
    )
    )
  ->execute();
  drupal_set_message('database updated');
}

If you have an autoincrement value for the primary key on the table you are inserting, then the execute() function will return you this increment value. So just check what it is returning.
But do make sure the value is defined as an autoincrement (defined as serial in hook_schema) because otherwise the returned value should not be used as it is undefined.

$nid = db_insert('node')
  ->fields(array(
    'title' => 'This is only a test.',
    'uid' => 1,
    'created' => time(),
  ))
  ->execute();
// This will ouput the $nid value to Drupal log.
 watchdog('yourmodule', "The value for nid is $nid .");


How can I add a caption to my navigation menu? How can I add a caption to a navigation menu in Drupal 6?  I am trying to achieve this effect:

function MYTHEME_menu_item_link($link) {
  // Debug:
  // dpm($link);

  // Check menu item localization settings:
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }

  // Target the desired menu:
  if ($link['menu_name'] == 'primary-links' && $link['options']['attributes']['title']) {

    // Theme menu item description:
    $desc = '' .
      check_plain($link['options']['attributes']['title']) .
    '';

    // And title:
    $link['title'] = '' .
      check_plain($link['title']) .
    '';

    // HTML should be enabled:
    $link['localized_options']['html'] = TRUE;

    // Theme the menu item title as a link, then append the description:
    return l($link['title'], $link['href'], $link['localized_options']) . $desc;
  }
  // For other menus:
  else {
    return l($link['title'], $link['href'], $link['localized_options']);
  }
}

Place this into your theme's template.php
Don't forget to flush your Drupal cache at admin/settings/performace (D6)


How to get a second join into hook_views_data? I am trying to make the value of a string (name) found in mymodule_names.name available to Views by means of hook_views_data().

To get the name, I need to first look up the nid of the node I want to view in a table named mymodule.  This tells me the email-address of user who authored the node.  Then I need to look up the email address in the table mymodule_names, by finding the row where the same email address is in the column mymodule_names.email. What I want returned is the user name attached to that email-address, which  the value of mymodule_names.name in the same row.

The code below is how far I have been able to get. This makes the value of mymodule_names.email available - but getting that is just an intermediary step.  I think I need a second join to get the user name. I am unable to figure out how to do do that.  How should I modify this code to get the data from the second table?

/**
 * Implements hook_views_data().
 */
function mymodule_views_data() {
  $data = array();
  $data['mymodule']['table']['group'] = t('MyModule');
  $data['mymodule']['table']['base'] = array(
    // This is the identifier field for the view.
    'field' => 'nid',
    'title' => t('MyModule'),
    'help' => t('Table contains ...'),
    'weight' => -10,
  );

  // This table references the {node} table. The declaration below creates an
  // 'implicit' relationship to the node table, so that when 'node' is the base
  // table, the fields are automatically available.
  $data['mymodule']['table']['join'] = array(
    'node' => array(
      // Primary key
      'left_field' => 'nid',
      // Foreign key
      'field' => 'nid',
    ),
  );
  $data['mymodule']['nid'] = array(
  'title' => t('Title'),
    'help' => t('Help.'),
  );
  // Join with the email field.
  $data['mymodule']['email'] = array(
    'title' => t('Email'),
    'help' => t('Author email.'),
    'field' => array(
      'handler' => 'views_handler_field',
      // This is used by the table display plugin.
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  return $data;
}

(This is a non-standard setup where node.uid cannot be used to get the node author UID.)

I know how to get the name by inserting a subquery with hook_views_query_alter() (see: this answer). The question is about doing without using subquery.

$data['mymodule']['table']['join']['node'] = [

  //Second table for Join

  'left_table' => 'foo',
  'left_field' => 'nid',
  'field' => 'nid',
]

more info: https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_data/8.6.x


Is there an anti-spam advantage of using reCAPTCHA module instead of just CAPTCHA by itself? What is the advantage of using the reCAPTCHA module over the plain old CAPTCHA module?

Are spam bots less likely likely to beat reCAPTCHA?

Thanks

The biggest advantages of using reCaptcha is the built in support for people who are visually impaired and the ability to evolve without your intervention. ReCaptcha continuously changes to fight of spam bots.


Block-Placement in a Feature via Context I have got a Feature consisting of a few boxes and a context which puts those boxes in the right regions. That works if I install drupal and my theme and activate the feature.

But it does not work if i install it using drush site-install and my installation profile which contains my theme and my feature. I guess this is because the theme gets activated after the feature and so the feature does not know the regions while activating. What would you recommend to solve this? I could remove my feature as a dependency and activate it manually after my theme in myprofile.install, but is there a "cleaner" approach?

i think doing it in profile.install is clean enough :)
you only set the theme to default in there anyway, dont you ?


User list with View: display only on role In addition to the Administrator role, I've created several roles. I'm still using the Administrator role for users who needs administrator access.

However, in my user list, I've created with Views, I'd like to hide the Administrator role, so it only displays the one role I've chosen instead of listing all the roles associated to the user.

I've already configured a filter criteria where I haven't included the Administrator role and only the roles I'd like to display, but Views disregards this and display the Administrator role.

You can see the members page here: You can see the list here: http://xpeek.dk/sas-members

I hope any of you can assist me in this.

Regards, Frederik

I think you should use Views PHP module. here you can able to write custom code. May be it'll helpful to you.
You want approx this kind of view?

For that you should try View Php Module. After that choose Global Php option in field tag and then write your code. I tried this may be it's not feasible, but here is the code.

In output section:-

<?php
$roles = array();
$user = user_load($row->uid);
$roles = $user->roles;
if (array_key_exists("7",$roles)) {
   // admin role has rid 7
   unset($roles[7]);
}

foreach ($roles as $key => $val) {
 echo $val."<br>";
}

?>


Adding links to $content['links'] in theme layer I know that I can use template_node_view_alter() or template_preprocess_node() in template.php, but the problem is, that some of the information that I can alter there, seems to be processed already. For example:

$variables['content']['links']['node']['#links']['node-readmore']['title']

have some styling informations and a bit of text that is already translated. Is it possible to add a link even before, that structure was constructed? I don't want to overwrite something that was generated by Drupal for specific purpose.

You don't have to worry about overwriting what is there, just don't overwrite anything :)

The correct place for altering links is generally hook_node_view_alter(), as you mentioned.

For adding your own links it is hook_node_view()

As an example see http://drupal.org/node/224333#node_links


How to load a form/page into a div via AJAX? I want to open the create user form (/admin/people/create) into a specific div via AJAX. I can currently open such forms into a modal window using the following link format:
<a href="/admin/people/create" class="use-ajax" data-dialog-type="modal">
    Add user
</a>

Is there any way to load this form/page into a div instead of into a modal window?

Core does not provide an HTML format for non-dialogs, but you can create your own custom format.
mymodule/js/custom-ajax-loader.js:
(function ($, Drupal) {
  Drupal.behaviors.myCustomAJAXStuff = {
    attach: function (context, settings) {
      $("a.use-custom-ajax", context).once('mymodule-ajax').each(function(i, ajaxLink) {
        const $linkElement = $(ajaxLink);

        const elementSettings = {
          url: $linkElement.attr("href"),
          event: 'click',
          progress: {type: 'throbber'},
          element: ajaxLink,
        };

        const myAjaxObject = Drupal.ajax(elementSettings);

        // Declare a new Ajax command specifically for this Ajax object.
        myAjaxObject.commands.insert = function (ajax, response) {
          let target = $linkElement.attr("target");
          $(target).html(response.data);
        };
      });
    },
  };
})(jQuery, Drupal);

mymodule.libraries.yml:
mymodule.ajax:
  js:
    js/custom-ajax-loader.js: { }
  dependencies:
    - core/drupal.ajax

Add the library wherever needed: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal module
Then when you create your link
<a href="/admin/people/create" class="use-custom-ajax" target="#some-div-id">
    Add user
</a>


how to print login_days with user_stats module? <?php print format_date(user_stats_get_stats('login_days', $node->uid), 'custom', 'j'); ?>

Returns "1" always, how to use user_stats - login_days correctly?

As Berdir stated in the comment, user_stats_get_stats('login_days'...) returns a number of days so you can't use this with format_date, also I tried this on my site and if you're the author of the node this function will return nothing, but if you try with other users that have logged in, this should display the number of days since their last access.

In fact if you're only using this module for this function, it may be a little overkill and you should better do this manually:

$u = user_load(31);
print floor((time() - $u->access) / 86400);

Edit: 12/06 11:57
If you want to format the last access date then do:

$u = user_load(31);
print format_date($u->access, 'custom', 'j M H:i');
//will display 12 Jun 12:03 with hour formated in 24H.