Is it possible to programmatically add a path alias to a programmatically created node?

To create the alias, I first check if the alias was set in the user interface, and if it is empty then I set it manually using the label().

use Drupal\Core\Entity\EntityInterface;

/**
 * hook_entity_insert
 */
function mymodule_entity_insert(EntityInterface $entity) {
    // Convert to lowercase, trim spaces, replace spaces with underscore and then truncate to 60 chars.
    $pathTitle = substr(str_replace(" ","_",trim(strtolower($entity->label()))),0,60);
    if ($entity->toArray()['path'][0]['alias'] == "") {
        $path = \Drupal::service('path.alias_storage')->save("/node/" . $entity->id(), "/mynewpath/" . $pathTitle, "en");
    }
}

https://www.drupal.org/node/1853148 for more information


Destination fields not filled from custom migration process plugin

That last part where you are doing the mapping like:

'field_video_upload/video': video_url
'field_video_upload/thumbnail': video_thumb
'field_video_upload/poster': video_thumb

is probably the closest. Is the destination field a multi-valued field? Then you'll need to follow the pattern as espoused in https://www.mtech-llc.com/blog/charlotte-leon/migration-csv-data-paragraphs

You need to create an array of data, then iterator over it and insert each record into the destination.

Namely (this is completely untested, but the idea of it should work if the destination is multi-valued):

   combination:
    plugin: get
    source:
      - video_url
      - video_thumb
  field_video_upload:
    plugin: iterator
    source: @combination
    process:
      video: video_url
      thumbnail: video_thumb
      poster: video_thumb


Hyphenated nodeName or DTD nested in XML causes Feeds XPath Parser failure

There are 2 errors regarding the xml:id and xsi:schemaLocation, but they are not fatal. I'm guessing the xsi namespace is defined previously.

There's nothing wrong with nested namespaces.

Is there a default namespace declare somewhere passed the root? That could be because of https://drupal.org/node/1220834.

The hyphen in EAC-CPF is not causing the problems.

Remember that if elements have a namepsace, the namespace must be present in the XPath query.


You can try these modules :
Commerce Waitlist
 or Commerce Stock Notifications
They allow send notifications if product available again. As for possibility for user to reserve product in stock: without custom module such feature,I think, cannot be realized.


Any easy way to create Login page in Drupal 7

One easy possible way to do this is you can create a node with no content and assign a url "/login" to that node and then assign login block to content region for that page only.


How can I know whether user has logged in through facebook account or through Site login?

You could use Rules module together with Notification module, to achieve what you want. There is no out of the box solution for this problem.

You will have to look into Adding a new rule to react to user registrations
Or to user logins. You will properly have to create a custom module depending on the deepth of what you exactly need


Adding 2>&1

exec('/usr/bin/python script.py 2>&1');

Pointed me to the right direction.

I was writting in a file ( inside the script that hadn't enough permissions )

chmod 666 name_of_the_file.txt totally solved the issue!

Thanks!


Custom Javascript Not Loading On Paginated Pages (Except First Page)

The problem is when using ajax pagination in the view, document.ready isn't called.

Instead you should follow best practice and use Drupal.behaviors instead.

That way, the behavior will run on document.ready and on the ajax refresh.

Try this:

(function ($) {

  Drupal.behaviors.cboxClick = {
    attach: function (context, settings) {
      $(".views-field-field-video").click(function() {
        $(this).parent().find("a.cboxElement").click();
      });
    }
  };

})(jQuery);


Best way to display PDF in drupal as a slideshow

Drupal is essentially a framework, it can't do anything that a 'normal' website can't do. This includes displaying PDF files in the format you want.

The only way is to use Flash (as suggested on the SO post you linked to). This would involve either building the SWF file yourself using Adobe's tools, or using one of the dozens of tools available to build a navigable SWF from a PDF file (e.g. SWFTools).

Drupal only comes into the equation when you actually want to display the Flash file.

Some purists might actually argue that this is a bad idea anyway; you should probably allow your users to read PDF files using the software that they have chosen for that particular job.

If you were trying to DRM your PDF for whatever reason then it might make sense, but as you're providing a download link to the direct file anyway I don't think this applies.


How to theming and deploy custom blocks which created in admin UI?

You can add custom classes or id's to your blocks. If you don't feel to code it yourself your best bet would be to use the Block class module, and perhaps also along with the Block Class Styles module which provides custom templates for your blocks.

--update--

The new version (7.x-2.0) of Block Class module has just changed it database structure, removed the block_class table and add a field css_class into block table. The current version of Block Class Styles module work well with Block Class 7.x-1.2.


You could do this approach in HOOK_form_alter. Depending on validation that you want to remove... I provide you a simple example of required fields: Suppose you have an Image field that it's required, you could make it unrequired using the following:

$form['field_image']['widget']['0']['#required'] =  TRUE;

Also if you want to remove the "Alt field" for a image you could use:

$form['field_image']['widget']['0']['#alt_field'] =  FALSE;


nginx sets content-type text/html on redirect

There is nothing wrong with the redirect having a content type of text/html. On the contrary, it is actually mandated by the HTTP/1.1 specification itself:

  The temporary URI SHOULD be given by the Location field in the
  response. Unless the request method was HEAD, the entity of the
  response SHOULD contain a short hypertext note with a hyperlink to the
  new URI(s).

The cache control header might be confusing Webkit mobile. Have you tried add expires off; inside the location @redirect block?


Is updating the composer.json file & consequently composer.lock in Drupal 8 considered a good practice or hacking the core?

Modifying anything in core is generally not recommended.
Unlike other projects that use composer, Drupal already has its composer packages included in core/vendor and you are not supposed to change them, nor the composer.json. Updates to Drupal 8 core would wipe your changes.

There is a module Composer manager that will open a second vendor directory in sites/sitename/vendor (I think). There is some discussion going on in the issue queue, e.g. Is it okay to have duplicates of symfony, guzzle, etc... in sites/all/vendors?. I imagine a future where sites/sitename/vendor could replace core/vendor. But we are not there yet.

I think you should participate in the composer vendor issue queue, this is all work in progress.

EDIT:
It should be mentioned that the way Drupal 8 is using Composer is not the way it is recommended. The recommended way is that the user should download Drupal and vendor packages via Composer. Instead, it is all pre-packaged. One reason for this is to support shared hosting where you don't have a commandline available, and just want a complete package to upload.


Updating Drupal modules via git on remote server

In my opinion the workflow you mentioned look good. You just need to make sure you have a latest database backup in case you need to revert back.
Have you looked into https://getpantheon.com/ it is free for drupal development. Request an invitation code at https://getpantheon.com/request-code Best thing about pantheon is it provides dev test and live sites, daily, weekly, monthly and on demand backups. Push code from dev to test and live, Pull database and files from live to test and dev with just push of a button.


Theming a custom data table from php code text format with Drupal 7

The format of arguments to theme functions changed in Drupal 7, instead of

$output = theme('table', $header, $rows);

you need to use

$output = theme('table', array('header' => $header, 'rows' => $rows));

or, using a render array,

$build = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);
$output = drupal_render($build);


You can use $form_state['triggering_element'] to find out if and by which element a form was submitted.

That said, I am not sure if what you want to do is possible. When rebuilding the form, you will have to provide all valid form elements and options for them again.

If that query is slow, you might be able to use the caching system instead (That is, unless these options are personalized for the current user).

But maybe I didn't exactly get what you meant, so try it..


How do I access the updated entity after saving with entity wrapper

There's no "preferred" way, as such, but I guess if you're using the wrapper to work with the entity, it makes sense to stick with that convention to re-access it.

Don't forget you've just altered an in-memory object, so regardless of the persistence layer, that object will still have the changes in it.

Once you've done this:

$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

Your changes will immediately be available by inspecting

$node_wrapper->field_textfield

EMWs use the core entity API under the hood, so persistence is actually done through the default entity controller. As such, everything that would happen in calling node_save(), for example, happens when you update the wrapper object.

In practical terms, that means you can save an entity with EMW, and also access the changes on it immediately using an object returned from entity_load(). It's the same underlying object in memory.

I think it's safe to say that context, and even surrounding code/conventions, will often dictate the particular method you use.


Multilingual site, always use language path prefix (no bare URLs)

Here the steps:

Install Redirect module.
Enable the module /admin/modules
Go to admin page /admin/config/search/redirect/settings.
Ensure Enforce clean and canonical URLs is checked.


To answer my own question I guess(better alternatives are more than welcome).

use Drupal\Core\Entity\EntityTypeManagerInterface;

class SomeRepository {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entity_type_manager;

  /**
   * ProductRepository constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entity_type_manager = $entity_type_manager;
  }

  /**
   * @param $node_id
   *
   * @return array|null
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function getNodeComments($node_id) {
    try{
      $node = $this->entity_type_manager
        ->getStorage('node')
        ->load($node_id);
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

    try{
      $comment_ids = $this->entity_type_manager
        ->getStorage('comment')
        ->getQuery('AND')
        ->condition('entity_id', $node->id())
        ->condition('entity_type', 'node')
        ->sort('cid', 'DESC')
        ->execute();
    }catch(\Exception $exception) {
      // log here
      // rethrow error or return, whatever works for you
      return NULL;
    }

    if(empty($comment_ids)) {
      return [];
    }

    $comments = $this->entity_type_manager
      ->getStorage('comment')
      ->loadMultiple($comment_ids);

    $comments_array = [];

    foreach($comments as $comment) {
      // Loop over and get whichever fields you want from the comments
      $comments_array[$comment->id()] = [
        'cid' => $comment->id(),
        'owner_id' => $comment->getOwnerId(), // node to which this comment belongs
        'some_field' => $comment->get('some_field')->value
      ];
    }

    return $comments_array;
  }
}


Create views have field image with multil image style?

You can use Views "Attachment", so you can create main View to display only first two items, then you can create "Attachment" with different markup (remeber to apply this only for current format) and skip first two elements and then attach it to the main view (after it). Sorry for my english ;)


How to remove custom block parent div's?

_block_get_renderable_array function render default block theme where I couldn't remove parent element, So I made it by using module_invoke function:

$block = module_invoke('custom_module_name', 'block_view', 'block_name');
              print render($block['content']);


Do I need BOTH jQuery wrappers or just one?

does the first jQuery wrapper (Code-Wrapper #1) include the Document-Ready function or not (Code-Wrapper #2).

No it doesn't.

  Do I have to wrap the jQuery in BOTH wrappers?

If you need DOM ready, yes you do, but in Drupal 7, they suggested Drupal.behaviors. See https://www.drupal.org/node/756722#behaviors


How to theme the controls of an Openlayer map?

The CSS is mostly contained in the js of the module. You can poke around in the openlayers user lists to maybe find a solution.


Panels Node Add form and passing url parameters

This is an old question but there is an easier way with the Node Reference URL Widget module, which should work with Panels as well.


That might be because of Locale core module. I had the same problem, but when i disabled the Locale module the problem was gone.

You can observe the main cause of the problem. When you look into the duplicate url aliases you will find the difference between the original url alias and duplicate url alias. In the original url alias you will have language = " and whereas with new/duplicate url alias you will find language = 'en'.

Hope this answers your question.


Composer keeps overwriting .htaccess (and other files) every time I do anything

That's Drupal's Composer Scaffold. Listed as "drupal/core-composer-scaffold": "^8.8.0" or a different version in your project's composer.json file.

To prevent certain scaffold files from being overwritten every time you run a Composer command you need to specify them one by one in the "extra" section of your project's composer.json. See the docs on Excluding scaffold files.

The following snippet prevents the .htaccess and the development.services.yml from being overwritten.

"drupal-scaffold": {
    "locations": {
        "web-root": "web/"
    },
    "file-mapping": {
        "[web-root]/.htaccess": false,
        "[web-root]/sites/development.services.yml": false
    }
},

But maybe you want to ensure you always get Drupal's latest .htaccess for security updates for example. For that you don't exclude this file from Drupal Scaffold but you patch it instead. See the docs on Altering scaffold files.

Create a patch of the .htaccess and maybe put it in a folder called "patches" in your project root. Then configure a "post-drupal-scaffold-cmd" in the "scripts" section of your composer.json file to have this patch applied to Drupal's core .htaccess every time Drupal scaffolding is triggered.

"scripts": {
    ...
    "post-drupal-scaffold-cmd": [
        "cd web && patch -p1 < ../patches/htaccess-ssl.patch"
    ]
}


Drupal will hide menu items for paths that users don't have access to. But for this to work, it requires that the access callback for that menu item returns FALSE. If you handle access control in the menu callback instead, Drupal won't know that the user doesn't have access and will display the menu.

A solution would be to implement a custom access control module/function if you can't use any of the existing for the nodes.


Hide a region from a specific node? (Without CSS)

Try doing it via hook_page_alter

  Perform alterations before a page is rendered.

  Use this hook when you want to remove or alter elements at the page
  level, or add elements at the page level that depend on an other
  module's elements (this hook runs after hook_page_build().

You can then get the page you are on by calling menu_get_object without parameters and inspect the returned node object.

Add this code to your theme's template.php file:

function MYTHEME_page_alter(&$page){
  //dpm($page);
  if ($node = menu_get_object()) {
    if ($node->nid == 72) { // pick your node or add a condition to your liking
      // remove sidebar first region
      unset($page['sidebar_first']); // remove the regeion here
    }
  }
}

If your theme depends on it, and depending on the region you are removing, you should also implement template_preprocess_html and adjust your body classes so that they are in sync.

As to the CSS, dispay:none as a css rule should remove the element from display, whereas visibility:hidden hides an element, but it will still take up the same space as before. CSS Display and Visibility


Use a preprocess function to populate $title_suffix. It belongs in a file called template.php in your theme folder.

Here's a primer: Setting up variables for use in a template.

A basic example that populates the variable $foo and makes it available to page.tpl.php (Drupal 7.x):

<?php
function THEMENAME_preprocess_page(&$variables) {
  $variables['foo'] = 'bar';
}
?>

The core module Contextual links populates $title_suffix in its implementation of hook_preprocess(). View source at modules/contextual/contextual.module for an example of how it is done.


Drupal Deployment to Dev & Prod and Git Code Repository Setup

CI (continous integration) can contain many moving parts during deployment and code pushes. But instead of using all of it, which isn't necessary for every site, I've come up with the following setup:

2 environments: Dev and Prod domains
Code revisions gets stored in the git servers
2 git branches: dev and master, the master branch is the prod server code.
Each developer will have their own local servers for testing and coding on their laptops.
Each developer checks out the dev branch.
Master (prod) branch should only be touched when dev is tested. Then, merge dev into master.
Once a push to the Dev branch is detected, script on server will auto 'git pull' to get new changes.
Once a merge with dev + master, script on server will auto 'git pull' to get new changes into prod.
Drupal files content will be managed by the "Stage File Proxy" module without the need to download all files.
Database will be synced by downloading a copy from the dev server with "drush sql-dump"


Benefit of loading JavaScript in template.php rather than the theme info file?

No real advantages.

There are two reasons to add Javascript : to make some elements work, or to make them look cool.

JS to make something work

These should be #attached to the element they make work. Preferably in the module that created said element. Or they may be written in unobtrusive way and put in info file of this module. Either way, they should never be put in theme, makes no sense to have them there. So these should be out of your question's scope.

Eye candy

These belong to theme all right. And because they do, they shouldn't depend on any script that's in module. If you have a rare situation when they do, then you need to add them in PHP for conditionals that'll cache and not waste browser's resources. But you told no conditions, so this is moot. Or should be, if your theme just assumes presence of modules without checking you have serious bug there, problems waiting to happen.

Having them added in PHP allows some reordering etc. In my experience it was always easier to write my JS in a way that didn't require this. Drupal Behaviors are good for this. If for some reason you can't write your scripts in order independent way, ie you have to use external scripts or have no time for rewrite, then #attached is the way to go.

Other "advantage" would be to attach them only to elements that are supposed to get their cool effects. But this rarely is an advantage. If all you need is to make sure JS is included, include it always. Better for caching and it'll act only on elements with specific id or class anyway, no real harm for browser. Exception here is when you need to take some php variables and make them avaliable to Javascript. Then info file will obviously not suffice and you need to add it via php.

TL;DR

Your intuition is generally good.


How to natural sort by text fields in Views?

As per Views Natural Sort module homepage, you should enable Enable Views Natural Sort Text Field support to make the text fields sortable.
Here are the steps:

Enable Views Natural Sort.
Also Enable Views Natural Sort Text Field support (this will most likely go away in the future)
Navigate to the fields edit page for the field that you wish to enable 1. Natural Sorting on and check "Enable natural sorting."
http://screencast.com/t/eDkW0c6AC This is needed so that we aren't
indexing other text fields needlessly bloating the sorting table. In
the future there may be a separate table for each field, I'll have to
do some performance testing.
When you do that, your fields "Should" be reindexed... at that time. You should be taken to a batch operations screen.
Next you can go to the view you are editing and the option to sort the view naturally should be there. http://screencast.com/t/6XD7oeBtl

Note: When working with fields there is the need to enable fields for indexing. At the point the setting is enabled, the field is indexed and will be ready for use in a view. Follow the following steps to allow natural sorting on text fields:


What is the correct way to translate variable_get string values entered in admin input fields?

You should use the Variable translation module, part of Internationalization.

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Then, you'll be able to select language for which you are configuring your variable:

Advice taken from this community documentation.


Poll with multilingual choices in Drupal 7

@chabea you are right in asking the question, the answers given in the links above do not explain how to apply the patch on D7. Here is what you need to do:

Under the i18n module created a i18n_poll folder.
Copy the patch to the above folder.
Run the command patch < 1173130_i18n_poll_module_5.patch. This creats two files i18n_poll.info and i18n_poll.module which are all you need to get the poll aggregate module in D7. (I'm assuming you are using *nix operating system and have already enabled the core poll module) You can checkout how to apply a patch in Drupal.
Then go to the poll content type edit page Structure > Content Types > Poll > Edit. In the publishing options - multilingual support section check the Enable, with translation option.

Now go to the poll content type create page Content > Add Content > Poll and create a new poll.
On the newly create poll page there is a Translate link.

The translation page provides a list of language that the poll can be translated to so click on the language of your choice to start translation.

The translation workflow is quite consistent to other modules/content types. Hope this helps.


A Google search for add flash to drupal 7 gives the SWF Embed module as the first result.

You could also look at the Media suite of modules, which can give you a much more user friendly interface at the expense of some additional time invested in figuring out which of the modules you need.


How to test an exception have been logged instead of thrown?

There is no standard test feature to assert a logged message.

The simplest approach is to just install dblog in your test and then inspect the watchdog table for the expected record.

Alternatively, You could write your own log backend that stores it in memory and then access it from there if you don't want to install the necessary database tables in the test.

Or, don't use watchdog_exception() but an injected logger service that you can mock and then configure that to expect the call.


Well after some research I could found the answer. Actually drupal itself do provide such functionality and there is no need to code or ...

When exposing a field as filter to user, in filter settings window a filter identifier can be set (this can't be empty and is filled with field name by default), this is shown in image below :

in above example the identifier is set as cat, in this situation the path sitename/view-address/?cat=term-1 will load the view with my exposed filter assigned as term-1 and corespond entities.


Migrating taxonomy terms when source is a separate table?

The piece I was missing was GROUP_CONCAT for the attachment table. My query now looks like this:

$query = Database::getConnection('default', 'wp')
       ->select('artists', 'a');
$query->join('attachment', 'at', 'a.artist_id = at.attachment_target_id');
$query->fields('a',
          array(
              'artist_id',
              'artist_name',
              'artist_publish_date',
              'artist_bio',
              'artist_record_company',
              'artist_social_links',
          )
        );
//Pull in genres.
$query->addExpression('GROUP_CONCAT(DISTINCT at.attachment_info)', 'genres');
$query->condition('at.attachment_target', 'artist');
$query->condition('at.attachment_type', 'genre');
$query->groupBy('a.artist_id');


Write errors to the log unless the user is an administrator

Using the devel module you can print to the screen errors that you are seeing, but that requires custom work to catch specific exceptions that you expecting to see.


How to create arguments in path with regular page node instead of module, yet pass them to a module

https://www.drupal.org/project/pathauto
will help you on your quest ... to do this make custom fields to collect the arguments then use tokens to replace them...
Edit:
but if your developer is using the front end to create content (nodes) its easy to create path arguments ...
my idea was to make the fields to help generate the "path" ...
then in your module you have to simply load the node then access the fields .. sure there is more ways to do this like look in to the path and explode out the "/" then use them but way easier just to get from the loaded node object.
other than that can you please up date your question to be more clear


What would cause contextual filter settings NOT to save?

In the end, the "simple" answer worked. I deleted the filter and added it back.  I'm not sure if I configured it wrong to begin with or if something "bigger" was at play.


How to properly works in Chrome as a Drupal administrator?

When you clearing the chrome cache it will ask for some options(shows a dialogue box with checkboxes), there you only need to check the Empty the cache checkbox and uncheck all other checkboxes and then click on Clear browsing data. Then it will only clear your browser cache not all chrome data.


Drush and mysql database (with MAMP) connection problem

The problem seems to be in mysql.sock location. I found a solution from here:
http://www.razorsql.com/docs/support_mysql_mac_mamp.html

Short answer

  One way to change the socket location is to edit the MAMP start and stop scripts so that the mysql.sock location is the default. This can be done by editing the following files:

  /Applications/MAMP/bin/startMysql.sh

  /Applications/MAMP/bin/stopMysql.sh

  Replace

  socket=/Applications/MAMP/tmp/mysql/mysql.sock

  with

  socket=/tmp/mysql.sock

How I solved the problem

I did

drush ard -v

to see what was going on.

Executing: mysqldump --result-file /tmp/drush_tmp_1352892897_50a381e13a71d/... --no-autocommit --single-transaction --opt -Q  ... --host=localhost --user=... --password=...
Database dump failed.

So I copied the mysqldump command and copied it to the command line and hit enter.

mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) when trying to connect.

After this I tried several methods to solve the socket issue after I found the solution from www.razorsql.com.


It looks like the Social API stack is the solution going forward in D8:
https://www.drupal.org/project/social_api
https://www.drupal.org/project/social_auth
https://www.drupal.org/project/social_auth_google

Good luck!


How to remove the "Add new Comment" link from book pages

I did get the solution and was able to remove the "Add new comment" link, from the links area. I just went to comment module and commented the following lines of code on line #675.

// Show the "post comment" link if the form is on another page, or
// if there are existing comments that the link will skip past.
if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->comment_count) && user_access('access comments'))) {
  $links['comment-add'] = array(
    'title' => t('Add new comment'),
    'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
    'href' => "node/$node->nid",
    'fragment' => 'comment-form',
  );
  if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
    $links['comment-add']['href'] = "comment/reply/$node->nid";
  }
}

I know it is not recommended to modify the core. I have implemented a hook to remove the link.

Solution found
The following hook in my custom module works for me :)

function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}


$form_state['node'] Values Being Lost in Multistep Node Form After Ajax Click

You need to add a submit handler that has

$form_state['rebuild'] = TRUE;

Otherwise the form will actually submit, and the form_state values will be purged.


How can I create 301 redirects from "unclean" URLs?

The warning you're seeing is generated by the Redirect module when you try to redirect from a path (the part without the query string) which is already a valid Drupal path, which is true for your case (your redirect's source path is the site root, /): https://git.drupalcode.org/project/redirect/-/blob/8.x-1.x/src/Plugin/Field/FieldWidget/RedirectSourceWidget.php#L68. The query string is ignored in this validation step.

Without a query parameter, this would "cover up" the existing path and make it inaccessible, which is why the warning exists. But since your redirect does specify a query, this isn't a problem - the redirect only happens if the query matches ?page_id=123.

The warning should be safe to ignore; your initial approach was likely correct.


Try Webform, to create many flexible forms. Here is a quote about it (from the module's project page):

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


How to use Facebook Connect's user picture in Views?

I found a solution: You can use the following hook to copy facebook's user image and save it as drupal user image. Make sure to ask your users to allow this!

/* Copy facebook image if no user image is present.
   See: http://drupal.org/node/1764176 */
function custom_api_user_login (&$edit, $account) {
  $fbuid = fbconnect_get_fbuid();
  if(is_null($account->picture) && $fbuid && isset($account->data['fb_avatar']) && $account->data['fb_avatar']){
    #$test = fbconnect_user_picture_override(array('fbuid' => $fbuid, 'account' => $account, 'size' => '25'));
    #drupal_set_message(print_r($test, true), 'status', true);

    if(copy("http://graph.facebook.com/".$fbuid."/picture?type=normal", '/tmp/'.$fbuid.'.jpg')) {
      $path = '/tmp/'.$fbuid.'.jpg';
      $file = new StdClass();
      $file->uid = $account->uid;
      $file->uri = $path;
      $file->filename = $fbuid;
      $file->filemime = file_get_mimetype($file->uri);
      $file->filesize = filesize($path);
      $file->status = FILE_STATUS_PERMANENT;
      $dest = "public://" . $fbuid.'.jpg';
      $file = file_copy($file, $dest);
      file_save($file);
      $edit['picture'] = $file;
      user_save($account, $edit);
      #drupal_set_message(print_r('<img typeof="foaf:Image" src="'.$path.'" alt="Naomi Yoshida">', true), 'status', true);
    } else {
      drupal_set_message(print_r('Kopieren schlug fehl', true), 'status', true);
    }
   }
}


Can i port theme settings also in a feature

Theme settings are usually stored as a variable, which is exportable with strongarm. Note that some things in the theming system is cached.


Show exposed pager as links instead of select box

Hope this will help, Use Better Exposed Filters
go to settings of better exposed filter


First of all, you say:

  I have started overwriting Twig files in Drupal 8.

I hope you mean "overriding" Twig files.

Rule #1: Don't hack core.

Secondly, as leymannx suggests in the comment above, this is better accomplished using Views rather than in a Twig template.


"Undefined index" error for field which is defined

First thing to note is you're seeing notices, not errors. Notices are a less severe type of PHP error. It's an alert that notes script execution is continuing, but something is wrong that could be a bigger problem. In your case, the array element $fields['field_video'] doesn't exist,
thus trying reference a property $fields['field_video']->content on a non-existant object causes PHP to fire off notices.

As Geoff mentioned, this can occur if your view rows are loading nodes that don't produce this field and throwing an isset($fields['field_video']) && in your if statement should fix your template from making bad references.


Views count grandchildren with specific value

EDITED

The end result of this will be a view using the organisation NID showing property with the number of claims.

ie. on an organisation's node, this would be the block.

Property 1 -  18 (open claims)

Property 2 -  13 (open claims)

Step 1: Grandchildren.

Add your regular group ID contextual filter.
Add the relationship, OG membership: Group Node from OG membership.
Add it to your contextual filter as its relationship. This gives grandchildren.
Filter out Property content type.
Add property entity reference as a field.

You now have a all properties with all claims.

Step 2: Counting

Try Views Aggregation in Advanced. It will probably cause an OG error.
Instead, install Views Merge Rows. https://www.drupal.org/project/views_merge_rows
It will add a new option under Advanced in your view.
For title, Count merged unique values.
For property entity ref field, Use values as a filter.

Now you should have something similar to my example above.

Step 3: Filtering to OPEN

Add a relationship for that field. I just tried it with a taxonomy field but a Boolean should be similar.
Add a filter, eg. (term from field_hello) Taxonomy term: Term ID (= 90210)

Adapt the filter to what you need or use the general idea to create your own solution.


Is there an optimal method to grant permissions for a newly added permission defined by hook_permission?

The only reason Drupal would not know of the new permission is because it hasn't yet registered your hook. This would only happens after a cache clear.

I would not advise to run a full cache clear before an update (as that might well invoke code that will expect the update to have been run already). Maybe you could get away with clearing the cache of hooks in module_implements. You could call this in your hook_update_N before setting the role:

module_implements('permission', FALSE, TRUE);

But even that feels a bit risky ; it is best not to interfere with the way things run, you might end up with debugging headaches.

Otherwise I don't think there is a perfect solution. Drupal just doesn't have a 'post-update' style hook. You could implement such a hook yourself (maybe using a variable_get/set and hook_init ; or as a drush script as you suggest), however this feels like a complicated way to do what could otherwise be done with a simple SQL query.

If you know your target uses an SQL database, then I think that, while not entirely satisfying, the SQL insert statement is the simplest solution.


AJAX callback issue when using 'Manage Form Display' and 'Manage Display'

Well, I feel like a fool as the answer was actually simple... I had forgotten about switching all input elements to actual button elements. This broke any AJAX request only when the type was a submit button.


The Drupal way of adding HTML syntax within hook_redirect_alter

Since you cannot specify a 301 redirect in javascript, here is what I did all within hook_redirect_alter() :

function mymodule_redirect_alter($redirect) {
  // If checkbox is set then use URL parameter for redirect, otherwise ignore everything
  if (variable_get('my_checkbox', '') == '1') {
    $params = drupal_get_query_parameters();
    $my_parameter = variable_get('my_parameter', '');

    // Append redirect values seperated by commas if the specified parameter exists
    if (!empty($params[$my_parameter])) {
      $refs = $params[$my_parameter] . ',' . $redirect->source;
    }
    // Otherwise add souce as the value of the parameter
    else {
      $refs = $redirect->source;
    }

    // Create parameters to append to URL
    $params = array('query' => array($my_parameter => $refs));

    // Do the actual redirect with this new parameter
    drupal_goto($redirect->redirect, $params);

    // This kills sever-side redirect
    exit();
  }
}

So the URL mysite.com/original_page will be redirected to a page with URL mysite.com/mypage?redirect=original_page


How do I change pager (# of items) for one page display in a view?

I guess I answered my own question, when I clicked the left side Use pager:Display a specified number of items it let me select if I want to override for just that display.


Drupal hash salt / private key is changing?

drupal_get_hash_salt() is either:

a manually-entered value stored in your settings.php
...or (by default) a hash of your serialized-DB config

drupal_get_private_key() is either:

a stored variable called drupal_private_key if it's set
...or (by default) randomly generated bytes (that are saved to drupal_private_key after generation)

So, either one can change their value if:

You changed your DB config (if $drupal_hash_salt isn't manually set in settings.php).
You've lost/removed drupal_private_key from the variable DB table.


If you intend to remove ALL strings imported through interface translation, you could execute something like this:

// Replace the empty string with your target language code.
$langcode = '';
\Drupal::database()
  ->delete('locales_target');
  ->condition('language', $langcode)
  ->condition('customized', 0)
  ->execute();

You may also want to reset the source file history information, so - if you change your mind afterwards - you can re-import the very same translations:

\Drupal::database()
  ->delete('locale_file')
  ->condition('language', $langcode)
  ->execute();

or

locale_translation_file_history_delete([], [$langcode]);

As the locale module is making heavy use of static caches, you may run above commands in a dedicated process as, e.g. Drush PHP CLI (drush php:cli).


By default, if you have English configured, it is not available as a translation target. However, you are only one checkbox away from enabling that feature:

Go edit English and make it available for translation. This will make English behave as any other language and from then on, you can "translate" to English as well:

All strings will still fall back on the built-in English text (eg. if you also have Hungarian on the site, untranslated strings in Hungarian will fall back on Drupal built-in English text). However when English is used for display, all your overrides will be effective. (Cross-language fallbacks can be implemented in contributed modules now with Drupal 8's service architecture for string lookups).

Source: http://hojtsy.hu/blog/2013-aug-20/drupal-8-multilingual-tidbits-12-english-can-now-be-translated

Result:


Problem was in theme. I change to the site Bartik theme and the problem was gone.

I'm using the commerce kickstart distribution if that helps someone. I run into other issues in the past with the frontpage in this distribution. I just remember that and that is why I thought it could be a problem related to the theme. The theme of this distribution has some lines in the preprocess file and that imho may be the source of the problem.

I my situation I will use other theme since I don't need a responsive theme at all.


Specify which theme to use when rendering a page with drupal_render_page()

I discovered that menu_get_custom_theme() only uses a custom theme if the menu does NOT have a "theme callback". In the case of the batch process, it does have a theme callback: _system_batch_theme().

To specify what theme to use when rendering a batch process, I had to use hook_menu_alter() to change the theme callback to my own.

function MYMODULE_menu_alter(&$items) {

  $items['batch']['theme callback'] = 'MYMODULE_batch_theme';

}

Then I just needed to add a conditional

function MYMODULE_batch_theme() {

  // Use a Custom Theme
  if ($_REQUEST['op'] == 'do') {
    return 'email';
  }
  else {
    return _system_batch_theme();
  }

}

This fixes the problem by specify the custom theme in the theme callback rather than in hook_custom_theme() (which is ignored when a theme callback is present).

Thanks!


How do I set a block title to the title of a referenced node?

In Views, with a block output & Content Entity Relationship set up, in 'Contextual Filters':

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
- Override title (tick this & I used %1 with some text)

which offers "Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc."


Adding an editable field to a custom block module

I believe the block example module should show what you want


Changing color of form html with Javascript

You can try like this (thats's step-one.js file):

(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function (context, settings) {
      $('#step-one').css('color', '#769edd');
    }
  };
})(jQuery);


You should use the serializer service if you want to serialize a Drupal data type (Typed Data API) so that normalization is run properly. This requires enabling the serialization module as pointed out by Alari Truuts, which defines the serializer service.

The serialize method is a little confusing as to what the $context parameter means. For Drupal Typed Data, it requires the plugin id of the data type (EntityAdapter in this case).

$serializer = \Drupal::service('serializer');
$node = Node::load(2);
$data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);


Upgrade drupal using drush: Failed to check available update

As tenken suggested, you might try adding -d for debug to your drush command or -v for verbose.

Beyond that, I suggest trying to set $conf['update_max_fetch_time'] to a higher value (I usually set it to 360). It sounds like you may be running into an issue where fetching the update information is exceeding the timeout.


Event "After cloning a node" by node clone module is not working

Your issue seems to be confirmed by some other users also now.

Comment #9 of that issue contains a patch that might possibly solve it.

Another possible solution (patch) is included in comment #8 of that issue, proposed by the module maintainer. With a comment like "Not sure about the use case ..."

The issue is currently in status "Needs review", so maybe you might (still) have an appropriate use case to get that issue in RTBC status?


How can I find (programmatically) which fields have been edited on a piece of content?

In the node form submit, you can call node_load($node->nid, NULL, TRUE) for Drupal to retrieve the original about-to-be-overwritten node, allowing you to walk the list of fields, and compare them.

I would use sha1sum(serialize($field)) to compare them, as that makes it easy to do regardless of field type.


Why are the regions being highlighted when I mouse over on them?

This is a debugging feature that this theme uses. Disable this line (or similar) in ninesixty.info by adding a semicolon before it.

stylesheets[all][] = styles/framework/debug.css

Then clear caches for example on this page: admin/config/development/performance


Flexslider view with pictures from nodes tagged with a taxonomy term

I suspect the "Multiple field settings" in the view image field configuration. Try to uncheck "Display all values in the same row".


How to display the same node twice in one teaser?

There are a lot of ways you could accomplish that.

One way that seems to match your requirements is using the field collection module.

You could have a multiple value field collection field on your content type and that field collection could have your title, subtitle and image fields.

It depends somewhat on all your requirements though.

For example, this might work very well for your views (like the taxonomy one) if you want both blocks to show one after the other (since you have a view of nodes and these are both on the same node), but maybe it wouldn't be as good a solution if you wanted them spread out (in which case it might be better if they were 2 separate nodes).


When translating a node, can I avoid copying the default value from the original language

Unset the field values in a hook_ENTITY_TYPE_translation_create:

use Drupal\node\NodeInterface;

/**
 * Implements hook_ENTITY_TYPE_translation_create().
 */
function mymodule_node_translation_create(Nodeinterface $translation) {
  if ($translation->getType() == 'product') {
    unset($translation->body);
  }
}


I was missing the File Entity module. Installed it and was good to go.

Also, was having trouble when using normal json format. Switched to hal_json and that got it.

It's also worth noting that using Base64.encode is unnecessary because FileReader does that for you. Also, you need to split off the file type from the returned data string, otherwise the file will be corrupted when you go to upload it.


Disqus include causing Bad Gateway errors

It looks like the API was undergoing maintenance which is why it was rejecting with a 5xx error. Here is the list of meanings to the HTTP response codes that Disqus uses:

http://disqus.com/api/docs/errors/


Node add form alter & submit custom field

Try this...

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

  if ($form_id == 'event_node_form') {

    global $user;
    $query = db_select('pricelist', 'p');
    $query->fields('p', array('pricelist_id', 'pricelist_name'));
    $query->condition('user_id', $user->uid);
    $results = $query->execute()->FetchAllKeyed(0,1);

    $results['_none'] = "-Select-";

    $query2 = db_select('field_data_field_pricelist', 'd');
    $query2->fields('d', array('field_pricelist_value'));
    $query2->condition('entity_id', $form['nid']['#value']);
    $results2 = $query2->execute()->fetchField();

    if(empty($results2)) {
      $results2['_none']="-Select-";
    }

    $form['field_pricelist'][LANGUAGE_NONE]['#options'] = $results;
    $form['field_pricelist'][LANGUAGE_NONE]['#default_value'] = $results2;

   // $form['#submit'][] = "TableManager_form_submit";  // No longer need of this function

  }

}


You can do it by PHP rule action,
first create a function in your custom module
as example

function _yourfuction_user_change pass($account,$pass){
    user_save($account,array('pass'=>$pass));
}

Then in your rule in action section select php action and in it's field
enter

 _yourfuction_user_change pass($account,'111111'); //your password=111111 and $account = available account parameter in field

and another solution is create your on action


You can inject the UrlGenerator as service and use UrlGenerator::generateFromRoute, but in the linked doc you are discouraged to do so:

  @internal Should not be used in user code. Use \Drupal\Core\Url
  instead.

So the code in your question to create an url object is OK for a service, but not the toString() method. Render the url only with this method when the page rendering process has started, for example in a theme.

In a service you usually don't know this and you should return an unrendered url object, so that it can be rendered later in the rendering pipeline.

$url = Url::fromRoute('<current>', [], ['absolute' => 'true']);

toString() in the wrong place generates ugly error messages about early rendering which are hard to debug when this happens somewhere in a service.


Cannot view individual article, instead the node's link displays all articles

I suggest that you first delete all (if you can, else just news) path aliases (via the pathauto interface). Get your view working as you like. Then regenerate the aliases (again via the pathauto admin interface). Keep things simple first and then proceed to complicate :)

If things persist, try with a test node type.


A couple of things to check:

Confirm you added the field to the right content type and save the changes
Make sure you added the field to right view "display" and save the changes
Clear the cache of the whole site
Make sure if you are using field permissions that they are properly set
If you are using a template file for the view make sure to add the new field.


Keep info in one place to be use in several locations

There really isn't a best practice. I'd say it depends on the intent and what part of Drupal's CMS functions best fit your scenario. For example:

Is it a part of distributed theme template? It could be a theme settings.
Is it a part of functional application logic? It could be a variable added to a site configuration form.

For most practical purposes of boilerplate phone info in a footer, I'd think most people would go for block with a region placed in the theme's footer, but Drupal is flexible by design so you could see alternative decisions depending on the intent.


Conditional Fields with multiple conditions

You can try the module Reference Option Limit

With this module you can try to make a reference.

The documentation of this modules is here

Documentation

Is a Great module, hope i can help you


Is there a way to programmatically alter a field's schema?

I believe you are looking for the API function hook_schema_alter.

Though you should also be aware that the Media module exists specifically to solve this particular problem in a much nicer way.


Call multiple hook inserts from different modules?

Rule of thumb: Don't call hook_anything() in other modules. :-)

If you call node_save($yourNode) then the node API will invoke hook_insert() in the module that implements that node type, if the node is being inserted. Otherwise hook_update() gets called for updates.

If you need to act on an insert for any type of node, and it sounds like you do, then you want to implement hook_nodeapi().

Examples has a node project and a nodeAPI project, so you can figure out which you need.


Banner block (referenced by url) not displayed when using language extensions

You may want to check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.


How do I add embedded YouTube videos in a field?

Just use the Video Filter module, here is a quote from its project page:

This is a highly flexible and easily extendable filter module to embed any type of video in your site using a simple token. Other modules can add video sites/formats (called codecs) using an easy plugin architecture.
With WYSIWYG installed, you can use the Video Filter button to easily add videos in a rich text editor.


With the help of 4k4, I could solve my problem... I will start by explain my first try, which could be a good solution in some cases, then I will explain/show how I finally end up.

Firstly I created my computed field in hook_entity_base_field_info_alter [Note that this is not a pseudo field this time]

function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
    if ($entity_type->id() === "node") {
      ...field is created here... will show you how to after
    }
}

Secondly, we need to create a class (that will perform the calculation) for the computed field (will show you after)

Thirdly, we can display this field in a view simply by implementing hook_views_data_alter... This is the beauty of this solution: the view integration is made very quickly. Here is the how the hook is implemented

function my_module_views_data_alter(array &$data) {
  $data['node']['my_computed_field'] = [
    'title' => t('My computed field'),
    'field' => [
      'id' => 'field',
      'default_formatter' => 'string',
      'field_name' => 'my_computed_field',
    ],
  ];
}

What was not good in my case, is the fact that my computed field does appears in all bundles (even if I use setTargetBundle('my_bundle') like showed below).

Thus I changed a little bit my computed field process creation:

1-Create the computed field in hook_entity_bundle_field_info_alter ... not in _entity_base_field_info_alter (As you can see, it is a float field... youn could use a string)

function my_module_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if ($entity_type->id() == 'node' && $bundle == 'my_bundle' ) {
        $fields['my_computed_field'] = BaseFieldDefinition::create('float')
        ->setName('my_computed_field')
        ->setLabel(t('Nombre de litres total'))
        ->setComputed(TRUE)
        ->setTargetEntityTypeId('node')
        ->setTargetBundle('my_bundle')
        ->setClass('\Drupal\my_module\MyComputedFieldItemList')
        ->setDisplayOptions('view', [
            'type' => 'float',
            'weight' => 0,
        ])
        ->setDisplayConfigurable('view', TRUE);
    }

}

Note: if someone know the purpose of ->setTargetBundle('my_bundle') I would be glad to read anything on it as I added it without knowing if it is mandatory/usefull.

2-Extend FieldItemList (MyComputedFieldItemList) [use the same name as in ->setClass('\Drupal\my_module\MyComputedFieldItemList')]

The main point here is the protected function computeValue that will use $node to compute the value.

<?php
namespace Drupal\my_module;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * Item list for a computed field that displays the total liter for a soup.
 *
 */
class MyComputedFieldItemList extends FieldItemList
{

    /**
     *
     * {@inheritdoc}
     */
    use ComputedItemListTrait;

    protected function computeValue()
    {
        $node = $this->getEntity();
        if (! $node->isNew()) {
            $this->list[0] = $this->createItem(0, my_module_function_to_compute($node));
        }
    }
}

At this stage, you have a computed field that you can display in "my_bundle"... Lets go to the view integration

3-Alter hook_views_data_alter to tell views that you have a new computed field linked to a node. The main point here is the id my_computed_field

function my_module_views_data_alter(&$data)
{
    $data['node']['my_computed_field'] = array(
        'title' => t('My computed result'),
        'group' => t('Content'),
        'field' => array(
            'title' => t('My computed result'),
            'help' => t('bla bla.'),
            'id' => 'my_computed_field',
        ),
    );
}

4-Thanks to 4k4, I understood that you need to create a plugin class that will have a render function to show the result in the view. The second important thing here is the @ViewsField("my_computed_field") annotation that needs to be the same as the id in step 3

<?php
/**
 * @file
 * Definition of Drupal\my_module\Plugin\views\field\ComputeField
 */

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Field handler to flag the node type.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_computed_field")
 */
class ComputeField extends FieldPluginBase {

    /**
     * @{inheritdoc}
     */
    public function query() {
        // Leave empty to avoid a query on this field.
    }

    /**
     * @{inheritdoc}
     */
    public function render(ResultRow $values) {
        $node = $values->_entity;
        if ($node->bundle() == 'my_bundle') {
            return my_module_function_to_compute($node);
        }
    }
}

Now, everything runs fine:

The field could be displayed (or not) in any display mode and you can change the settings in the UI as any regular field
The field could be inserted in a node view
There is a function my_module_function_to_compute($node) that you can put in your module. This function will compute the result of your field with the entity as argument (node here)

One thing is missing: the sort (in the view) doesn't work... I have to dig into it


drupal facebook autopost working but post are not visible to public

You need to take your app out of development mode and make it live to the public. All of your previous posts will then appear to their appropriate audiences (and so will future posts).

You can do this by going to https://developers.facebook.com, going to your app's dashboard, then to App Review. At the top there is a Yes/No field for "Make app public?" Set it to yes.


How to exclude multiple nodes based on their ID in taxonomy term view?

Add more than one ID Filter

You can simply solve it by adding as many Content: ID Filters as you need, each excluding only one node. As you already know set the Operator to Is not equal to and enter one value, then add another Content: ID Filter and so on for all the nodes you need to exlude.

Use Regular expression

Or you can use the Operator Regular expression in a single Content: ID Filter. This way you can use a regex pattern that matches all the ID numbers you want to exclude.

For example the expression (2[45]) matches two numbers, 24 and 25, so those two nodes would be filtered and shown in results.

In your case you need to exclude some numbers, so you would have to have a regex that excludes. That is a bit out of scope for this question so I won't go into it. There are online regex generators you can use to help you construct the expression, but I expect it would take some time, regex is notorious for being complex and mind-boggling.

For whole range of numbers take a look at this tool: Regex Numeric Range Generator. Don't forget you need to modify the expression to exclude the list!


Cannot update modules with drush – needs higher bootstrap level

Finally I found an answer that I could adapt to my WAMP environment here. I simply added C:\wamp\bin\mysql\mysql5.7.14\bin to the PATH, and then Drush worked also for updates.


Is there a drupal 7 equivalent to the Country Ban module?

this module may help you : Smart IP ,,,,

  Overview Smart IP identify visitor's geographical location
  (longitude/latitude), country, region, city and postal code based on
  the IP address of the user. These information will be stored at
  session variable ($_SESSION) with array key 'smart_ip' and Drupal
  $user->data object with array key 'geoip_location' of the user but
  optionally it can be disabled (by role) .....


How to add Cancel button to Batch operation?

There is no good way to interrupt a batch process, afaik. There used to be a hackish trick in Drupal 6 though, see http://drupal.org/node/894222. Maybe if you can figure out how that worked, you can make Drupal 7 do the same.


Use selected NID from Entity Reference field to populate second Entity Reference field

My solution is to:

Pre-populate and disable the first entity reference field with a node ID
Add an extra path component with the same nid and have the second field use an entity reference view with default: Path Component 4

So the URL looks like /node/add/hacky/123?field_solution=123.

While hacky, it has uses, especially if you want to filter fields that don't have a connection. In that case the URL could be /node/add/hacky/123/456?field_solution=789.


How can I create Menu items through hook_install()?

You can use hook_menu_links_discovered_alter() to modify or add additional links to those provided in *.menu.links.yml files, but these types of links are not completely editable (e.g. you can not change their title in the UI).

If your links are content based, need to be completely editable later through the UI, or are being placed in a custom menu you can directly create the menu link entities:

MenuLinkContent::create([
  'title'      => 'My internal link from a route name',
  'link'       => ['uri' => 'route:myroute'],
  'menu_name'  => 'my-menu',
])->save();

Also check out the Entity API documentation, and Working with the Entity API for more information.


No, Drupal isn't making a single DB call per checkbox - that would be suicide :)

Looking at user_role_permissions() should de-mystify the whole thing...all enabled permissions for the given roles (or all roles if none are provided), are lazy-loaded into memory when they're needed, and statically cached for the same request.

It's about as efficient as it can possibly be when you consider how Drupal's permission system works - I doubt you'll be able to squeeze anything more out of it that wouldn't be considered pointless micro-optimising.

As an aside 50 roles is a lot. I've never seen a site with anywhere near that many; if you can reduce the number of those, you'll be doing yourself a great service.


wysiwyg + ckeditor - failed to open stream sites/default/files/js/wysiwyg/wysiwyg_ckeditor_XXX.js

This bug should be fixed in the latest dev snapshot of wysiwyg:

See also http://drupal.org/node/1802394 (which essentially provides a patch for the previous response above).


Views related content based same term names in different vocabulary

First option (doesn't work as expected though):

You should be able to do that, by doing the following in your contextual filter:

Check the "Specify validation criteria" option.
Select "Taxonomy term" as "Validator".
Select "Term name" as "Filter value type".

I just tried this however and it returns only one result, which is not what you need.

Alternative (this one was tested and works):

You can create a View of Taxonomy Terms, and then use a "Taxonomy term: Name" contextual filter.
Afterwards, you can add a relationship to your tagged nodes, using the "Taxonomy term: Content with term" relationship.

That way, you can get all the content tagged with a specific term name, even if the term name belongs to different taxonomies.

Here is a sample View configuration:

and a sample result-set with "ManU" used as a contextual filter:

Good luck!


Hook_views_query_alter: adding condition with entity reference value

This comment save my life!
https://api.drupal.org/comment/49458#comment-49458

  Be careful to add the table, even if You added the field in the view
  UI :

I added

$view->query->add_table("field_data_field_installatori_reference");

and then I could access to my field:

$view->query->add_where(1, "field_data_field_installatori_reference.field_installatori_reference_target_id", $user->uid, '!=');


How to display a block with menu child items programmatically?

I found the answer based in this question: How to turn a menu tree into an associative array?

You can use each array element as a item of MenuLinkInterface

To see others parameters check the class MenuTreeParameters

<?php
/**
 * @file
 * Contains \Drupal\YOUR_MODULE\Plugin\Block\SectionsFooter.
 */

namespace Drupal\YOUR_MODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;

/**
 * Provides a 'SectionsFooter' block.
 *
 * @Block(
 *   id = "sections_footer",
 *   admin_label = @Translation("Sections"),
 *   category = @Translation("YOUR_MODULE")
 * )
 */
class SectionsFooter extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(0);
    //Delete comments to have only enabled links
    //$parameters->onlyEnabledLinks();

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $list = [];

    foreach ($tree as $item) {
      $title = $item->link->getTitle();
      $url = $item->link->getUrlObject();
      $list[] = Link::fromTextAndUrl($title, $url);
    }

    $output['sections'] = array(
    '#theme' => 'item_list',
    '#items' => $list,
    );
    return $output;
  }
}

References:

Menu tree building is now a service


How do I create product and product display once, like in Commerce Kickstart?

This is through the contributed module Inline Entity Form.


Using hook_entity_view, you can insert the view into the field's build array.

function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'example_content_type' && $view_mode == 'full') {
    $node_id = \Drupal::routeMatch()->getRawParameter('node');
    $index = 0;
    foreach($build['field_paragraph_field'] as $key => $value) {

      if (is_numeric($key) && $value['#paragraph']->bundle() == 'body') {
        $news_view = [
          '#type' => 'view',
          '#name' => 'my_news_feed',
          '#display_id' => 'block_1',
          '#arguments' => [$node_id],
        ];

        array_splice($build['field_paragraph_field'], $index + 1, 0, [$news_view]);

      }
      $index++;
    }
  }

}


How can I prevent cache on any page where a paragraph appears?

You probably want to be really heavy handed and use \Drupal::service('page_cache_kill_switch')->trigger();
If you put that in a custom module in hook_entity_view_alter() then you can add a conditional that fires it when your paragraph entity is being built.


Generate file path for created file so it can be downloaded

/tmp is outside of webroot so apache (or whatever) can't serve files from there.

You have 2 options:

Move the file from /tmp to your public files directory. This will mean anyone will have access to it (if they know the url). See file_unmanaged_move().

Eg.

$source = '/tmp/my_file.csv';
$destination = 'public://csv/my_file.csv';
file_unmanaged_move($source, $destination);

Stream the file to the browser via php. This means only people who can access your php script can get access to the file.

Eg.

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=my_file.csv');
return readfile('/tmp/my_file.csv');


Apachesolr search results Facet Filter by date range

If i clearly understand you will have to use facets date.

And using Solr there's a issue where you cannot do multiple facets on the same field in the same query... This issue is now marked as fixed Solr backlog but the release is not ready yet i believe last time i checked. In my case since the fixed was not ready i created in the schema new field that are copyfields and i do the appropriate query.

Therefore you will have something like that :

Last hour

f.date1.facet.range.start=NOW-1HOUR&f.date1.facet.range.end=NOW&f.date1.facet.range.gap=+1HOUR&

Last 24 hours

f.date2.facet.range.start=NOW-24HOUR&f.date2.facet.range.end=NOW&f.date2.facet.range.gap=+24HOUR&

Last 48 hours

f.date3.facet.range.start=NOW-48HOUR&f.date3.facet.range.end=NOW&f.date3.facet.range.gap=+48HOUR&

Last Week

f.date4.facet.range.start=NOW-7DAY&f.date4.facet.range.end=NOW&f.date4.facet.range.gap=+7DAY&

facet.range=date&facet.range=date2&facet.range=date3&facet.range=date4

Hi hope that helps you!!! Cuz i've look so long to figured out myself ;)


Programmatically delete one entry from one field on one entity

If you're able to rely on the entity API module you should be able to use code similar to the following:

// Load some entity.
$entity = entity_load_single($entity_type, $id);

// Remove the field value.
unset($entity->field_FIELD_NAME[LANGUAGE_NONE][$index]);

// Reset the array to zero-based sequential keys.
$entity->field_FIELD_NAME[LANGUAGE_NONE] = array_values($entity->field_FIELD_NAME[LANGUAGE_NONE]);

// Save the entity.
entity_save($entity_type, $entity);


How to get Entity Reference Autocomplete results to display in a table?

The first thing thats jumps out at me is that you have "Referencing Entity" rather than "Referenced Entity" in your views relationship.

Because you are showing  a view of content with the field, you are already showing the referencing entity. What you want is a relationship to the referenced entities.

Have you also got the views block to display on the correct content type?

You have the correct contextual filter set up (you can use "get content id from url" rather than raw value).

Make sure the block is shown in a region on all of the referencing entities content type.


Converting a Project from D6 to D7 using Drush in localhost?

Drush Site Upgrade 7.x-2.x is for upgrading FROM Drupal 6 sites TO Drupal 7 sites.  I know that the version numbering is a bit confusing, but it is based on the fact that the Current version of Drush is 7.x-5.x.  This version of Drush supports both Drupal 6 and Drupal 7, but is versioned 7.x to match the most recent stable version of Drupal supported.  Similarly, Drush Site Upgrade is versioned 7.x to match the version of Drush that it works with.  I added a sentence to the Drush Site Upgrade homepage to clarify that it is for D6 -> D7 upgrades; the README.txt already explains this.

As for a step-by-step guide to using Drush Site Upgrade, please understand that the Drush Site Upgrade command itself is a step-by-step guide to upgrading your Drupal site.  This command will print out an explanation of what it is about to do at every step, and then prompt you before taking action.  Run with the --always-prompt flag when you're first getting started to insure that absolutely everything will be prompted.  If there is a step that is not applicable, or does not work right for your environment, you can tell Drush sup to skip the step, you can do the operation(s) you need to by hand, and Drush sup can continue the upgrade process on the next step.  If something goes horribly wrong, you can always start over from the beginning and try again.

As you inferred, Drush Site Upgrade will not actually upgrade the code of your custom modules to D7.  For help with that, please see http://upgrade.boombatower.com/.


Convert exposed dropdown filter to links Drupal Views

You can use something like this:

Add a contextual filter to your view for 'Content:created year"

Add a Header Global Text Area (Full HTML) with this in it:

2012

2013

2014

2015

by-date is my view's path. Yours will be different.

Style it.

Looks like this without styling:

If you don't want a contextual filter you could create your date links with a query parameter like this:

by-date?date-filter=2015

Then use a views hook to read the query paramter and add the filter in code.


Getting node user view permissions (Nodeaccess)

I am not sure if I fully understand your question but this is what I make out of it: you want to check if a certain user has access to a certain node, am I right?

If this is the case, this can easily be achieved with the following code:

// Use this if you want to load the current user.
global $user;
// Use this if you want to load a user by UID.
$user = user_load($uid);
// Load the node object.
$node = node_load($nid);
// Perform the access check.
if (node_access('view', $node, $user)) {
  // The user has permission.
}

You can read more about node_access in the Drupal docs.


newly created fields values are not loaded with node_load

Oops.

All my values are there. I was fooled by output, reading values from wrong nodes. I have complex loops here pulling out nodes so i was fooled.

How trivial :(


How to define text css style in my themes folder to work with wysiwyg editor?

i usually add a separate .css file for the editors, this is only possible via the WYSIWYG module, in the settings of that text-format.
you can even add special classes and block-formats the user can choose then.

to see what's happening, you can inspect the editor normally in your browser, and should see the problem.


View is rendered as "empty" even though the query returns results

This might work:

Goto Query Settings under Advanced options and disable SQL rewriting.

OR

Try providing the view a default value for the contextual filter under "When filter value is not available option."


How to get links of translated node edit page in the secondary tabs

Add a derivative for each language:

/mymodule/src/Plugin/Derivative/TranslatedNodeTabDeriver.php

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class TranslatedNodeTabDeriver extends DeriverBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];
    foreach (\Drupal::languageManager()->getLanguages() as $language) {
      $lang_id = $language->getId();
      $this->derivatives[$lang_id] = $base_plugin_definition;
      $this->derivatives[$lang_id]['title'] = $this->t('Translate @language', ['@language' => $language->getName()]);
    }
    return $this->derivatives;
  }

}

and then you can get the language id with $this->getDerivativeId() in the plugin class:

/mymodule/src/Plugin/Menu/TranslatedNodeTab.php

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class TranslatedNodeTab extends LocalTaskDefault {

  /**
   * {@inheritdoc}
   */
  public function getOptions(RouteMatchInterface $route_match) {
    $options = parent::getOptions($route_match);
    $options['language'] = \Drupal::languageManager()->getLanguage($this->getDerivativeId());
    return $options;
  }

}

/mymodule/mymodule.links.task.yml

translated_node_tabs:
  class: Drupal\mymodule\Plugin\Menu\TranslatedNodeTab
  deriver: Drupal\mymodule\Plugin\Derivative\TranslatedNodeTabDeriver
  base_route: entity.node.canonical
  route_name: entity.node.edit_form


You can create tpl for the menu and render the content and design tpl as required or create tpl for the content type in theme


I'm not sure I understand your problem ... Are we talking about like a node/edit page or a View? Or is this a menu page callback where you want node(s) and this entity both with paged output on a single html page ... ?

If you have written custom PHP/SQL/EFQ in a menu page callback, I see no reason you cannot explicitly set $element uniquely as needed in your queries.

Where is your http page query parameter coming from? A view? A url() you created by hand? If you have 2 pagers, you should have 2 $GET parameters ...

Edit: this is what I mean blog example


How to theme field for many views in drupal 7?

If you want to use template file, you can do that with: views-view--[view name]--[display].tpl.php

If your view name is "My product Image" and display is "block"

view mashine name will be: "my_product_image"

and your template file will be:

views-view--my-product-image--block.tpl.php

in this file you can get your fields in that way:

$fields = $view->style_plugin->rendered_fields; // fields array

and then customize fields with the foreach loop.

Example:

<?php foreach ($fields as $delta => $item): ?>
    <?php if ($item['uri']) : ?>
        <img src="<?php print $item['uri']; ?>" alt="" class="pull-left">
    <?php endif; ?>
<?php endforeach; ?>

Of course there are several ways to custom your image field. In this example I assuming that you need to do that in view template file.


Add a field Content: Path This would add another token which would be the aliased path of the node you can use that.

Please note that to use a token with in view the field should be above the field being used.

By the if you just want to Link the Title to its node then you can simply tick "Link this field to the original piece of content" This would link it to the article that the Title points to with the aliased url


How to apply image style in a views-view-fields--[view]--[machine-name].html.twig

Welcome to Drupal Answers!

You can try something like below in your for loop:

{% set image = {
    '#theme':      'image_style',
    '#style_name': 'your_image_style_name',
    '#uri':        image.entity.uri,
    '#alt':        image.alt
   }
%}

then render the image as {{ image }} without img tag as it is rendered along with img tag.


How to make use of Devel debugging functions on large or complex objects

The first problem can temporarily get fixed by changing the max array/object levels Kint will go deep. Currently this still has to be done by changing one line of code in the module. Though there already is an issue https://www.drupal.org/node/2405179 to make this a configurable setting.

In devel/kint/kint/config.default.php change 7 to any number you are fine with. I usually set it to 4.

/** @var int max array/object levels to go deep, if zero no limits are applied */
$_kintSettings['maxLevels'] = 7;

Remember that this number will get reset as soon as you update the Devel module.

Update: Now I found this beautiful snippet to simply be placed in your settings(.local).php. No hacking or patches needed.

// Change kint maxLevels setting:
include_once(DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php');
if (class_exists('Kint')) {
  // Set the maxlevels to prevent out-of-memory.
  Kint::$maxLevels = 4;
}


How does a module tell Drupal which mail plugin should be used?

Basing on Mail backends are now annotated plugins, drupal_mail_service() has been removed and the documentation for the MailManagerInterface interface, a module implementing a mail plugin should not set its own plugin as default plugin because MailManagerInterface interface doesn't document any configuration key the classes implementing it should use; only the site maintainer eventually know which mail manager is being used, and which configuration keys that mail manager is using. This is similar to setting the cache handlers, which is done in the settings.php file.

The SMTP Authentication module is doing the correct thing when it doesn't set its plugin as default plugin for sending emails.

As for the code to send a test email, the correct one should not directly set the configuration keys, if it wants to be independent from the current implementation of the mail manager. Eventually, code similar to the following should be used.

$mailer = \Drupal::service('plugin.manager.mail')->createInstance($plugin_id);
$bool = $mailer->send($mailer->format($message));


Getting wrong output after implemented `theme_item_list`

Your code is wrong, since the items to render are in $variables['items'] not $variables as evident in theme_list_items().

function theme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];

  // Omissis
}

You are confusing what the theme function gets in Drupal 7 with what the same theme function gets in Drupal 6.

In general, in Drupal 7 what the theme functions need to render is always an index of the array $variables passed them; they never use $variables directly like your code does.

function theme_table($variables) {
  $header = $variables['header'];
  $rows = $variables['rows'];
  $attributes = $variables['attributes'];
  $caption = $variables['caption'];
  $colgroups = $variables['colgroups'];
  $sticky = $variables['sticky'];
  $empty = $variables['empty'];

  // Add sticky headers, if applicable.
  if (count($header) && $sticky) {
    drupal_add_js('misc/tableheader.js');
    // Add 'sticky-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
    $attributes['class'][] = 'sticky-enabled';
  }

  $output = '<table' . drupal_attributes($attributes) . ">\n";

  if (isset($caption)) {
    $output .= '<caption>' . $caption . "</caption>\n";
  }

  // Omissis
}


Views field strips out
 tag. To add background image you need to follow below steps:

Add global custom field into view header and put below code.

Now assign background-img class to  Global :Custom text field like

.

{{ field_social }}
{{ title}}
{{ field_profession_team }}

  Note: Use Global Text Area in view header and select an input filter
  where html tags aren't limited i.e. full html text format


Why should it change (drastically) -- it embraces a base of HTML5 markup; anything beyond that essentially becomes business need, accessibility requirements or simply put designer preference on what clean and simple means to them.

Mobile Initiative
Design Initiaive
HTML5 Initiative

From HTML5 Initiative page

  We want to ensure we're spending our time implementing features that will directly benefit Drupal's user base the most. As part of this initiative we'll focus mostly on:

  Adding support for the new form elements to Drupal's Form API.
  Adding new semantic elements in core templates in an appropriate way.
  Adding ARIA roles to markup to improve accessibility.
  Simplifying style and script elements.
  Ensuring input filters and functions accept HTML5
  elements.

Does the above goals mean that Drupal 8 HTML markup will be as lean turning on Fences in Drupal 7 and nuking all built-in markup? No, will the base markup be too complex, hardly. It will be designed to meet most peoples needs.


What does the outbound path processor do?

Inbound path processing is used for incoming requests to the site. Outbound path processing is used when generating URL's, doesn't matter if it is outside of the site or not, in fact it would be very uncommon to use it for those kind of links.

The most obvious example is language negotation path prefix/domain, on an incoming request to en/node/1, inbound path processing removes "en" and sets the current language to english, when generating a linke to "node/1", path outbound processing adds the en/ prefix based on the current or provided language.


Find top and average value from input field text

The PHP function strtotime() might help you here:

  strtotime — Parse about any English textual datetime description into a Unix timestamp

For example, you could create a computed field and use that function to convert the text input to a time value.

But as you're using a text field and not a date/time filed, I doubt that you'll be able to get all values correctly (because user input can differ enormously).


Access EntityEmbedFilter process function in a preprocessor

Considering letting Drupal do the work for you. Instead of calling things yourself, just let Drupal render it for you using a specific text format, which is configured to use entity embed.

See how check_markup() works, you could call that, but since you seem to be in a context where you want a render array anyway, just do what it does and use #type processed_text with #type and #format.

If that is for some reason not possible, then you need to mark the resulting object as a safe string by wrapping it with an object that implements MarkupInterface, for example with Markup::create() although that is marked as internal.


Use '+' to separate the tags instead of ','. The '+' is used for "OR" while the ',' is used for "AND".

Here is a screenshot from the Views administrative interface:


how should i send data form my custom module to a php file after submitting?

If all you are doing in your submit handler is redirecting to result.php then you should instead make your form submit direct to there, so that all the form post values will be available in the $_POST global variable in result.php.

To do so, in your my_module_my_form() function add this:

$form['#action'] = '/result.php'

Edit:

As Clive has pointed out, you cannot post that field value as you currently have it because it is a disabled field.

To make that field post you either have to make it not disabled, or if you don't want the user to be able to edit it you can use a different field type.

You can use type value to pass a value straight through, however the user won't be able to see it before they submit as it is a type of hidden value.

If you want the user to be able to view the value but not change it you could have 2 fields, one disabled (or just an item field) one that the user can see but doesn't submit, and a second value type field that submits the value.


Change download directory when installing new modules using "Install from a URL"

Unfortunately I believe there is no way to change this in settings because there is no setting in the update module to change the installation path. If you check the update module configuration (admin/reports/updates/settings) there are fields regarding updating, but nothing regardig the installation path.

Even if you read the documentation (https://drupal.org/documentation/install/modules-themes/modules-7#using-drupal-interface) its never mentioned there. You would simply have to hack the core.

On the other hand, I recommend using drush (https://github.com/drush-ops/drush) with simple command (drush dl [module_name]) which does respect your contrib directory out of the box.


Get Plugin Definition methods using dependency injection

Create an instance and then use a method on the plugin instance, for example to execute the task, if you have such a method in the plugin class:

$task = \Drupal::service('plugin.manager.task')->createInstance('my_task');

$task->execute();


How to get the content moderation entity related to node entity in drupal 8.2.x?

i did it with entityQuery

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
 if ($form_id='node_article_edit_form')
  {
    $article=$form_state->getFormObject()->getEntity();
    //get the associated content moderation entity
    $id = Drupal::entityQuery('content_moderation_state')
       ->condition('content_entity_id', $article->id())
        ->execute();

    $stateEntities = Drupal::entityManager()
        ->getStorage('content_moderation_state')
        ->loadMultiple($id);
    $stateEntity=array_values($stateEntities)[0];
    $moderation_state = $stateEntity->get('moderation_state')->getString();
   }
 }


How do I disable a module when Drush or the GUI doesnt work?

If you have access to your database, you can do it through there.

You can see all the modules enabled with:

SELECT name,status FROM system WHERE type='module' AND status='1';

You can disable a module by setting it's status to 0.

UPDATE system SET status='0' WHERE name='module_name';

For more on uninstalling stuff via drupal's db.


How to cache a custom rest resource when using Url::fromUri

This is the answer:
Url::fromUri($var)->toString(TRUE)->getGeneratedUrl();

Found here: https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8


How can I create comment on node insert?

I guess you're hitting some edge case in \Drupal\comment\CommentStatistics::create(), which is called in comment_entity_insert(). The code assumes that there is no comment yet when that is called. Which is an assumption that you are breaking, probably because your module gets called first.

That's arguably a core bug, you could open a bug report and try to fix it there to do a merge query. That said, as a workaround, make sure that your hook is called later than comment. You will have to implement hook_entity_insert() instead of node as that is apparently called later (by default, hooks are stored by modules by weight, name, so C should be before N).

PS: You should enable verbose error logging and check the full backtrace of that error. That can often help with understanding what's going on.


JQuery hoverIntent / Drupal contrib hoverIntent module not working

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

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

Solution:

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


There's a hook for exposing custom fields to Views: hook_views_data()

  Describe table structure to Views.

  This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. This must either be in the same directory as the .module file or in a subdirectory named 'includes'.

  The full documentation for this hook is in the advanced help.

The link also includes example code.


In Drupal 7 Commerce 1.x - is there a way to include the price into the dropdown product select box?

Include the price in the product title itself in same way which you want to show in select box.

There are other way, in that you will have fetch the product id of the product reference field in template.php & load full product to get price. Then prepare title again at theme lavel..

For better understanding of what I am talking about, you can see my answer for a question here, where I have explained how to prepare title of node again which include taxonomy. You also have to do something similar like that..

But I will suggest you to follow the first solution of mine means - Include price with title of the product.


Check if entity reference field (user) contains current user

Check following code:

global $user;
$team_members = array();
foreach($current_node->field_team['und'] as $team){
$team_members[] = $team['target_id'];
}

if (in_array($user->uid, $team_members)) {
$output = 'some_specific_content';
} else {
$output = 'you are not a team member of this project';
}


Is there any way to add the social medial buttons in a field?

You can use the Link icon module.

  The Link icon module is a simple link field formatter to create icon
  classes based on a predefined set of link titles.

Or the Social field module

  The Social field module provides a field that allows you to collect
  links to social network profiles like facebook, twitter, googleplus,
  linkedin, etc. Links are shown as icons. Social field links are
  validated according to the patterns inserted in the module
  configuration.


You can make the page available for all users, also anonymous, and in the page callback redirect the anonymous user to your custom page.


when a button_field is presses, how do I access the node that owns the button?

I was trying to do something similar. It looks like as you can have button_field on any entity, you need to DEFINE what entity has button_field in your rules. It worked for me thinking like that.

What I mean is in your rules’ conditions section after checking ‘Clicked button comparison’ with your_button_field_name if you check ‘Entity is of type’ Node and ‘Content is of type’ Your_content_type, then all of the fields of your content type including nid will be available in Actions section under entity. Check out Using Button Field


newsletter with export email to csv and import from csv features

Here's how to do that:

Install Views (you probably have this installed already).
Install Views data export module.
Create a new view that will show either "Simplenews subscriber" or "Simplenews subscription".
Add a new display of "Data export" type to that view. There you can choose the format (.csv, .doc, .txt, etc.) and configure other settings. Don't forget to set "Attach to" value to the page display you created in step #3.


How to sort comments by a new field in the comment table?

The sort_comments.module checks if a special value is set to use its' ordering:

if (isset($orderby['torder'])) { /* ... */ }

You likely want to set an sql expression like they do for your own module.

Then in sort_comments.module they just set an SQL order by or leave the default ordering by comment_id (cid):

// ...
$orderby['c.thread'] = 'DESC';
} else {
   $orderby['c.cid'] = 'DESC';
}

You likely want to mimic this functionality in your own vesrion of hook_QUERY_TAG_alter, a specific version of hook_query_alter.


(How) can I Create products by the square foot?

There isn't a complete solution, but there's a start and an open issue to make it do exactly what you need. I wrote a Physical Fields module that defines a dimensions field you can use to collect the length and width via a line item field exposed to the Add to Cart form. The issue is the dimensions field right now only supports collecting all three dimensions: length, width, and height. It needs to be updated to support using a subset of the dimensions, and I've just updated the appropriate issue that you can follow here.

Once you have that field on your line item type and have exposed it to the Add to Cart form, customers will be able to specify their dimensions when they add the product to the cart. With this data in fields on the line item, you can then make calculations based on the value of the field using Rules (or a custom Rules action). You can create a new data value by multiplying the length times the width (should be possible in Rules) and then set the product price accordingly. In such a case, I'd probably make the price of the product be the "sq. ft." price and then just multiply that times the square footage I calculate.


Clean way of receiving image_dimensions after applying image_style

I found one solution, which does not look neat, but works:

$sizes = getimagesize(drupal_realpath(image_style_path('style', $imageURI)));


If you are using redis, wouldn't your cache bins not be controlled in the Drupal database anymore? You would therefore need to explicitly set the cache bin to use DrupalDatabaseCache so that it uses the Drupal database in settings.php.

Example:

$conf['cache_class_activity_dashboard_cache'] = 'DrupalDatabaseCache';

This is how it used to be done with Memcache... Redis should be the same, but check the README:

http://cgit.drupalcode.org/redis/tree/README.txt?h=7.x-3.x

It would explain why you can query this on your local machine, if you only have Redis configuration set for the remote environments running it. You are querying the database, but the cache is pulling from Redis.

This is for Memcache, but sheds more light on excluding certain cache, like cache_form - which remains in the database. https://www.drupal.org/node/1131468


Associating comments with special pages/module output

Well, I think you pretty much have the answer.

Handling comments without the help of the Node API would probably be a lot of work.

But if you don't need all the extra features the Node layer brings, you can try to apply the same method on an entity. The Reply module takes care of attaching comments to your entity type.

Again, it's more work than simply using a node to store each item comments section. Just use your callback function to load or create a node with a field storing the item ID (if it doesn't exist yet on the database).

You can then use drupal_goto('node/' . $nid, array(), 301) to redirect the user to the comments page.


Drupal 7 as an Oauth 2.0 and/or 1.0a provider

I think you should try http://drupal.org/sandbox/sadashiv/1857254 for google_oauth2  This module is yet is sandbox but you can give it a try.


How to merge more than one profile type within registration page?

If you create fields for one profile, you can also use the same fields for another profile type.

When making the fields for the second type, rather than make new ones use the "Already Existing" Field to select the already made fields from a drop-down list.

This way both roles will fill in the same Contact Information since they both used the same fields for the task.


Your callback function is wrong:

function my_module_menu(){
  $items['beneficiaire/commande'] = array(
    'page callback' => 'commande_view',
  );
  return $items;
}

function commande_view(){
  var_dump('test_view');
  exit();
}


Drupal 8.5 broken after simultaneously enabling many modules

In the Drupal Slack channel, it was suggested I should try disabling modules using drush, starting with Devel since that appeared to be where the problem was coming from.  After

# drush pm-uninstall devel
The following extensions will be uninstalled: devel, ds_devel
Do you really want to continue? (y/n): y
devel was successfully uninstalled.                 [ok]
ds_devel was successfully uninstalled.              [ok]

the site's user interface came back to life, and I was able to install all of the modules I had previously selected, including Devel and Display Suite Devel.

I strongly suspect what happened is the error that terminated the initial attempt to enable modules

Maximum execution time of 30 seconds exceeded in /web/spacecolonists/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php on line 1005

occrured in the middle of processing the Devel installation, which broke it.

This tells me that module installations are not done as a transaction:  If they were, the timeout error would have caused the database transaction to fail, resulting in a rollback that left the database in a stable, working state.


Changing article text and summary with template_preprocess_node()

I believe that the node has already been rendered by the time template_preprocess_node() is called so changing any values on the node object will have no effect. You can try looking at $variables['node']->content to see if you can modify the text in that (I think this is the full HTML rendered node though, so lots of extra text/markup to deal with here).

You're probably better off using hook_node_load() instead. This gives you a chance to alter the node object directly before it gets rendered.